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 |
|---|---|---|---|---|---|
This is the first of the series of programs I wish to write to help myself get a handle on C#.
ObjectiveTo compare and contrast C# and Java, using a Unix style utility for numbering source codes. Target AudienceJava programmers wanting to familiarize with C#. SummaryThis is the first of the series of programs I wish to write to help myself get a handle on C#. This series should also help my peer Java programmers to get a few insights of C#.OverviewThe LineNum is a line numbering utility I wrote to help me add line numbers in source codes, accompanying the articles I plan to write. The Java version of this utility is poratble across diffrent operating systems like Linux and Solaris. Though C# and the .NET framework are theoritically platform independent, but as of now I do not know how to run it on Linux or Solaris. The line numbered source codes of Java and C# are provided in Appendix A and B, respectively. You might want to spend some time, at this point, to glance through the source codes. Some of the diffrences you will note is that the method names in C#, conventionally begin with an upper case. It is not illegal in C# to begin a method name with lower case, neither it is illegal in Java to begin a method name with uppercase character. These are however, matter of conventions. C# have many new syntax and semantic structures, these I have avoided to use in this example. I have not used get and set syntax of C# to define properties to keep the code comparison simple.DesignThe LineNum is a simple Unix sytle utility. It has a fine grain structure, that is, the classes and methods have been isolated functionality, even to the extent that some methods are one line long. The fine grain designs often sacrifice speed efficiencies in favour of reusability and source readibility. This utility has a two pass design. The first pass calculates the number of lines, hence the maximum padding zeros required. The second pass prints the zero padded line numbered input source files, to the standard output device. Diffrences & SimilesTo aid comparison between Java and C# versions of the program, I have kept the design, algorithm, and as far as possible, the method names similar. The C# is more object oriented, in the sense that you can even use methods in atomic types like integers, see line number 72 of the LineNum.cs listing in Appendix B. the string is an alias for System.String of C# API. Java also provides a special treatment to String objects.To accomodate strings, the Java language designers even flouted their own rule of not allowing operator overloading. The diffrences between LineNum.java and LineNum.cs are few and suttle. Given below are the names and line numbers of the classes used in implementing the utility.
Class Name
C# Lines
Java Lines
Notes
LineNum
54 to 84
56 to 85
The Main util class, having all static methods.
Padder
86 to 108
90 to 110
Helper Class to pad zero to line numbers.
LineCount
110 to 129
115 to 134
Helper Class to find maximum lines in the file.The method maps between Java and C#, used in the LineNum utility, are given below.
Java Methods
C# Methods
Notes
System.exit
Environment.Exit
Static method to exit the programs with a return value.
BufferedReader
StreamReader
A reader class containing ReadLine method.
StringBuffer
StringBuilder
String builder class
System.out.println
System.Console.WriteLine
printf subset of 'C' method.
import
using
syntax for including packages or namespaces.
package
namespace
disambiguates the classes and separates them.
"hello".length()
"hello".Length
String method length is implemented as property in C#ConclusionC# are Java are similar; Yet, as of now, Java has number of advantages over C#. The first is the portability and availability of Java on most of the popular platforms. However, C# has all the advantages of Visual J++, and may be useful for Java programmers to view it as next generation J++. C# also have some cool syntax and semantics introduced. And as noted above, it is more object oriented in treatment of basic types by char and int. However, in spite of the claim by Microsoft that C# is a direct descendent of C++, I feel it is more closer to Java than C++, since Java too was derived from C++. The most missed features of C++ in Java are missing in C# too. Namely the features of multiple inheritance and generic typing called templates are missing in C#. Just a thought that the '#' character of C# could have been inspired by shifting the second '+' symbol of J++ a little down and telescoping it with the first '+' symbol!AppendixSorry for lack of comments in the source codes. However, I tried to keep the method names friendly. I also apologize for the rather longish license, can't help it. DisclaimerThe source codes listed here are for explaining and analyzing the underlying designs only. No warranty claims are made by the author, they may contain bugs or by using them commercially you might be violating copyrights or patents. You may use the ideas and codes presented here at your own risk. Appendix AThis appendix lists the source code of LineNum.java. I wrote this Unix style utility for generating line numbers for the source codes to be included in programmer's introspection articles and peer review studies. The source code listings exhibited here, including this one, make use of this utility to generate line numbers. The file LineNum.java contains three classes, the first one is the class LineNum [lines: 56 to 86] itself. It is a two pass line numbering utility. It is a utility design pattern class, containing all static methods. The design is finely granuled in terms of functionality, that is each logical function is isolated either in a static method or an independent helper class. The static method main [lines: 59 to 70] , of the LineNum class, is called by the loader, which in turn opens the source input file to generate the line numbered output, in the example given below it numbers it's own source code! Using the helper class LineCount [lines: 115 to 134] and the static method maxPadCount [lines: 74 to 75], the utility calculates the maximum padding required. Thereafter, in the second pass, it uses the static method numGen [lines: 78 to 85] to generate the line numbered text to standard output. The numGen static method uses the helper class Padder [lines: 90 to 110] to generate the zero padded line numbers. To Compilejavac LineNum.javaTo Executejava LineNum LineNum.java > out.txtListing of LineNum.java follows:
001
001 /**002 *003 * @author Ashish Banerjee , 5-may-2001004 */ 005 /*006 (c) Osprey Software Technology P. Ltd., 2001, All rights reserved.007 ===========================================================================009 The Osprey Open Source Software License, Version 1.1010 (Adapted from Apache Software License, V 1.1 [])011 ===========================================================================012 013 Redistribution and use in source and binary forms, with or without modifica-014 tion, are permitted provided that the following conditions are met:015 016 1. Redistributions of source code must retain the above copyright notice,017 this list of conditions and the following disclaimer.018 019 2. Redistributions in binary form must reproduce the above copyright notice,020 this list of conditions and the following disclaimer in the documentation021 and/or other materials provided with the distribution.022 023 3. The end-user documentation included with the redistribution, if any, must024 include the following acknowledgment: "This product includes software025 developed by the Osprey Software Technology P. Ltd. ()."026 Alternately, this acknowledgment may appear in the software itself, if027 and wherever such third-party acknowledgments normally appear.028 029 4. The names "Osprey" and "Osprey Software Technology" must not be used to030 endorse or promote products derived from this software without prior031 written permission. For written permission, please contact032 mail@ospreyindia.com.033 034 5. Products derived from this software may not be called "Osprey", nor may035 "Osprey" appear in their name, without prior written permission of the036 Osprey Software Technology.037 038 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,039 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND040 FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE041 OSPREY SOFTWARE TECHNOLOGY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,042 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU-043 DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS044 OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON045 ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT046 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF047 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 048 */049 using System;050 using System.IO;051 using System.Text;052 053 namespace com.ospreyindia.util {054 public class LineNum {055 private LineNum() {} // no instance allowd056 057 public static void Main(string[] args) {058 if(args.Length != 1) {059 Console.WriteLine("LineNum <C# source file>"); 060 Environment.Exit(1);061 }062 LineCount cnt = new LineCount(args[0]);063 int max = MaxPadCount(cnt.GetLines());064 065 StreamReader rdr = new StreamReader(new FileStream(args[0], FileMode.Open));066 NumGen(max, rdr);067 rdr.Close();068 069 070 } // END Main071 public static int MaxPadCount(int lines) {072 return lines.ToString().Length;073 }074 /** generates line numbers and outputs to standard out (stdio)*/075 public static void NumGen(int max, StreamReader inr) {076 string ln;077 Padder pad = new Padder('0', max);078 int cnt = 0;079 while((ln = inr.ReadLine()) != null)080 Console.WriteLine((pad.Pad(++cnt)+" "+ln));081 }082 083 084 } // END class LineNum085 086 public class Padder {087 public Padder(char padChar, int maxPad) {088 this.maxPad = maxPad;089 StringBuilder buf = new StringBuilder(maxPad);090 for(int i=0; i < maxPad;i++)091 buf.Append(padChar);092 093 pads = buf.ToString();094 }095 public string Pad(int inp) {096 return Pad(inp.ToString());097 }098 public string Pad(string inp) {099 string ret = inp; 100 if((inp != null) && (inp.Length < maxPad)) {101 ret = pads.Substring(0,(maxPad - inp.Length)) + inp;102 }103 104 return ret;105 }106 private int maxPad;107 private string pads;108 } // END class Padder109 110 public class LineCount {111 public LineCount(string fileName) {112 fname = fileName;113 }114 115 public int GetLines() {116 StreamReader rdr = new StreamReader(new FileStreamfname,FileMode.Open));117 int ret = 0;118 while(rdr.ReadLine() != null)119 ret++;120 rdr.Close();121 122 return ret;123 }124 125 private String fname;126 127 } // END class LineCount128 129 } // END namespace | http://www.c-sharpcorner.com/UploadFile/abanerjee/LineNumberingUtilityinCSnJava12052005063055AM/LineNumberingUtilityinCSnJava.aspx | crawl-002 | refinedweb | 1,781 | 56.76 |
Next article: Friday Q&A 2009-03-27: Objective-C Message Forwarding
Previous article: Friday Q&A 2009-03-13: Intro to the Objective-C Runtime
Tags: fridayqna objectivec!
Definitions
Before we get started on the mechanisms, we need to define our terms. A lot of people are kind of unclear on exactly what a "method" is versus a "message", for example, but this is critically important for understanding how the messaging system works at the low level.
- Method: an actual piece of code associated with a class, and which is given a particular name. Example:
- (int)meaning { return 42; }
- Message: a name and a set of parameters sent to an object. Example: sending "meaning" and no parameters to object
0x12345678.
- Selector: a particular way of representing the name of a message or method, represented as the type
SEL. Selectors are essentially just opaque strings that are managed so that simple pointer equality can be used to compare them, to allow for extra speed. (The implementation may be different, but that's essentially how they look on the outside.) Example:
@selector(meaning).
- Message send: the process of taking a message and finding and executing the appropriate method.
Methods
The next thing that we need to discuss is what exactly a method is at the machine level. From the definition, it's a piece of code given a name and associated with a particular class, but what does it actually end up creating in your application binary?
Methods end up being generated as straight C functions, with a couple of extra parameters. You probably know that
self is passed as an implicit parameter, which ends up being an explicit parameter. The lesser-known implicit parameter
_cmd (which holds the selector of the message being sent) is a second such implicit parameter. Writing a method like this:
- (int)foo:(NSString *)str { ...
int SomeClass_method_foo_(SomeClass *self, SEL _cmd, NSString *str) { ...
What, then, happens when we write some code like this?
int result = [obj foo:@"hello"];
int result = ((int (*)(id, SEL, NSString *))objc_msgSend)(obj, @selector(foo:), @"hello");
What that ridiculous piece of code after the equals sign does is take the
objc_msgSend function, defined as part of the Objective-C runtime, and cast it to a different type. Specifically, it casts it from a function that returns
id and takes
id,
SEL, and variable arguments after that to a function that matches the prototype of the method being invoked.
To put it another way, the compiler generates code that calls
objc_msgSend but with parameter and return value conventions matched to the method in question.
Messaging
A message send in code turns into a call to
objc_msgSend, so what does that do? The high-level answer should be fairly apparent. Since that's the only function call present, it must look up the appropriate method implementation and then call it. Calling is easy: it just needs to jump to the appropriate address. But how does it look it up?
The Objective-C header
runtime.h includes this as part of the (now opaque, legacy)
objc_class structure members:
struct objc_method_list **methodLists OBJC2_UNAVAILABLE;
struct objc_method_list { struct objc_method_list *obsolete OBJC2_UNAVAILABLE; int method_count OBJC2_UNAVAILABLE; #ifdef __LP64__ int space OBJC2_UNAVAILABLE; #endif /* variable length structure */ struct objc_method method_list[1] OBJC2_UNAVAILABLE; } OBJC2_UNAVAILABLE;
objc_methodstructs. That one is in turn defined as:
struct objc_method { SEL method_name OBJC2_UNAVAILABLE; char *method_types OBJC2_UNAVAILABLE; IMP method_imp OBJC2_UNAVAILABLE; } OBJC2_UNAVAILABLE;
So even though we're not supposed to touch these structs (don't worry, all the functionality for manipulating them is provided through functions in elsewhere in the header), we can still see what the runtime considers a method to be. It's a name (in the form of a selector), a string containing argument/return types (look up the
@encode directive for more information about this one), and an
IMP, which is just a function pointer:
typedef id (*IMP)(id, SEL, ...);
objc_msgSendhas to do is look up the class of the object you give it (available by just dereferencing it and obtaining the
isamember that all objects contain), get the class's method list, and search through the method list until a method with the right selector is found. If nothing is there, search the superclass's list, and so on up the hierarchy. Once the right method is found, jump to the IMP of method in question.
One more detail needs to be considered here. The above procedure would work but it would be extremely slow.
objc_msgSend only takes about a dozen CPU cycles to execute on the x86 architecture, which makes it clear that it's not going through this lengthy procedure every single time you call it. The clue to this is another
objc_class member:
struct objc_cache *cache OBJC2_UNAVAILABLE;
struct objc_cache { unsigned int mask /* total = mask + 1 */ OBJC2_UNAVAILABLE; unsigned int occupied OBJC2_UNAVAILABLE; Method buckets[1] OBJC2_UNAVAILABLE; }
Methodstructs, using the selector as the key. The way
objc_msgSendreally works is by first hashing the selector and looking it up in the class's method cache. If it's found, which it nearly always will be, it can jump straight to the method implementation with no further fuss. Only if it's not found does it have to do the more laborious lookup, at the end of which it inserts an entry into the cache so that future lookups can be fast.
(There is actually one more detail beyond this which ends up being extremely important: what happens when no method can be found for a given selector. But that one is so important that it deserves its own post, so look for it next week.)
Conclusion
That wraps up this week's edition. Come back next week for more. Have a question? Think Objective-C's messaging system should be done differently? Post below.
Remember, Friday Q&A is powered by your ideas. If you have an idea for a topic, tell me! Post your idea in the comments, or e-mail them directly to me (I'll use your name unless you ask me not to).
The very beginning of objc_msgSend() has two special cases.
The first checks to see if the receiver is nil and short circuits the call. But it doesn't just return. There is actually a hook for handling messages to nil buried in there. It isn't terribly useful, though, as there are a couple of 10s of thousands of message to nil as an average app does its thing ().
The second only occurs under GC. In this case, the selectors for -retain, -release, and -autorelease are overwritten and cause a short-circuit that very quickly returns self. Trivia: -retainCount is also short-circuited and, thus, -retainCount will return an absurdly large number under GC.
Note, also, that objc_msgSend() tail calls the real IMP. This is what enables method implementations to just be C functions. objc_msgSend() goes to great lengths to not muck with the arguments on the stack. Instead, it just figures out what address should be jumped to just like a normal C function.
As he mentions in his articles on DTrace/Instruments, the implication of this is that you can't attach a DTrace probe to the return of objc_msgSend.
Add your thoughts, post a comment:
Spam and off-topic posts will be deleted without notice. Culprits may be publicly humiliated at my sole discretion. | https://www.mikeash.com/pyblog/friday-qa-2009-03-20-objective-c-messaging.html | CC-MAIN-2016-30 | refinedweb | 1,216 | 61.46 |
Introduction
In this lesson, we will learn how to make a blinking LED by programming. Through your settings, your LED can produce a series of interesting phenomena. Now, go for it.
Components
Note: In order to proceed smoothly, you need to bring your own Raspberry Pi, TF card and Raspberry Pi power.
Principle
Breadboard
A breadboard is a construction base for prototyping of electronics. It is used to build and test circuits quickly before finishing any circuit design. And it has many holes into which components mentioned above can be inserted like ICs and resistors as well as jumper wires. The breadboard allows you to plug in and remove components easily.
The picture shows the internal structure of a full+ breadboard. Although these holes on the breadboard appear to be independent of each other, they are actually connected to each other through metal strips internally.
LED
LED is a kind of diode. LED will shine only if the long pin of LED is connected to the positive electrode and the short pin is connected to negative electrode.
The LED can not be directly connected to power supply, which can damage component. A resistor with 160Ω or larger (work in 5V) must be connected in series in the circuit of LED.
Resistor
Resistor is an electronic element that can limit the branch current. A fixed resistor is a kind of resistor whose resistance cannot be changed, while that of a potentiometer or a variable resistor can be adjusted.
Fixed resistor is applied in this kit. In the circuit, it is essential to protect the connected components. The following pictures show a real object, 220Ω resistor and two generally used circuit symbols of resistor. Ω is the unit of resistance and the larger units include KΩ, MΩ, etc. Their relationship can be shown as follows: 1 MΩ=1000 KΩ, 1 KΩ = 1000 Ω. Normally, the value of resistance is marked on it. So if you see these symbols in a circuit, it means that there is a resistor.
When using a resistor, we need to know its resistance first. Here are two methods: you can observe the bands on the resistor, or use a multimeter to measure the resistance. You are recommended to use the first method as it is more convenient and faster. To measure the value, use multimeter.
As shown in the card, each color stands for a number.
Schematic Diagram
In this experiment, connect a 220Ω resistor to the anode (the long pin of the LED), then the resistor to 3.3 V, and connect the cathode (the short pin) of the LED to GPIO17 of Raspberry Pi. Therefore, to turn on an LED, we need to make GPIO17 low (0V) level. We can get this phenomenon by programming.
Note: Pin11 refers to the 11th pin of the Raspberry Pi from left to right, and its corresponding wiringPi and BCM pin numbers are shown in the following table.
In the C language related content, we make GPIO0 equivalent to 0 in the wiringPi. Among the Python language related content, BCM 17 is 17 in the BCM column of the following table. At the same time, they are the same as the 11th pin on the Raspberry Pi, Pin 11.
Experimental Procedures
Step 1: Build the circuit.
- For C Language Users
Step 2: Go to the folder of the code.
If you use a monitor, you’re recommended to take the following steps.
Go to /home/pi/ and find the folder davinci-kit-for-raspberry-pi.
Find C in the folder, right-click on it and select Open in Terminal.
Then a window will pop up as shown below. So now you’ve entered the path of the code 1.1.1_BlinkingLed.c .
In the following lessons, we will use command to enter the code file instead of right-clicking. But you can choose the method you prefer.
If you log into the Raspberry Pi remotely, use “cd” to change directory:
cd /home/pi/davinci-kit-for-raspberry-pi/c/1.1.1/
Note: Change directory to the path of the code in this experiment via cd.
In either way, now you now are in the folder C. The subsequent procedures based on these two methods are the same. Let’s move on.
Step 3: Compile the code
gcc 1.1.1_BlinkingLed.c -o BlinkingLed -lwiringPi
Note: gcc is GNU Compiler Collection. Here, it functions like compiling the C language file 1_BlinkingLed.c and outputting an executable file.
In the command, -o means outputting (the character immediately following -o is the filename output after compilation, and an executable named BlinkingLed will generate here) and -lwiringPi is to load the library wiringPi (l is the abbreviation of library).
Step 4: Run the executable file output in the previous step.
sudo ./BlinkingLed
Note: To control the GPIO, you need to run the program, by the command, sudo(superuser do). The command “./“ indicates the current directory. The whole command is to run the BlinkingLed in the current directory.
After the code runs, you will see the LED flashing.
If you want to edit the code file 1.1.1_BlinkingLed.c, press Ctrl + C to stop running the code. Then type the following command to open it:
nano 1.1.1_BlinkingLed.c
Note: nano is a text editor tool. The command is used to open the code file 1.1.1_BlinkingLed.c by this tool._10<<
Code
The program code is shown as follows:
#include <wiringPi.h> #include <stdio.h> #define LedPin 0 int main(void) { // When initialize wiring failed, print message to screen if(wiringPiSetup() == -1){ printf("setup wiringPi failed !"); return 1; } pinMode(LedPin, OUTPUT);// Set LedPin as output to write value to it. while(1){ // LED on digitalWrite(LedPin, LOW); printf("...LED on\n"); delay(500); // LED off digitalWrite(LedPin, HIGH); printf("LED off...\n"); delay(500); } return 0; }
Code Explanation
#include <wiringPi.h>
The hardware drive library is designed for the C language of Raspberry Pi. Adding this library is conducive to the initialization of hardware, and the output of I/O ports, PWM, etc.
#include <stdio.h>
Standard I/O library. The pintf function used for printing the data displayed on the screen is realized by this library. There are many other performance functions for you to explore.
#define LedPin 0
Pin GPIO17 of the T_Extension Board is corresponding to the GPIO0 in wiringPi. Assign GPIO0 to LedPin, LedPin represents GPIO0 in the code later.
if(wiringPiSetup() == -1){ printf("setup wiringPi failed !"); return 1;
This initialises wiringPi and assumes that the calling program is going to be using the wiringPi pin numbering scheme.
This function needs to be called with root privileges. When initialize wiring failed, print message to screen. The function “return” is used to jump out of the current function. Using return in main() function will end the program..
printf("...LED off\n");
The printf function is a standard library function and its function prototype is in the header file “stdio.h”. The general form of the call is: printf(” format control string “, output table columns). The format control string is used to specify the output format, which is divided into format string and non-format string. The format string starts with ‘%’ followed by format characters, such as’ %d ‘for decimal integer output. Unformatted strings are printed as prototypes. What is used here is a non-format string, followed by “\n” that is a newline character, representing automatic line wrapping after printing a string.
delay(500);
Delay (500) keeps the current HIGH or LOW state for 500ms.
This is a function that suspends the program for a period of time. And the speed of the program is determined by our hardware. Here we turn on or off the LED. If there is no delay function, the program will run the whole program very fast and continuously loop. So we need the delay function to help us write and debug the program.
return 0;
Usually, it is placed behind the main function, indicating that the function returns 0 on successful execution.
- Ø For Python Language Users
Step 2: Go to the folder of the code and run it.
If you use a monitor, you’re recommended to take the following steps.
Find 1.1.1_BlinkingLed.py and double click it to open. Now you’re in the file.
Click Run ->Run Module in the window and the following contents will appear.
To stop it from running, just click the X button on the top right to close it and then you’ll back to the code. If you modify the code, before clicking Run Module (F5) you need to save it first. Then you can see the results.
If you log into the Raspberry Pi remotely, type in the command:
cd /home/pi/davinci-kit-for-raspberry-pi/python
Note: Change directory to the path of the code in this experiment via cd.
Step 3: Run the code
sudo python3 1.1.1_BlinkingLed.py
Note: Here sudo – superuser do, and python means to run the file by Python.
After the code runs, you will see the LED flashing.
Step 4: If you want to edit the code file 1.1.1_BlinkingLed.py, press Ctrl + C to stop running the code. Then type the following command to open 1.1.1_BlinkingLed.py:
nano 1.1.1_BlinkingLed.py
Note: nano is a text editor tool. The command is used to open the code file 1.1.1_BlinkingLed.py by this tool.
Press Ctrl+X to exit. If you have modified the code, there will be a prompt asking whether to save the changes or not. Type in Y (save) or N (don’t save).
Then press Enter to exit. Type in nano 1.1.1_BlinkingLed.py again to see the effect after the change.
Code
#!/usr/bin/env python3 import RPi.GPIO as GPIO import time LedPin = 17 def setup(): # Set the GPIO modes to BCM Numbering GPIO.setmode(GPIO.BCM) # Set LedPin's mode to output,and initial level to High(3.3v) GPIO.setup(LedPin, GPIO.OUT, initial=GPIO.HIGH) # Define a main function for main process def main(): while True: print ('...LED ON') # Turn on LED GPIO.output(LedPin, GPIO.LOW) program destroy() will be executed. except KeyboardInterrupt: destroy()
In this way, import the RPi.GPIO library, then define a variable, GPIO to replace RPI.GPIO in the following code.
import time
Import time package, for time delay function in the following program.
LedPin = 17
LED connects to the GPIO17 of the T-shape extension board, namely, BCM 17.
def setup(): GPIO.setmode(GPIO.BCM) GPIO.setup(LedPin, GPIO.OUT, initial=GPIO.HIGH)
Set LedPin’s mode to output, and initial level to High (3.3v).
There are two ways of numbering the IO pins on a Raspberry Pi within RPi.GPIO: BOARD numbers and BCM numbers. In our lessons, what we use is BCM numbers. You need to set up every channel you are using as an input or an output.
GPIO.output(LedPin, GPIO.LOW)
Set GPIO17(BCM17) as 0V (low level). Since the cathode of LED is connected to GPIO17, thus the LED will light up.
time.sleep(0.5)
Delay for 0.5 second. Here, the statement is similar to delay function in C language, the unit is second.
def destroy(): GPIO.cleanup()
Define a destroy function for clean up everything after the script finished.
if __name__ == '__main__': setup() try: main() # When 'Ctrl+C' is pressed, the program destroy() will be executed. except KeyboardInterrupt: destroy()
This is the general running structure of the code. When the program starts to run, it initializes the pin by running the setup(), and then runs the code in the main() function to set the pin to high and low levels. When ‘Ctrl+C’ is pressed, the program, destroy() will be executed.
Phenomenon Picture
| https://learn.sunfounder.com/lesson-1-1-1-blinking-led/ | CC-MAIN-2021-25 | refinedweb | 1,975 | 67.65 |
#include <hallo.h> > My recommendations are: > > 1. libc6-dev should be part of the standard installation. It includes > all of the standard header files (stdio.h, for example). This depends on _your_ needs! For example, I don't think that the compiler is seen as part of a user-oriented operating system. If you want to do "complicated stuff, coding", eg. compile programs, you want to install build-essential anyways. Same thing if you install the kernel. > 2. ssh should also be part of any installation. ssh has the standard priority and should be suggested somewhere during the base config. At least you would need to select some special things to avoid installing it. If you wanted to say that ssh should be part of the basedebs or even an "essential" package, then no. Simply no. There are enough boxes where ssh is not needed or should not be installed for various reasons. Regards, Eduard. -- Der Aberglaube ist die Poesie des Lebens; deswegen schadet's dem Dichter nicht, abergl�isch zu sein, -- Johann Wolfgang von Goethe (Maximen und Reflexionen) | https://lists.debian.org/debian-user/2004/09/msg03131.html | CC-MAIN-2016-07 | refinedweb | 179 | 68.36 |
- Closed
Activity
- All
- Work Log
- History
- Activity
- Transitions
Well if
HBASE-1416 is really just about the first issue then I think this jira plays well with it, we can have a commit thread per WAL for example. Also my patch is already done, I'm currently running the unit tests to make sure I didn't forget something.
Sounds good J-D.
Patch that implements the group commit but that also cleans up
HDFS-200 era code. Passes all tests
- I remove LogFlusher in favor of the LogSyncer thread. This also fixes the fact that the optional log flush value was never use.
- I use an AtomicBoolean to force sync. This part was tricky because there is no message passing between the client thread and the LogSyncer.
Damn forgot to mention that according to my many tests, single thread writing is ~1% slower but using 9 threads you get a 15-20% improvement.
This can be final:
+ private LogSyncer logSyncerThread;
Can this be static inner class? Paass in flushinterval? And the atomicboolean close? Make it private?
+ public class LogSyncer extends Thread {
Why syncfs and not just sync? syncfs was name of the method in hdfs-200... its now called hflush?
Do the above on commit I'd say. They are small changes. Looks good to me J-D.
I'm good with the comments.
There's already a method called sync in HLog that's used from HRS and such so I was searching for another name. I'll rename it to syncAppends maybe? Or syncOutputStream?
Have you tried it on a heavy write job?
Thx!
call it hflush? its the new style!
I did not try your patch. Will do after you commit.
Doh missed that part.
BTW, I cannot have the class static because it relies on the instance of that HLog as it calls hsync and uses its close boolean.
Committed to trunk, please test your massive inserts and see how better (or worse, could happen) it is when syncing every edit.
>+ // Set force sync if force is true and forceSync is false
>+ forceSync.compareAndSet(!forceSync.get() && force, true);
Wouldn't this leave forceSync to 'true' all the time?
Raghu,
Thanks for looking at this patch, I guess I am wrong but in the way you described.
!(true) && false => false == false then set it to true. That's ok you want to let it true
!(false) && false => false == false then set it to true. That's not ok we want it to stay false
!(false) && true => true != false then let it be false. That's not ok we want it to be true
!(true) && true => false != true then let it be true. That's ok you want it true
Also that value is reset in hsync to false.
So I indeed need to fix this thx!
> Wouldn't this leave forceSync to 'true' all the time?
not all the time. forceSync will remain unchanged when 'force' is true.
syncDone needs to be signaled in finally? Otherwise might leave the waiters hanging.
Reopening since it seems I was too fast at committing.
Second version of the patch against current trunk with Raghu's comments.
So I changed the condition so that it really sets to force if force == true and forceSync == false. In all the other cases it should stay to current value and hsync resets to false if the value was set to true. I also cleaned a LOG which has an unnecessary stack trace and removed now un-thrown exceptions.
Committed patch to trunk.
Thanks J-D.
I should have seen the update earlier... not sure how important 'force' flag is. Currently it might not work properly.
Say sync thread starts fs_sync() at time t0. At t1 a client appends and invokes a force-sync... I am assuming the contract is it should return after next fs_sync. But in the current implementation, it may not : when fs_sync() returns at t2, it sets this flag to false.. client's force-sync could return without a fs_sync.
I might implement it something like :
addToSyncQ(boolean force) { lock() if (force) { this.forceSync = true; } //... }
Rest of the implementation remains same.. with forceSync being a simple boolean rather than an atomic.
Raghu,
Again thanks a lot for spending some time looking at my work.
So the background is that the catalog tables like .META. must never lose any edits so, even if we sync every 100 edits for some reason, when this catalog edit comes in we want to make sure it's safely registered.
And you are right, this is not the right place to set force as you pointed out.
v3 with Raghu's comments.
Should the forceSync be volatile? Otherwise patch looks good (make it volatile on commit?)
+1. It does not need to be volatile since it is always accessed under the same lock.
@Raghu Will that ensure all threads see most recent change to forceSync?
yes. should be same as accessing inside a synchronized section. We could consider atomic or volatile if findbugs does not see that.
I committed without the volatile.
Resolving since it wasn't the source of Hudson's instability.
Ported this patch back to version 0.20. Note that this refactoring incidentally fixed a bug on the tip with HLog.sync(). To summarize, the code under sync() should read
sync(); syncFs()
instead of
(syncFs) ? syncFs() : sync();
sync() flushes the SequenceFile.Writer buffer to DFSOutputStream. syncFs() flushes the output stream across the network to the datanodes. So the current implementation isn't flushing the buffers properly and still gets stuck on local storage until the SequenceFile.Writer buffer is full.
I applied Nicolas's
HBASE-1939-20.4.patch above under the aegis of HBASE-2298. It doesn't look like TRUNK has the above issue calling sync (it don't use hdfs-200) but talking J-D in case.
This issue was closed as part of a bulk closing operation on 2015-11-20. All issues that have been resolved and where all fixVersions have been released have been closed (following discussions on the mailing list).
How does this relate to
HBASE-1416? I was looking at that. I think work on that issue and this one would clobber each other. | https://issues.apache.org/jira/browse/HBASE-1939 | CC-MAIN-2017-09 | refinedweb | 1,040 | 86.3 |
Data integration and data exchange is one of the key features in XML that will have wide usage in the future which means that applications would be able to exchange data. All large and small players in the computer industry are adopting XML. Hence XML is and will be a sure key enabler for e-business. Sound’s quite intriguing and fascinating isn’t it? Then read this article to understand why and how.
You may think in this strange world where standards come and go like seasons, even a single standard are fragmented by companies seeking competitive advantage. XML however, appears to be different. The technologies that dominate the market for data storage are pre-relational and relational databases that manage traditional data types like numbers and text. But with the advent of XML into the market, we have amazing new products that can manage and process “diligent data”, which means self-describing data. Relational systems will always be recommended for storing text and numbers, but if communication and processing are the priorities, XML is the technology of choice.
How is ASP and XML related? If you are using ASP to create a web site, then chances are pretty high that you are using a database to store data. XML is another format for storing data and being increasing used.
We’ve already seen XML support be introduced into Internet Explorer and ADO, but the support is far from full. The trouble stems from the fact that ADO and IE are evolving at different rates. While it is true that browser support is limited (although W3C’s Amaya browser as well as JUMBO browser supports it), in the near future all browsers are expected to fully support XML, and ADO and IE albeit would be more integrated. This shouldn’t give you the impression that XML is useless, until a browser supports it. XML isn’t about display, it’s about structure.
XML is gaining universal acceptance and is sure to stay in future. Parsing algorithms and tools continue to improve as more and more people come to know the long-term benefits of moving their data to XML.
Technical gurus claim that XML is revolutionizing the way we communicate, spread and exchange information across the Web and within Intranets. This powerful language will help you do things with your data that you never before thought possible. {mospagebreak title=Preparing Yourself For The Future!} What Is Extensible Markup Language: Before we can learn what XML is, it’s a good idea to clarify what markup language is. Because, language is probably the wrong term. It is not a language in the sense that Visual Basic or C++ are languages, but it’s a set of rules that define how text documents should be marked up. Now we have to define what we mean by marked up. Marking up a document is the process of identifying certain areas of a document as having special meaning. In short markup language is just a set of rules that define how we add meaning to areas of a document.
The main difference between XML and HTML XML takes a different view from HTML, although it still uses tags, It is not a replacement for HTML. XML and HTML were designed with different goals. The major difference is that XML is designed to describe the structure of text, not how it should display. In short, XML was designed to carry data, to describe data and to focus on what data is. On the other hand HTML was designed to display data and to focus on how data looks. To put it in a line we can say HTML is about displaying information, while XML is about describing information. Let us take a simple example 1: Save it as .html
<body>When you load the above html file into a browser, then it displays the above tags as though it were formatted document. Which will looks something like below
Hello !!
<h1> Welcome to the Web Age. </h1>
This is normal text. <b> while this is bold text.</b>
</body>
Hello!! Welcome To The Web Age This is normal text. While this is bold text.However if the above text defines an XML document, then the tag don’t mean anything. Say you load same file with .html extension (example 1) into the browser like IE but now with a .xml file suffix. Internet Explorer interprets this XML and displays it for us which looks like this
<body>But notice it’s done nothing with the XML – just displayed it as such (except indents the tags to give a structured look). The browser knows how to interpret HTML and display it with all formatting. The browser also knows how to interpret XML, but in this case since XML tags don’t imply formatting nothing is done and the tags are displayed as such. {mospagebreak title=The Name Says It All…..EXtensible:} HTML has a fixed set of element types, for example TITLE, H1, H2, EM, BODY, P, HR, and so on. A valid HTML document must use these elements. It cannot invent its own. A browser vendor can of course add its own proprietary tags (for instance, Netscape’s <BLINK> tag), but there is no standard way to introduce new element types. While this is not the case with XML. XML has the ability to define new elements, and furthermore, this can be done in the document itself. Thus, XML documents are in essence self-describing. Let’s consider an example. Imagine that you are looking at an HTML document with the following table in it:
Hello !!
<h1> Welcome to the Web Age. </h1>
This is normal text. <b> while this is bold text.</b>
</body>
<table >Although we as humans or programmers can make an educated guess, we really have no way of knowing what this data represents. Is “Visual Basic Programming” the name of a book? A course opted? Skill set required? It is impossible to say. And if it’s a course (as appear to be), are there three named participants registered (Naven, Gokul, and Anna). Or just one named Naven Gokul Anna? XML fixes this. The corresponding information would be represented in XML like this:
<tr>
<td> <i>Visual Basic Programming</i> </td>
<td> BTech</td>
<td> Eduwardo Wancelloti </td>
<td> Naven<br> Gokul <br> Anna </td>
</tr>
(and so on for each row)...
</table>
<course>The lesson here is tags can be anything you like, it is only how you use them that gives them meaning. Of course it is sensible to give meaningful names to start with. In the above example we have used XML to describe data, and we’ve used tag names that represent field names of the data. Thus in XML, information about the data structure can be preserved. It’s standard text, so can easily transfer from machine to machine. It’s not in proprietary format, so anyone can read it, and if the tags are named sensibly, the XML is self-describing. Furthermore, all information concerning presentation style has been removed from the document. We can say that this XML document evidently supports an element named “course,” and the question you should be asking yourself is: But how am I supposed to know how to format this? (Notice that the HTML code contains a style directive for the text “Visual Basic Programming;” for example, the element indicates italics.{mospagebreak title=Proof Is In The Output} XML does not have a fixed number of tags or elements, as HTML does, but is extensible, as is SGML, allowing the document designer to define meaningful tags. XML represents a response to the inadequacy of both languages to meet typical information publishing needs in an era that includes global information networks, and conventional paper publishing. XML is designed as a slim SGML, better suited for software development, distribution on information networks, and for use on non-conventional computing systems. The virtue of XML will become clearer as the Internet expands and as information devices such as palm-held computers and cellular phones become increasingly popular. Now let us look at some terms, and different ways that XML can be laid.
<name> Java Programming </name>
<department> BTech </department>
<teacher> Eduwardo Wancelloti </teacher>
<student> Naven </student>
<student> Gokul </student>
<student> Anna </student>
</course>
Tag and Element:
We have used the name <b>tag <b>to identify some HTML such as <b> and <h1>. An <b>Element<b> is a fully formed use of those tags. For example:
<b> Some Bold text and <I> italic text </I></b>.
This tag consists of two opening and closing tags and two elements: “b” and “I”. So an element comprises of a start tag, an end tag, and text it encloses, which can include other elements. This is of great significance because it introduces the concept of <b>Well-formed XML</b>. In which an openeing tag must have closing tags. This is very different from HTML where some tags like <IMG> and <BR> don’t have closing tags.
If you are using XML it is possible that some fields might contain no data. In that case the tags would be empty. Empty tags in XML could be define in one of the two ways. First is with start and end tags, but no content:
<TagName></TagName>
<TagName/>Another aspect of being well-formed is that XML tags are case sensitive, so opening and closin tags must match. This means the following is incorrect:
<TagName></tagname>{mospagebreak title=Starting From The Roots of XML…} Root Tags:
Another term to be aware of is the Root Tag. This is defined as the outer tag, and an XMl document can have only one root. For example:
<BookAuthors>There can be only one top-level tag in the above code <BookAuthors>. Say you add <BookAuthors> some <author>tags and another <Bookauthors> within the above tag, then it will become invalid.
<Author>
<au_id>1001</au_id>
<au_name> Bill Gates </au_name>
</Author>
<Author>
<au_id>1002</au_id>
<au_name> Harry Potter</au_name>
</Author>
</BookAuthors>
The <?XML Tag>: This isn’t a true XML tag but special tag indicating special processing instructions. The <?xml tag> should be the first line of each XML document. And can be used to identify the version and language information. It is also a place where you define the language used in your XML data. It is trivial that if your data contains characters that aren’t a part of ASCII (standard english character set) you can specify the encoding used in your document by adding encoding attribute to the ?xml processing instruction as follows:
<?xml version=”1.0” encoding=”iso-8859-1” ?>Attributes:
Like HTML, XML has Attributes to define the properties of elements, and they mus also be well-formed.
Special Characters:
XML has special set of characters, which cannot be used as normal string. They are &, <, >, “ and,. For example the following is invalid <book> Advanced ASP & ADO Concepts </book>
Schemas and DTD’s:
As stated earlier XML tags don’t actual mean anything and you can give any name, but how do you know what name to give and what sort of tags are allowed in a document. For this purpose you have to use either a Document Type Definition (DTD) or Schema. Schema and DTDs are like flip side of the same coin. They both specify which element are allowed in a document, and can run well-formed XML document into Valid XML document. All this means is that XML as well as being correctly marked up (well-formed) it contains only allowed elements and attributes.{mospagebreak title=The Best Of Both The Worlds} We will discuss both DTDs and Schemas you can decide which to use. A DTD is a text file that defines the structure of an XML document, but DTDs isn’t XML – it is completely separate syntax.
Let us look at a typical DTD – say you have Employees table in your database that had fields like emp_id, emp_lname, emp_fname, phone, address, zip. Then the XML document generated for this Employee from the database will look this below.
<!ELEMENT DOCUMENT (EMPLOYEE+)>This is actually quite simple it states that this document comprises zero or more employee elements. The plus sign on the end of EMPLOYEE says one or more. Each EMPLOYEE element is made up of six other elements. And each of these sub-elements contains character data (CDATA).
<!ELEMENT EMPLOYEE(emp_id, emp_lname, emp_fname, phone, address, zip)>
<!ELEMENT emp_id (CDATA)>
<!ELEMENT emp_lname(CDATA)>
<!ELEMENT emp_fname(CDATA)>
<!ELEMENT phone(CDATA)>
<!ELEMENT address (CDATA)>
<!ELEMENT zip (CDATA)>
There are two real flaws with DTD:
• They are not XML as such
• You cannot specify data types such as integer, data and so on.
Because of this Microsoft proposed Schemas to the W3C. If we converted the above DTD into a Schema it will look something like this:
<Schema ID=”EMPLOYEE”>With the addition of data types display will look like below.
<ELEMENT name = “emp_id”/>
<ELEMENT name = “emp_lname”/>
<ELEMENT name = “emp_fname”/>
<ELEMENT name = “phone”/>
<ELEMENT name = “address”/>
<ELEMENT name = “zip”/>
</Schema>
<Schema ID=”EMPLOYEE”>Namespaces:
<ELEMENT name = “emp_id” type = “string”/>
<ELEMENT name = “emp_lname” type = “string”/>
<ELEMENT name = “emp_fname” type = “string”/>
<ELEMENT name = “phone” type = “string”/>
<ELEMENT name = “address” type = “string”/>
<ELEMENT name = “zip” type = “string”/>
</Schema>
One problem with XMl is you can give an element almost any name. Unfortunately this means there is good chance you’ll pick the same name as someone else. This is where namespaces come in, as namespaces uniquely identifies the schema to which elements belong. Namespaces are added to XML document by defining the xmlns attributes in the root tag, which requires Uniform resource Identifier (URI). {mospagebreak title=The Potential Of XML} Parts of an XML document:
The various building blocks of an XML document is shown in the document below. And this will be a recap to what we have already learnt.
The Prolog consisits of two internal blocks :
• The first block defines the XML version declaration which is optional. <?xml version = “1.0” ?>
• DTD (document type definition) OR SCHEMA
PROLOGXML Style Sheets
VERSION
DECLARATION
DTD OR SCHEMA
<ROOT>
BODY…..
</ROOT>
XML documents, unlike HTML, contain absolutely no formatting directives. Instead, an XSL (XML style sheet) is applied to the XML document. Think of a style sheet as a pre-processor for the actual graphical flow-engine that creates the final layout. The style sheet contains functions and rules for every element type. The functions are written in Scheme (a programming language derived from LISP) and have access to the full structure of the XML document being processed. This means that elements can be processed conditionally, for example, based upon their parent-element type (or some other relevant factor).
It is beyond the scope of this document to discuss XSL style sheets. However, the concept of applying a style sheet as part of the server-side processing is in fact extremely interesting and relevant to the discussion vis-a-vis server-side XML processing. I like to think of style sheets as transformation engines, which are capable of transforming an XML document into something else–for instance, a database record–or an HTML document. {mospagebreak title=XML Parser} A parser is a piece of software that makes sure the XML document is valid or at least well-formed. Parsers are extremely complex to develop and so only experienced programmers will design one. Once a parser is developed, other programmers and Web designers can easily reuse it .A parser is part of XML that you will never see.
XML tags are custom-defined thus enabling the generation of domain specific markup languages for diverse fields such as vector graphics, mathematics, music and technical documentation. I hope my now you have got a fair idea of this most hyped up XML technology, we will explore more of this in the next part. | http://www.devshed.com/c/a/xml/introduction-to-xml/3/ | CC-MAIN-2016-07 | refinedweb | 2,651 | 63.39 |
This PySpark Cassandra repository is no longer maintained. Please check this repository for Spark 2.0+ support:
PySpark Cassandra brings back the fun in working with Cassandra data in PySpark.
This module provides python support for Apache Spark's Resillient Distributed Datasets from Apache Cassandra CQL rows using Cassandra Spark Connector within PySpark, both in the interactive shell and in python programmes submitted with spark-submit.
This project was initially forked from, but in order to submit it to, a plain old repository was created.
Contents:
Feedback on (in-)compatibility is much appreciated.
The current version of PySpark Cassandra is succesfully used with Spark version 1.5 and 1.6. Use older versions for Spark 1.2, 1.3 or 1.4.
PySpark Cassandra is compatible with Cassandra:
PySpark Cassandra is used with python 2.7, python 3.3 and 3.4.
PySpark Cassandra is currently only packaged for Scala 2.10
Pyspark Cassandra is published at Spark Packages. This allows easy usage with Spark through:
spark-submit \ --packages TargetHolding/pyspark-cassandra:<version> \ --conf spark.cassandra.connection.host=your,cassandra,node,names
spark-submit \ --jars /path/to/pyspark-cassandra-assembly-<version>.jar \ --driver-class-path /path/to/pyspark-cassandra-assembly-<version>.jar \ --py-files /path/to/pyspark-cassandra-assembly-<version>.jar \ --conf spark.cassandra.connection.host=your,cassandra,node,names \ --master spark://spark-master:7077 \ yourscript.py
(note that the the --driver-class-path due to SPARK-5185) (also not that the assembly will include the python source files, quite similar to a python source distribution)
Replace
spark-submit with
pyspark to start the interactive shell and don't provide a script as argument and then import PySpark Cassandra. Note that when performing this import the
sc variable in pyspark is augmented with the
cassandraTable(...) method.
import pyspark_cassandra
sbt compile
The package can be published locally with:
sbt spPublishLocal
The package can be published to Spark Packages with (requires authentication and authorization):
make publish
A Java / JVM library as well as a python library is required to use PySpark Cassandra. They can be built with:
make dist
This creates a fat jar with the Spark Cassandra Connector and additional classes for bridging Spark and PySpark for Cassandra data and the .py source files at:
target/scala-2.10/pyspark-cassandra-assembly-<version>.jar
The PySpark Cassandra API aims to stay close to the Cassandra Spark Connector API. Reading its documentation is a good place to start.
The primary representation of CQL rows in PySpark Cassandra is the ROW format. However
sc.cassandraTable(...) supports the
row_format argument which can be any of the constants from
RowFormat:
DICT: The default layout, a CQL row is represented as a python dict with the CQL row columns as keys.
TUPLE: A CQL row is represented as a python tuple with the values in CQL table column order / the order of the selected columns.
ROW: A pyspark_cassandra.Row object representing a CQL row.
Column values are related between CQL and python as follows:
This is the default type to which CQL rows are mapped. It is directly compatible with
pyspark.sql.Row but is (correctly) mutable and provides some other improvements.
This type is structurally identical to pyspark_cassandra.Row but serves user defined types. Mapping to custom python types (e.g. via CQLEngine) is not yet supported.
A
CassandraSparkContext is very similar to a regular
SparkContext. It is created in the same way, can be used to read files, parallelize local data, broadcast a variable, etc. See the Spark Programming Guide for more details. But it exposes one additional method:
cassandraTable(keyspace, table, ...): Returns a CassandraRDD for the given keyspace and table. Additional arguments which can be provided:
row_formatcan be set to any of the
pyspark_cassandra.RowFormatvalues (defaults to
ROW)
split_sizesets the size in the number of CQL rows in each partition (defaults to
100000)
fetch_sizesets the number of rows to fetch per request from Cassandra (defaults to
1000)
consistency_levelsets with which consistency level to read the data (defaults to
LOCAL_ONE)
PySpark Cassandra supports saving arbitrary RDD's to Cassandra using:
rdd.saveToCassandra(keyspace, table, ...): Saves an RDD to Cassandra. The RDD is expected to contain dicts with keys mapping to CQL columns. Additional arguments which can be supplied are:
columns(iterable): The columns to save, i.e. which keys to take from the dicts in the RDD.
batch_size(int): The size in bytes to batch up in an unlogged batch of CQL inserts.
batch_buffer_size(int): The maximum number of batches which are 'pending'.
batch_grouping_key(string): The way batches are formed (defaults to "partition"):
all: any row can be added to any batch
replicaset: rows are batched for replica sets
partition: rows are batched by their partition key
consistency_level(cassandra.ConsistencyLevel): The consistency level used in writing to Cassandra.
parallelism_level(int): The maximum number of batches written in parallel.
throughput_mibps: Maximum write throughput allowed per single core in MB/s.
ttl(int or timedelta): The time to live as milliseconds or timedelta to use for the values.
timestamp(int, date or datetime): The timestamp in milliseconds, date or datetime to use for the values.
metrics_enabled(bool): Whether to enable task metrics updates.
A
CassandraRDD is very similar to a regular
RDD in pyspark. It is extended with the following methods:
select(*columns): Creates a CassandraRDD with the select clause applied.
where(clause, *args): Creates a CassandraRDD with a CQL where clause applied. The clause can contain ? markers with the arguments supplied as *args.
limit(num): Creates a CassandraRDD with the limit clause applied.
take(num): Takes at most
numrecords from the Cassandra table. Note that if
limit()was invoked before
take()a normal pyspark
take()is performed. Otherwise, first limit is set and then a
take()is performed.
cassandraCount(): Lets Cassandra perform a count, instead of loading the data to Spark first.
saveToCassandra(...): As above, but the keyspace and/or table may be omitted to save to the same keyspace and/or table.
spanBy(*columns): Groups rows by the given columns without shuffling.
joinWithCassandraTable(keyspace, table): Join an RDD with a Cassandra table on the partition key. Use .on(...) to specifiy other columns to join on. .select(...), .where(...) and .limit(...) can be used as well.
When importing
pyspark_cassandra.streaming the method ``saveToCassandra(...)``` is made available on DStreams. Also support for joining with a Cassandra table is added:
joinWithCassandraTable(keyspace, table, selected_columns, join_columns):
Creating a SparkContext with Cassandra support
import pyspark_cassandra conf = SparkConf() \ .setAppName("PySpark Cassandra Test") \ .setMaster("spark://spark-master:7077") \ .set("spark.cassandra.connection.host", "cas-1") sc = CassandraSparkContext(conf=conf)
Using select and where to narrow the data in an RDD and then filter, map, reduce and collect it::
sc \ .cassandraTable("keyspace", "table") \ .select("col-a", "col-b") \ .where("key=?", "x") \ .filter(lambda r: r["col-b"].contains("foo")) \ .map(lambda r: (r["col-a"], 1) .reduceByKey(lambda a, b: a + b) .collect()
Storing data in Cassandra::
rdd = sc.parallelize([{ "key": k, "stamp": datetime.now(), "val": random() * 10, "tags": ["a", "b", "c"], "options": { "foo": "bar", "baz": "qux", } } for k in ["x", "y", "z"]]) rdd.saveToCassandra( "keyspace", "table", ttl=timedelta(hours=1), )
Create a streaming context, convert every line to a generater of words which are saved to cassandra. Through this example all unique words are stored in Cassandra.
The words are wrapped as a tuple so that they are in a format which can be stored. A dict or a pyspark_cassandra.Row object would have worked as well.
from pyspark.streaming import StreamingContext from pyspark_cassandra import streaming ssc = StreamingContext(sc, 2) ssc \ .socketTextStream("localhost", 9999) \ .flatMap(lambda l: ((w,) for w in (l,))) \ .saveToCassandra('keyspace', 'words') ssc.start()
Joining with Cassandra:
joined = rdd \ .joinWithCassandraTable('keyspace', 'accounts') \ .on('id') \ .select('e-mail', 'followers') for left, right in joined: ...
Or with a DStream:
joined = dstream.joinWithCassandraTable(self.keyspace, self.table, ['e-mail', 'followers'], ['id']) | https://www.programcreek.com/python/?project_name=TargetHolding%2Fpyspark-cassandra | CC-MAIN-2021-04 | refinedweb | 1,299 | 51.24 |
JPEG Support
I know this has been asked a thousand times, but none of the solutions have worked for me. I am creating a very simple web-view gui app. It compiles just fine, but there is no jpeg support when i deploy the app to any other computer other than mine.
What I have tried:
compiling QT statically (after 4 days of compiling errors, this is probably not going to work for me)
Copying the plugin directly into the release version of the App (I would love to do this, but I am not quite getting it right). Here is my .pro contents:
@
QT += core gui
QT += webkit
TARGET = browser3
TEMPLATE = app
SOURCES += main.cpp
mainwindow.cpp
HEADERS += mainwindow.h
FORMS += mainwindow.ui
win32:RC_FILE = MyApplication.rc
QT_PLUGIN_PATH = plugins
@
I then put the qjpeg4.dll file into the plugins folder. This is probably really stupid for obvious reasons which are unknown to me.
I have been trying to get my simple QT app to work for 5 days. If someone can solve this relatively easy problem, I will forever be in your debt. Although beggars shouldn't demand anything, if you are kind enough to answer with some possible solution, please provide as much detail as possible. I am a noob, so please assume I know nothing. Thanks so much!
Try to put in your .pro
@
QTPLUGIN += qjpeg
@
and in your main.cpp :
@
#include <QtPlugin>
Q_IMPORT_PLUGIN(qjpeg);
int main(int argc, char *argv[])
{
...
...
}
@
First, thanks for the speedy response! Second, I had tried that earlier, but kept getting errors like cannot find -lqjpegd. However, I figured it out!
Although I had tried putting the plugin directly into myapp/plugins/imageformats/qjpeg4.dll, and I had tried myapp/qjpeg4.dll, I had not tried myapp/imageformats/qjpeg4.dll. So, although it appears that the plugin path in my project file is completely ignored - I really don't care, as long as it works. Documentation on this, however, would have been invaluable as I lost 4 days of work before stumbling across this solution (by trial and error). Again, plugin worked for me when i did this:
myapp/imageformats/qjpeg4.dll
Wow.
- claudio.donofrio
Hi guys
I don't know whats going wrong but I've just tried to run a small image browser app on Windows 7 SP1 32bit. This app worked fine for the last couple of month. Now my app can't load jpgeg images anymore. I do have myapp/imageformats/qjpeg4.dll. I've even tried to register the dll, but that gives me an error "The module failed to load". Loading PNG images still works flawlessly......
Did you, by any chance, change something in your compilation environment? New Qt version? Using release instead of debug? Changed compiler? All those need to match between the libs, your application and your plugins.
- claudio.donofrio
I will have to check the consistency of workflow, but I just copied the application folder as is (previously working fine) and again; the same app works fine with PNG images. | https://forum.qt.io/topic/1003/jpeg-support | CC-MAIN-2018-30 | refinedweb | 507 | 67.96 |
0
I am currently in need of help on a piece of homework, I'm using python 3.3 and i need to set a delay on a times table program that i created heres the code:
def get_int(prompt="Enter an integer: "): """this function will loop until an integer is entered""" while True: try: # return breaks out of the endless while loop return int(input(prompt)) except ValueError: print("Try again, value entered was not an integer.") x = get_int ("Enter a number: ") for i in range(1,13): print (x*i)
Is it possible to add a delay without changing the code dramatically or would i have to change everything? Thanks in advance. | https://www.daniweb.com/programming/software-development/threads/464338/setting-a-delay-on-times-tables | CC-MAIN-2017-39 | refinedweb | 114 | 62.01 |
Clodoaldo Pinto Neto wrote ..
> Since it is not possible to instantiate the FieldStorage class when
> using the Publisher handler is there a way to pass the
> keep_blank_values argument to Request.form?
Since publisher explicitly sets keep_blank_values to 1, does that mean
you want to override it to be 0?
Like mod_python.psp, the mod_python.publisher handler should perhaps
use an existing instance of the form stored as req.form. That way you
could wrap the publisher handler and override how the form is created.
def handler(req):
req.form = util.FieldStorage(req, keep_blank_values=0)
return mod_python.publisher.handler(req)
This change should perhaps be made in mod_python 3,3.
By allowing this, it might feasibly allow things to be done with the file
callback hooks that FieldStorage accepts in the constructor as well.
Graham | http://modpython.org/pipermail/mod_python/2006-October/022386.html | CC-MAIN-2018-39 | refinedweb | 134 | 50.73 |
CloudWatch Metrics for Spot Fleet
Amazon EC2 provides Amazon CloudWatch metrics that you can use to monitor your Spot Fleet.
Important
To ensure accuracy, we recommend that you enable detailed monitoring when using these metrics. For more information, see Enable or Disable Detailed Monitoring for Your Instances.
For more information about CloudWatch metrics provided by Amazon EC2, see Monitoring Your Instances Using CloudWatch.
Spot Fleet Metrics
The
AWS/EC2Spot namespace includes the following metrics, plus the CloudWatch
metrics for the Spot Instances in your fleet. For more information, see Instance Metrics.
The
AWS/EC2Spot namespace includes the following metrics.
If the unit of measure for a metric is
Count, the most useful statistic
is
Average.
Spot Fleet Dimensions
To filter the data for your Spot Fleet, you can use the following dimensions.
View the CloudWatch Metrics for Your Spot Fleet
You can view the CloudWatch metrics for your Spot Fleet using the Amazon CloudWatch console. These metrics are displayed as monitoring graphs. These graphs show data points if the Spot Fleet is active.
Metrics are grouped first by namespace, and then by the various combinations of dimensions within each namespace. For example, you can view all Spot Fleet metrics or Spot Fleet metrics groups by Spot Fleet request ID, instance type, or Availability Zone.
To view Spot Fleet metrics
Open the CloudWatch console at.
In the navigation pane, under Metrics, choose the EC2 Spot namespace.
(Optional) To filter the metrics by dimension, select one of the following:
Fleet Request Metrics — Group by Spot Fleet request
By Availability Zone — Group by Spot Fleet request and Availability Zone
By Instance Type — Group by Spot Fleet request and instance type
By Availability Zone/Instance Type — Group by Spot Fleet request, Availability Zone, and instance type
To view the data for a metric, select the check box next to the metric. | https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/spot-fleet-cloudwatch-metrics.html | CC-MAIN-2018-17 | refinedweb | 307 | 61.77 |
Volume 72 Number 3
2016 CFA Institute
Robert Shillers cyclically adjusted priceearnings.
I
n 1998, Robert Shiller and John Campbell pub- research to the Board of Governors of the Federal
lished the pathbreaking article Valuation Ratios Reserve, warning that stock prices in the late 1990s
and the Long-Run Stock Market Outlook. A were running well ahead of earnings. Fed Chairman
follow-up to some of their earlier work on stock Alan Greenspans (1996) irrational exuberance
market predictability, it established that long-term speech, delivered one week later, was said to have
stock market returns were not random walks but, been partly based on their research.4 At the top of
rather, could be forecast by a valuation measure the bull market in 2000, the CAPE ratio hit an all-
called the cyclically adjusted priceearnings ratio, time high of 43, more than twice its historical aver-
or CAPE ratio.1 Shiller and Campbell calculated the
age, and correctly forecast the poor equity returns
CAPE ratio by dividing a long-term broad-based
over the next decade. In January 2015, the CAPE
index of stock market prices and earnings from 1871
ratio reached 25.0454.59% higher than its long-
by the average of the last 10 years of earnings per
term meanforecasting a 10-year future real stock
share, with earnings and stock prices measured
in real terms.2 They regressed 10-year real stock return of only 2.20%. This estimate is 4.5 percentage
returns against the CAPE ratio and found that the points (pps) below the long-run compound annual
CAPE ratio is a significant variable that can predict real return on equities, which averaged 6.70% a year
long-run stock returns. between 1871 and 2015.
The predictability of real stock returns implies The CAPE models January 2015 forecast of
that long-term equity returns are mean reverting. meager stock returns is the result of two factors:
In other words, if the CAPE ratio is above (below) the higher valuation of equities and the forecast
its long-run average, the model predicts below- decline of the CAPE ratio. If the CAPE ratio remains
average (above-average) real stock returns for the constant at its January 2015 value and if the growth
next 10 years. Figure 1 plots the CAPE ratio from rates of real earnings and dividends remain at their
1881 through 2014, together with both the forecast average levels since 1871, the 10-year future annu-
10-year annualized real stock returns from the model alized real return on stocks will be 5.2%150 bps
and the actual 10-year forward returns.3 The CAPE below its long-run average.5 This estimate implies
model explains more than a third of the variation in that the forecast reversion of the CAPE ratio to
future 10-year real stock returns. its mean subtracts an additional 300 bps from the
The CAPE model first gained national attention annual return on equity.
on 3 December 1996, when Robert Shiller and John
Campbell presented a preliminary version of their
Reasons for Elevated CAPE Ratios
Jeremy J. Siegel is the Russell E. Palmer Professor of One of the suggested reasons for the elevated CAPE
Finance at the Wharton School, University of Pennsyl- ratios (including the number cited by many bearish
vania, Philadelphia. stock market forecasters) is that investors are over-
Editors note: This article was reviewed and accepted optimistic about future earnings growth and when
by Robert Litterman, executive editor at the time the that growth does not materialize, investors will sell,
article was submitted. sending stock prices downward.
Figure 1. Shiller CAPE Ratio and Actual and Forecast 10-Year Real Stock
Returns, 18812014
Real Stock Returns (%) CAPE Ratio
25
20
Actual Returns
15
10
5
Forecast
0 Returns
5
50
10 CAPE Ratio
30
Mean 10
10
1881 1901 1921 1941 1961 1981 2001
But there are other explanations for an elevated than in the earlier years of Shillers sample. Because
CAPE ratio that do not rely on unduly bullish the CAPE ratio takes into account the last 10 years
expectations of future earnings. The rise in the of earnings, any stock return forecast issued before
CAPE ratio and the forecast reduction in the real 2018 will include the extraordinarily low earnings of
stock return may be owing to the dramatic fall in 20082009 and may be biased downward.
the real yield on bonds. The average real return on
US Treasury bonds over 18712014 was 2.95%, but Shillers CAPE Methodology
the January 2015 real return on 10-year Treasury
Shillers CAPE methodology regresses the forward
inflation-protected securities (TIPS) was only 0.5%.
10-year annualized real stock return (RETt) on the
The 2.45 pp reduction will exceed the reduction in
current value of the CAPEt ratio, which is the sim-
the real return on stocks if the CAPE ratio remains
ple arithmetic average of the last 10 years of real
at its current level over the next 10 years.
reported per share earnings of the S&P 500 Index,
Even if real returns on bonds revert to their
EARNt, over 18812004:
historical mean, the CAPE ratio could remain at
its 2015 elevated level owing to a lower equity risk RETt = 0.270 0.177 log ( CAPEt ) + t , R 2 = 0.350,
premium required by investors. The vast literature t = 10.53 t = 8.13
in this area dates back to the pathbreaking research where
of Mehra and Prescott (1985), who found that the
Pt
realized returns on equities are far too high to be CAPEt = .
explained by standard risk and return models. The ( EARNt + EARNt 1 + + EARNt 10 ) / 10
higher CAPE ratio may reflect investors adjustment
The coefficient on the CAPE ratio is highly sig-
to a lower risk premium over bonds and thus their
nificant and the R2 is 35%, indicating that the CAPE
willingness to accept a lower real return on stocks
ratio explains more than a third of the variation of
relative to bonds.
10-year real equity returns.
In this article, I offer an alternative explana-
tion of the elevated CAPE ratio. The nature of the
earnings series that is substituted into the CAPE The Total Return Portfolio
model has not been consistently calculated for the The CAPE methodology is not robust to a secular
long period over which Shiller has estimated his change in the growth rate of per share earnings.
CAPE equations. Changes in accounting practices The higher the growth rate of real earnings, the
since 1990 have depressed reported earnings dur- lower the average of the past 10 years of earn-
ing economic downturns to a much greater degree ings relative to current earningswhich raises the
CAPE ratio. The higher ratio biases the forecast of Earnings Concepts
future returns downward because it is based on Although the lower real return on bonds and/
estimates drawn from data when the growth rate or a lower equity risk premium may explain the
of earnings was lower. As Table 1 shows, growth rise in the CAPE ratio, an alternative reason for
in real earnings per share has accelerated since the higher CAPE values in recent years is changes
1945. One reason for the higher growth is the sub- in accounting standards, particularly for reported
stitution of share buybacks for cash dividends, as earnings. Companies report their earnings in two
evidenced by the sharply lower dividend payout principal ways: reported earnings (or net income)
ratio.6 and operating earnings. Reported earnings are
Acknowledging that a change in dividend policy earnings sanctioned by the Financial Accounting
affects the CAPE ratio, Bunn and Shiller (2014) neu- Standards Board (FASB), an organization founded
tralized its impact by constructing the CAPE ratio of in 1973 to establish accounting standards. Those
a total return portfolio (TRP). The TRP assumes that standardsthe generally accepted accounting prin-
all dividends are reinvested in the index and that the ciples, or GAAPare used to compute the earnings
TRPs earnings per share are the indexs earnings per that appear in annual reports and that are filed with
share times the number of shares in the TRPwhat government agencies (earnings filed with the IRS
Bunn and Shiller termed the scale-adjusted earn- may differ from those filed elsewhere). GAAP earn-
ings per share. The P/E (price-to-earnings ratio) ings, which are the basis of the Standard & Poors
of the TRP is the total return divided by the scale- reported earnings series that Shiller used in com-
adjusted earnings, and the CAPE ratio of the TRP is puting the CAPE ratio, have undergone significant
the total return index divided by the average of the conceptual changes in recent years.
last 10 years of scale-adjusted earnings per share A more generous earnings concept is operat-
with all variables calculated in real terms. The TRP ing earnings, which often exclude such one-time
is agnostic as to whether a change in dividend policy events as restructuring charges (expenses associ-
has taken place because it treats price and dividend ated with a companys closing a plant or selling a
returns symmetrically. division), investment gains and losses, inventory
The scale-adjusted earnings per share grow at write-offs, expenses associated with mergers and
a faster rate than the per share earnings of an index spinoffs, and depreciation or impairment of good-
will. But the term operating earnings is not defined
of stock prices because of the reinvestment of divi-
by the FASB, and companies thus have some latitude
dendssuggesting that the 10-year past average
in interpreting what is and what is not excluded.
of scale-adjusted earnings will be a smaller frac-
In certain circumstances, the same charge may be
tion of current scale-adjusted earnings than the
included in the operating earnings of one company
CAPE ratio calculated at the index level and will
and omitted from those of another.
have a higher average CAPE ratio. Figure 2 plots Because of these ambiguities, several versions
the standard Shiller CAPE ratio as the price index of operating earnings are calculated. Standard &
CAPE ratio and the total return CAPE ratio. Poors calculates a very strict version of operating
The mean CAPE ratio of the TRP is 19.84, or earnings that differs from GAAP reported earn-
22.5% higher than the price index CAPE ratio; the ings only in excluding asset impairments (includ-
January 2015 total return CAPE ratio exceeds its ing inventory write-downs) and severance pay
long-run mean by 40.0%, compared with 54.6% for associated with such impairments.7 We can call the
the price index CAPE ratio. Shifting from a price earnings reported by companies company operat-
index to a total return CAPE ratio explains some, but ing earnings and those calculated by Standard &
certainly not all, of the rise in the CAPE ratio. The Poors S&P operating earnings.8
forecast 10-year real return on stocks in the TRP rises Over 19882014, when all three earnings series
to 2.81%61 bps higher than the 2.20% projected by are available, S&P operating earnings averaged 15.5%
the price index CAPE ratio but still well below the above reported (GAAP) earnings, and company-
6.7% historical average real return on stocks. reported operating earnings averaged 3.2% above S&P
Figure 2. Price Index CAPE and Total Return CAPE Ratios relative to Their
Means, 18812014
CAPE Ratio
3.0
2.5
2.0
1.5
1.0
0.5
0
1881 1901 1921 1941 1961 1981 2001
operating earnings. During recessionsparticularly it was acquired by Time Warner, also an S&P 500
the Great Recession of 20082009the gaps between member, because the purchase price was far above
these earnings concepts widened significantly. In 2008, book value, but that capital gain was never recorded
company operating earnings declined 26.9% to $50.84, in the S&P earnings data. In 2002, after the internet
S&P operating earnings fell 40% to $39.61, and GAAP bubble popped, Time Warner was forced to write
reported earnings collapsed 77.3% to $12.54. down its investment in AOL by $99 billionat the
time, the largest loss ever recorded by a US corpo-
Changes in Reported Earnings ration. The combined profits and market value of
The definition of reported earnings has undergone AOL and Time Warner were not materially different
substantial changes in the last two decades. In 1993, after the tech bubble than before. But because the
the FASB issued Statement of Financial Accounting capital gains on AOL shares were never included
Standards (FAS) No. 115, which stated that securities as earnings, the aggregate earnings of the S&P 500
of financial institutions held for trading or avail- fell dramatically when AOLs market price tumbled.
able for sale were required to be carried at fair Many other companies also took large write-downs
market value. FAS Nos. 142 and 144, issued in 2001, on assets acquired during the tech bubble.
required that any impairments to the value of prop- The impact of write-downs was even more
erty, plant, equipment, and other intangibles (e.g., extreme in the Great Recession that followed the
goodwill acquired by purchasing stock above book financial crisis. Before 2008, there was never a loss in
value) be marked to market.9 These new standards, any quarter in the historical reported earnings data
which required companies to write down asset that Shiller used, including the Great Depression of
values regardless of whether the asset was sold, were the 1930s. But GAAP earnings in the fourth quarter
especially severe in economic downturns, when the of 2008 experienced a loss of $23.25, caused primarily
market prices of assets are depressed. Furthermore, by the huge write-downs of two financial firms
companies were not allowed to write tangible fixed AIG and Citigroupand Bank of America, which
assets back up, even if they recovered from a previ- together lost in excess of $80 billion. None of these
ous markdown, unless they were sold and recorded losses would have been recorded in GAAP earnings
as capital gain income.10 before FAS Nos. 115, 142, and 144 were issued.
An example of this earnings distortion is Time Some might claim that the large losses taken by
Warners purchase of America Online (AOL) for $214 financial firms in Q4 2008 offset the firms unjusti-
billion in January 2000, at the peak of the internet fied extra profits from booking subprime mortgages
boom. AOL, a member of the S&P 500 at the time, before the crisis. But this claim finds little support
registered a huge capital gain for shareholders when in an examination of a time series of the earnings
data for the financial sector. From the 12-month compiles the national income and product accounts
period beginning in Q4 2003, when subprime lend- (NIPAs). The BEA defines corporate profits as the
ing began to grow rapidly, to the 12-month period income earned from the current production by US
ending June 2007, the peak level of financial firms corporationsbased on adjusting, supplement-
earnings, reported earnings of the S&P 500 financial ing, and integrating financial-based and tax-based
sector rose 32%which is less than the 42% for all source data (Hodge 2011, p. 22).15 Annual data
S&P 500 companies over the same period.11 Bianco on corporate profits go back to 1928, and quarterly
and Wang (2015) showed that S&P 500 financial data to 1947. Andrew Hodge, an economist at the
firms experienced $497 billion in write-downs and BEA, has indicated that line 45 of Table 1.12 of the
excess loss provisions over 20072010, dwarfing National Income and Product Accounts Tables has
the profits made from subprime securitizations and the data most comparable to the profits reported
premiums received from underwriting mortgage- by Standard & Poors.
related securities. Figure 3 plots after-tax per share earnings
recorded by three different series: (1) the reported
The Aggregation Bias in S&P 500 earnings series published by Standard & Poors
and used in the ShillerCampbell analysis; (2) S&P
Index Earnings operating earnings, the companion series first pub-
A few companies with large losses affect the inter- lished by Standard & Poors in 1989; and (3) real
pretation of the P/E of a stock index that includes after-tax corporate profits as published in the NIPAs
those companies. A distortion related to the Standard adjusted for changes in the number of shares out-
& Poors methodology for computing the P/E of an standing.16 It is easy to see that the sharp declines
indexwhat I call the aggregation biasoveres- of S&P reported earnings have increased markedly
timates the effective ratio of the index when a few in the last decades.
companies generate large losses, as happened dur-
ing the financial crisis. S&P adds together the dollar Variability of Earnings
profits and losses of each S&P 500 company, without
regard to the weight of each company in the index, Table 2 confirms the increase in the volatility of
to compute the aggregate earnings of the index. This S&P reported earnings by computing the percent-
age decline in each of the three measures of earnings
procedure would be correct if each company were a
from 1929 to the present, during the business cycles
division of the same conglomerate and one wished
as defined by the National Bureau of Economic
to determine the P/E of that conglomerate.12
Research. The volatility of S&P reported earnings
But this methodology understates the valuation
has increased dramatically in the last three busi-
of a portfolio that contains independent companies
ness cycles. Before 1989, the percentage decline in
because the value of an individual stock can never go
S&P reported earnings was less than the percentage
below zero no matter how great its losses become;
decline in NIPA profits in every recession except
the losses do not offset the equity values of other
19371938. The average magnitude of the earnings
companies.13 Although AIG alone had a weight of
decline in recessions was 23.9% for S&P reported
only under 0.2% in the S&P 500 at the time, its $63
earnings and 37.3% for NIPA profits. But in the last
billion loss more than wiped out the aggregate profits
three recessions, S&P reported earnings fell by more
of the 30 most profitable companies in the S&P 500
than twice as much as NIPA profits. In the 1990 reces-
in Q4 2008companies whose market values com-
sion, S&P reported earnings fell 42.8% while NIPA
posed almost half the index. This dramatic decline
profits fell only 4%. In 2001, S&P reported earnings
in reported earnings of the S&P 500 is a major reason
fell 55.3% and NIPA declined 24.3%. In the Great
why the CAPE ratio has remained so far above its
Recession, NIPA fell 53% while S&P reported earn-
mean since the financial crisis. Because the exact size
ings declined 92.1%.
of this aggregation bias is difficult to measure, I do not
As noted earlier, it is puzzling that the decline
make any adjustment for it in the S&P earnings data.
in S&P reported earnings in the 200809 reces-
If one were to do so, it would move in the direction of
sionwhen the maximum decline in GDP was
increasing effective earnings in recessions.14
just over 5%was much greater than the decline
in S&P reported earnings in the Great Depression,
NIPA Profits when GDP declined five times as much. NIPA
Because of changes in the definition of GAAP earn- corporate profits, unlike S&P reported earnings,
ings, it is important to use a definition of corporate were negative in 1931 and 1932, far more in line
profits that has not changed over time, as in the with other economic data. These disparities also
series computed by the national income economists suggest that there has been a change in the S&P
at the Bureau of Economic Analysis (BEA), which methodology from likely understating declines in
10
Real per Share Reported Earnings Real per Share NIPA Profits
Real per Share Operating Earnings
earnings during economic downturns to signifi- expenses. But since 2004, both operating and S&P
cantly overstating them. reported earnings do include option expenses, in
The accounting profession has analyzed the line with the FASB requirement that all companies
trends and sources of the volatility of reported earn- expense options no later than 2006.17
ings. Givoly and Hayn (2002) found that accounting The large gap between the S&P 500 reported
standards have become more conservative over time, earnings series and NIPA profits in the Great
particularly by requiring mark-to-market accounting Recession prompted the BEA to issue Hodge (2011).18
in the case of asset impairment. Dichev and Tang The author confirmed that a key source of the high
(2008) surmised that changes in accounting standards volatility in the S&P 500 quarterly reported earnings
are primarily responsible for increased earnings vari- is asset write-downs, citing the charges taken by
ability. Other researchers, conceding that changes AIG and other prominent financial companies in
in standards are one source of increased volatility, 2008 and 2009.
also point to the growing number of companies that
consider both intellectual property and R&D impor- CAPE Ratio with Alternative
tant. Such companies, which have more flexibility in
reporting when costs are taken, can be a source of Earnings Series
increased volatility. Donelson, Jennings, and McInnis Table 3 shows summary statistics for the CAPE fore-
(2011) determined that although accounting stan- casting regressions using S&P reported earnings,
dards definitely play a role in increasing earnings S&P operating earnings, and NIPA profits. Because
volatility, special item charges not connected with the S&P operating earnings series is available from
accounting standards may be more important. 1989 and the NIPA profits from 1928, the S&P
Some financial economists, including Andrew reported earnings series is spliced into those series in
Smithers of the United Kingdom, believe that man- the earlier years. Because the recent mark-to-market
agements manipulation of earnings leads to both rules are applied more stringently to reported earn-
an overstatement of earnings and an increase in ings than to operating earnings, the S&P operating
their volatility. Smithers (2014a, 2014b) has main- earnings series, appended to the reported earnings
tained that managers manipulate earnings in order data, may be calculated more consistently than the
to reach short-term goals on which their bonuses reported earnings series.
and the value of their options depend. Certainly, In forecasting future 10-year real stock returns,
many of the earnings reported by tech companies the highest R2 is achieved by using NIPA profits for
are overstated because they do not include option specifications of the CAPE regression, with either
the price index portfolio or the total return portfo- 18712014 data. Figure 5 does the same for the total
lio. For the price index CAPE, the overvaluation of return portfolio. Shifting from reported earnings to
the equity market in January 2015 drops from 54.6% operating earnings to NIPA profits reveals a reduc-
for reported earnings to 40.3% for S&P operating tion in the degree of overvaluation, and the over-
earnings and 18.8% for NIPA profits. For the total valuation is reduced even more by using Shillers
return CAPE, the overvaluation drops from 40.0% total return methodology.
to 27.0% to only 7.1% for NIPA profits. For NIPA
profits, the CAPE model forecasts for January 2015 Conclusion
January 2025 a 10-year annualized real return on the
S&P 500 of 4.41% for the price index portfolio and The CAPE ratio is a very powerful predictor of long-
5.25% for the total return portfolio. The latter return term real stock returns. But because of changes in
is more than 3 pps higher than that of the standard the way GAAP earnings are calculated, particularly
CAPE model using reported earningsand only with respect to mark-to-market mandates, the use
1.45 pps below the 6.70% long-term average real of S&P 500 reported earnings in CAPE calculations
return on equities. biases CAPE ratios upward and forecasts of real
Figure 4 depicts the CAPE ratio calculated for stock returns downward. In this research, I take no
19872014 by using the price index portfolio for position on whether the recent changes in accounting
S&P reported earnings, S&P operating earnings, conventions are right or whether current earnings
and NIPA profits. All these series are plotted rela- are too high or too low relative to some true value.
tive to their long-term mean as calculated from the Accurate evaluation of the CAPE model requires
2.5
2.0
1.5
1.0
0.5
0
87 91 95 99 03 07 11
2.5
2.0
1.5
1.0
0.5
0
87 91 95 99 03 07 11
that the earnings series used observe consistent and Schrand of the accounting department at the Wharton
uniform conventions across time, and the reported School of the University of Pennsylvania for the inter-
earnings series computed by Standard & Poors does pretation and use of many current accounting practices.
not conform to this requirement. The CAPE model Editors note: This article was reviewed via our double-
estimated with corporate NIPA profits instead of the blind peer review process. When the article was accepted
Standard & Poors reported earnings series exhibited for publication, the author thanked the reviewer in his
higher explanatory power and forecast significantly acknowledgments, and the reviewer was asked whether he
higher stock returns. agreed to be identified in the authors acknowledgments.
Clifford Asness was the reviewer for this article.
Notes
1. See also Campbell and Shiller (1988). On 21 July 1996, Robert 10. The International Financial Reporting Standards (IFRS) allow
Shiller posted on his website his paper Price Earnings write-ups of asset values in some situations.
Ratios as Forecasters of Returns: The Stock Market Outlook 11. Operating earnings for the financial sector grew 39%, com-
in 1996, which served as the basis for his presentation to pared with 47% for all S&P 500 companies.
the Federal Reserve. 12. That is exactly how Standard & Poors justified its earnings
2. More exactly, each month over the past 10 years is repre- computation procedure in a bulletin posted on its website
sented by the 12-month-lagged per share earnings, which after I published my criticism of S&Ps methodology; see
are deflated by the CPI (consumer price index) in each Siegel (2009).
month and the 120 months of lagged data are then averaged. 13. A more rigorous proof of this statement is based on the
Monthly data are obtained by interpolating quarterly data facts that the value of equity is an option on the value of
since 1926 and annual data before 1926. For more details on the company and that the sum of the values of 500 options
the data series, see Shiller (1990, 2000). on each company must exceed the value of an option on
3. The CAPE ratio is calculated from 1881 on because 10 years the earnings of a hypothetical conglomerate that contains
of past earnings are required to compute the ratio. each S&P 500 company.
4. Shiller (1996) forecast that the S&P 500 Index would decline 14. One procedure to reduce the bias is to weight the losses or
by 38.07% over the next 10 years. Although the S&P 500 gains of companies by their market value in the same way
appreciated by 41% over that period and real annual stock that Standard & Poors does when it calculates returns. In this
returns averaged 5.6%, the S&P 500 fell more than 60% from case, outsized losses of companies selling at low valuations
October 2007 to March 2009, partly vindicating Shillers are discounted. This procedure has little impact during bull
bearishness. markets but would have increased reported per share earnings
5. This estimate is computed by determining the real price path for the S&P 500 in 2008 by nearly 80%.
that keeps the CAPE ratio constant at 25.04 for each of the 15. In particular, tax accounting measures come from the IRS
next 10 years, assuming that the future growth of real divi- (Statistics of Income (SOI): Corporation Income Tax Returns):
dends and earnings per share equals the historical average..
6. Some researchers (e.g., Arnott and Asness 2003) have claimed 16. The actual S&P divisor (published on the Standard & Poors
that a lower dividend payout ratio does not lead to higher website) is used for 19642013 to deflate real NIPA profits.
future per share earnings growth because management does The average change in the divisor is 1.36% a year, and this
not effectively use the cash saved from lower dividends to change is extended back to the beginning of the NIPA series
increase the companys value. Whatever the reason for the in 1928. The cumulative change in the divisor reduces real
higher growth rate, a change in the growth trend of real per NIPA profits in 2013 by a factor of 3.13. This NIPA per share
share earnings will raise the CAPE ratio. profit series is then spliced to the S&P 500 reported earnings
7. When companies report their earnings, they frequently series by equating the 10-year averages for 19291939 for
exclude additional items, such as litigation costs, pension costs both series.
associated with changing market rates or return assumptions, 17. Moreover, companies regularly expense R&D costs instead of
stock option expenses, and so on. capitalizing them, a practice that understates true earnings.
8. The terms non-GAAP earnings, pro forma earnings, and earnings 18. For more details, see Dichev and Tang (2008); Donelson et al.
from continuing operations all refer to operating earnings. (2011); Srivastava (2014)all of whom agree that changes in
9. These rules are no longer called FAS. All the rules are now accounting standards are a significant source of variability,
organized in one accounting standards codification (ASC), though they differ on whether it is the primary source.
and the FASB periodically issues an accounting standards
update (ASU).
Bibliography
Arnott, Robert D., and Clifford S. Asness. 2003. Surprise! High Bianco, David, and Ju Wang. 2015. Financial Write-Downs
Dividends = Higher Earnings Growth. Financial Analysts Journal, and Loan Loss Provisions. Deutsche Bank US Equity Strategy
vol. 59, no. 1 (January/February): 7087. (11 August).
Bunn, Oliver D., and Robert J. Shiller. 2014. Changing Times, Mehra, Rajnish, and Edward C. Prescott. 1985. The Equity
Changing Values: A Historical Analysis of Sectors within the US Premium: A Puzzle. Journal of Monetary Economics, vol. 15, no.
Stock Market 18722013. Working paper (May). 2 (March): 145161.
Campbell, John Y., and Robert J. Shiller. 1988. Stock Prices, Shiller, Robert. 1990. Market Volatility. Cambridge, MA: MIT Press.
Earnings, and Expected Dividends. Journal of Finance, vol. 43,
no. 3 (July): 661676. . 1996. Price Earnings Ratios as Forecasters of Returns: The
Stock Market Outlook in 1996 (21 July):.
. 1998. Valuation Ratios and the Long-Run Stock Market edu/~shiller/data/peratio.html.
Outlook. Journal of Portfolio Management, vol. 24, no. 2 (Winter):
1126. . 2000. Irrational Exuberance. Princeton, NJ: Princeton
University Press.
Dichev, Ilia D., and Vicki Wei Tang. 2008. Matching and the
Changing Properties of Accounting Earnings over the Last 40 Siegel, Jeremy J. 2009. The S&P Gets Its Earnings Wrong. Wall
Years. Accounting Review, vol. 83, no. 6 (November): 14251460. Street Journal (25 February): A13.
Donelson, Dain C., Ross Jennings, and John McInnis. 2011. Smithers, Andrew. 2014a. True Profits and Published
Changes over Time in the Revenue-Expense Relation: Accounting Profits. Financial Times (18 September):
or Economics? Accounting Review, vol. 86, no. 3 (May): 945974. andrew-smithers/2014/09/true-profits-and-published-profits.
Greenspan, Alan. 1996. The Challenge of Central Banking in a Srivastava, Anup. 2014. Why Have Measures of Earnings Quality
Democratic Society. Speech delivered at the Annual Dinner and Changed over Time? Journal of Accounting and Economics, vol. 57,
Francis Boyer Lecture of the American Enterprise Institute for no. 23 (AprilMay): 196217.
Public Policy Research, Washington, DC (5 December).
Hodge, Andrew W. 2011. Comparing NIPA Profits with S&P 500
Profits. Survey of Current Business, vol. 91, no. 3 (March): 2227.
2016 FINANCIAL
ANALYSTS SEMINAR
Improving Investment Decisions
1821 JULY 2016
University of Chicago Gleacher Center
Chicago, Illinois, United States
SPEAKERS INCLUDE
GREG VALLIERE
Chief Global Strategist
Horizon Investments | https://pt.scribd.com/document/362679716/The-Shiller-CAPE-Ratio-a-new-look-2016-pdf | CC-MAIN-2019-35 | refinedweb | 5,435 | 52.7 |
Return data to an etcd server or cluster
python-etcd
In order to return to an etcd server, a profile should be created in the master configuration file:
my_etcd_config: etcd.host: 127.0.0.1 etcd.port: 2379
It is technically possible to configure etcd without using a profile, but this is not considered to be a best practice, especially when multiple etcd servers or clusters are available.
etcd.host: 127.0.0.1 etcd.port: 2379
Additionally, two more options must be specified in the top-level configuration in order to use the etcd returner:
etcd.returner: my_etcd_config etcd.returner_root: /salt/return
The
etcd.returner option specifies which configuration profile to use. The
etcd.returner_root option specifies the path inside etcd to use as the root
of the returner system.
Once the etcd options are configured, the returner may be used:
CLI Example:
salt '*' test.ping --return etcd
A username and password can be set:
etcd.username: larry # Optional; requires etcd.password to be set etcd.password: 123pass # Optional; requires etcd.username to be set
Authentication with username and password, currently requires the
master branch of
python-etcd.
You may also specify different roles for read and write operations. First, create the profiles as specified above. Then add:
etcd.returner_read_profile: my_etcd_read etcd.returner_write_profile: my_etcd_write
The etcd returner has the following schema underneath the path set in the profile:
The job key contains the jid of each job that has been returned. Underneath this job are two special keys. One of them is ".load.p" which contains information about the job when it was created. The other key is ".lock.p" which is responsible for whether the job is still valid or it is scheduled to be cleaned up.
The contents if ".lock.p" contains the modifiedIndex of the of the ".load.p" key and when configured via the "etcd.ttl" or "keep_jobs" will have the ttl applied to it. When this file is expired via the ttl or explicitly removed by the administrator, the job will then be scheduled for removal.
This key is essentially a namespace for all of the events (packages) that are submitted to the returner. When an event is received, the package for the event is written under this key using the "tag" parameter for its path. The modifiedIndex for this key is then cached as the event id although the event id can actually be arbitrary since the "index" key contains the real modifiedIndex of the package key.
Underneath the minion.job key is a list of minions ids. Each minion id contains the jid of the last job that was returned by the minion. This key is used to support the external job cache feature of Salt.
Underneath this key is a list of all of the events that were received by the returner. As mentioned before, each event is identified by the modifiedIndex of the key containing the event package. Underneath each event, there are three sub-keys. These are the "index" key, the "tag" key, and the "lock" key.
The "index" key contains the modifiedIndex of the package that was stored under the event key. This is used to determine the original creator for the event's package and is used to keep track of whether the package for the event has been modified by another event (since event tags can be overwritten preserving the semantics of the original etcd returner).
The "lock" key is responsible for informing the maintenance service that the event is still in use. If the returner is configured via the "etcd.ttl" or the "keep_jobs" option, this key will have the ttl applied to it. When the "lock" key has expired or is explicitly removed by the administrator, the event and its tag will be scheduled for removal. The createdIndex for the package path is written to this key in case an application wishes to identify the package path by an index.
The other key under an event, is the "tag" key. The "tag" key simply contains the path to the package that was registered as the tag attribute for the event. The value of the "index" key corresponds to the modifiedIndex of this particular path.
salt.returners.etcd_return.
clean_old_jobs()¶
Called in the master's event loop every loop_interval. Removes any jobs, and returns that are older than the etcd.ttl option (seconds), or the keep_jobs option (hours).
salt.returners.etcd_return.
event_return(events)¶
Return event to etcd server
Requires that configuration enabled via 'event_return' option in master config.
salt.returners.etcd_return.
get_fun(fun)¶
Return a dict containing the last function called for all the minions that have called a function.
salt.returners.etcd_return.
get_jid(jid)¶
Return the information returned when the specified job id was executed.
salt.returners.etcd_return.
get_jids()¶
Return a list of all job ids that have returned something.
salt.returners.etcd_return.
get_jids_filter(count, filter_find_job=True)¶
Return a list of all job ids :param int count: show not more than the count of most recent jobs :param bool filter_find_jobs: filter out 'saltutil.find_job' jobs
salt.returners.etcd_return.
get_load(jid)¶
Return the load data that marks a specified jid.
salt.returners.etcd_return.
get_minions()¶
Return a list of all minions that have returned something.
salt.returners.etcd_return.
prep_jid(nocache=False, passed_jid=None)¶
Do any work necessary to prepare a JID, including sending a custom id.
salt.returners.etcd_return.
returner(ret)¶
Return data to an etcd profile.
salt.returners.etcd_return.
save_load(jid, load, minions=None)¶
Save the load to the specified jid. | https://docs.saltstack.com/en/develop/ref/returners/all/salt.returners.etcd_return.html | CC-MAIN-2019-35 | refinedweb | 915 | 57.87 |
By default, automatic upgrades are enabled for Google Kubernetes Engine (GKE) clusters and node pools.
This page explains how to manually request an upgrade or downgrade for a GKE cluster or its nodes. You can learn more about how automatic and manual cluster upgrades work. You can also control when auto-upgrades can and cannot occur by configuring maintenance windows and exclusions.
New versions of GKE are announced regularly. To learn about about available versions, see Versioning. To learn more about clusters, see Cluster architecture. For guidance on upgrading clusters, see Best practices for upgrading
Save zonal persistent disks in the Compute Engine documentation.
About upgrading clusters
A cluster's control plane and nodes are upgraded separately.
Cluster control planes are always upgraded on a regular basis, regardless of whether your cluster is enrolled in a release channel or not.
Limitations
Alpha clusters cannot be upgraded.
Supported versions
The release notes announce when new versions become available and when older versions are no longer available. At any time, you can list all supported cluster and node versions using this command:
gcloud container get-server-config
Known issues
Although automatic upgrades might encounter the issue, the automatic upgrade
process forces the nodes to upgrade. However, the upgrade takes an extra hour
for every node in the
istio-system namespace that violates the
PodDisruptionBudget.
Downgrading limitations
Downgrading a cluster is not recommended. Nodes can be downgraded to a patch version older than the cluster.9": specified version is not newer than the current version.
Upgrading the cluster
Google upgrades clusters and nodes automatically. For more control over which auto-upgrades your cluster and its nodes receive, you can enroll it in a release channel.
To learn more about managing your cluster's GKE version, see Upgrades.
You can initiate a manual upgrade any time after a new version becomes available.
Manually upgrading the version, run the following command:
gcloud container clusters upgrade CLUSTER_NAME --master
To upgrade to a specific version that is not the default, run the following command:
gcloud container clusters upgrade CLUSTER_NAME \ --master --cluster-version VERSION
Refer to the
gcloud container clusters upgrade
documentation.
Console
To manually update your cluster control plane, perform the following steps:
Visit the Google Kubernetes Engine menu in Google Cloud Console.
Visit the Google Kubernetes Engine menu
Click the desired cluster name.
Under Cluster basics, click edit Upgrade Available next to Version.
Select the desired version, then click Save Changes.
Downgrading clusters
To downgrade a cluster to a previous patch version, change the cluster control plane version with the following command:
gcloud container clusters upgrade CLUSTER_NAME \ --master --cluster-version VERSION
Disabling cluster auto-upgrades
Infrastructure security is high priority for GKE, and as such control planes are upgraded on a regular basis, and cannot be disabled. However, you can apply maintenance windows and exclusions to temporarily suspend upgrades for control planes and nodes.
Although it is not recommended, you can disable node auto-upgrade.
Upgrading node pools
By default, a cluster's nodes have auto-upgrade enabled, and it is recommended that you do not disable it.
When a node pool is upgraded, you can configure surge upgrade settings to control how many nodes GKE upgrades at once as well as how disruptive the upgrade is to workloads. By default, GKE upgrades one node at a time.
While a node is being upgraded, GKE stops scheduling new Pods onto it, and attempts to schedule its running Pods onto other nodes. This is similar to other events that re-create the node, such as enabling or disabling a feature on the node pool.
The upgrade is only complete when all nodes have been recreated and the cluster is in the desired state. When a newly-upgraded node registers with the control plane, GKE marks the node as schedulable.
New node instances run the desired Kubernetes version as well as:
- The node image
- The Docker daemon, if applicable
kubelet
kube-proxy
Manually upgrade a node pool
You can manually upgrade a node pool version to match the version of the node pools to a version compatible with the control plane, using
the Google Cloud Console or the
gcloud command-line tool.
gcloud
The following command upgrades your nodes to the version that your control plane is running:
gcloud container clusters upgrade CLUSTER_NAME \ --node-pool=NODE_POOL_NAME
Replace CLUSTER_NAME with the name of the cluster to be upgraded.
To specify a different version of GKE on nodes, use the
optional
--cluster-version flag:
gcloud container clusters upgrade CLUSTER_NAME \ --node-pool=NODE_POOL_NAME \ --cluster-version VERSION
Replace
VERSION with the Kubernetes version to which
the nodes are upgraded. For example,
--cluster-version=1.7.2 or
cluster-version=latest.
For more information about specifying versions, see Versioning.
For more information, refer to the
gcloud container clusters upgrade documentation.
Console
To upgrade a node pool using Cloud Console, perform the following steps:
Visit the Google Kubernetes Engine menu in Cloud Console.
Visit the Google Kubernetes Engine menu
Next to the cluster you want to edit, click more_vert Actions, then click edit Edit.
On the Cluster details page, click the Nodes tab.
In the Node Pools section, click the name of the node pool that you want to upgrade.
Click edit Edit.
Click Change under Node version.
Select the desired version from the Node version drop-down list, then click Change.
Downgrading node pools
Node pools can be downgraded to a patch version older than the cluster version.
Checking node pool pool upgrade
You can cancel an upgrade at any time. When you cancel an upgrade:
- Nodes that have started the upgrade complete it.
- Nodes that have not started the upgrade do not upgrade.
- Nodes that have already successfully completed the upgrade are unaffected and are not rolled back.
Get the upgrade's operation ID using the following command:
gcloud container operations list
Run the following command to cancel the upgrade:
gcloud beta container operations cancel OPERATION_ID
Refer to the
gcloud container operations cancel
documentation.
Rolling back a node pool NODE_POOL_NAME \ --cluster CLUSTER_NAME
Replace the following:
NODE_POOL_NAME: the name of the node pool to roll back.
CLUSTER_NAME: the name of the cluster from which to roll back the node pool.
Refer to the
gcloud container node-pools rollback
documentation.
Changing surge upgrade parameters
Surge Upgrades allow you to change the number of nodes GKE upgrades at one time and the amount of disruption an upgrade makes on your workloads.
The
max-surge-upgrade and
max-unavailable-upgrade flags are defined for
each node pool. For more information on chosing the right parameters, go to
Determining your optimal surge configuration.
You can change these settings when creating or updating a cluster or node pool.
The following variables are used in the commands mentioned below:
CLUSTER_NAME: the name of the cluster for the node pool.
COMPUTE_ZONE: the zone for the cluster.
NODE_POOL_NAME: the name of the node pool.
NUMBER_NODES: the number of nodes in the node pool in each of the cluster's zones.
SURGE_NODES: the number of extra (surge) nodes to be created on each upgrade of the node pool.
UNAVAILABLE_NODES: | https://cloud.google.com/kubernetes-engine/docs/how-to/upgrading-a-cluster?hl=da | CC-MAIN-2021-17 | refinedweb | 1,177 | 54.42 |
specifies the width of the input field.
specifies the power of 10 by which to divide the input value. This argument is optional. If you specify d, the RBw.d informat divides the input value by the 10d value. SAS uses the d value even if the input data contains decimal points.
The RBw.d informat reads numeric data that is stored in native real-binary (floating-point) notation. Numeric data for scientific calculations is often stored in floating-point notation. (SAS stores all numeric values in floating-point notation.) A floating-point value consists of two parts: a mantissa that gives the value and an exponent that gives the value's magnitude.
It is usually impossible to key in floating-point binary data directly from a terminal, but many programs write floating-point binary data. Use caution if you are using the RBw.d informat to read floating-point data created by programs other than SAS because the RBw.d informat is designed to read-only double-precision data.
Because the RBw.d informat is designed to read-only double-precision data, it supports widths of less than 8 bytes only for those applications that truncate numeric data for space-saving purposes. RB4., for example, does not expect a single-precision number that is truncated to 4 bytes.
External programs such as those written in C and FORTRAN can produce only single- or double-precision floating-point numbers. No length other than 4 or 8 bytes is allowed. The RBw.d informat allows a length of 3 through 8 bytes, depending on the storage you need to save.
The FLOAT4. informat has been created to read a single-precision, floating-point number. If you read the hexadecimal notation 3F800000 with FLOAT4., the result is a value of 1.
To read data created by a C or FORTRAN program, you need to decide on the proper informat to use. If the floating-point numbers require an 8-byte width, you should use the RB8. informat. If the floating-point numbers require a 4-byte width, you should use FLOAT4.
For more information about OpenVMS floating-point representation, see HP OpenVMS Programming Concepts Manual, Volume II, Part I, OpenVMS Programming Interfaces: Calling a System Routine.
Consider how the value of 1 is represented in single-precision and double-precision notation. For single-precision, the hexadecimal representation of the 4 bytes of data is 3F800000 . For double-precision, the hexadecimal representation is 3FF0000000000000 . The digits at the beginning of the data are different, indicating a different method of storing the data.
#include <stdio.h> main() { FILE *fp; float x[3]; fp = fopen("test.dat","wb"); x[0] = 1; x[1] = 2; x[2] = 3; fwrite((char *)x,sizeof(float),3,fp); fclose(fp); }
The file TEST.DAT will contain, in hexadecimal notation, 3f8000004000000040400000 .
Reading Binary Data under OpenVMS
Copyright © 2009 by SAS Institute Inc., Cary, NC, USA. All rights reserved. | http://support.sas.com/documentation/cdl/en/hostvms/62450/HTML/default/alp-inf-rb.htm | crawl-003 | refinedweb | 488 | 50.94 |
simple dedicated camera for live streaming to YouTube.
My idea is to make a simple video camera using a Raspberry Pi 3, 2.8".
Don't feel like reading? Feel free to watch the video instead!
Step 1: Parts You Will Need
Along with various tools (soldering equipment, 3D printer, dremel, etc), I used these parts in order to complete this project:
Step 2: Setting Up the Raspberry Pi
As with any project using a Raspberry Pi, the first step is to get it set up. To do this, you'll need:
- A Raspberry Pi 3
- A micro SD Card (8gb or greater)
- HDMI or composite monitor and cable
- Keyboard and Mouse
- Power supply
With the hardware set, we next need to load the software onto the PI. You can download the latest Raspbian software from here. It's a large file, so it may take a while to download.
But once it has, you can burn it to your SD card using the Etcher.io software for Windows, Mac and Linux.
After you've successfully copied the files to the SD card, you can put it in your Raspberry Pi, plug in the monitor, keyboard, mouse and then the power. After a minute or so, it should boot to the Desktop.
The first thing you want to do is connect to your internet by clicking on the internet icon in the upper right and selecting your wireless network. Then inter your password and click "connect". Next you can right click on that same icon, and select "Wireless and Wired Network Settings". Here, you'll want to make sure wlan0 is selected and then give it a static IP address that matches the IP scheme of your network.
To finish up, click on the start menu in the upper left go to Preferences > Raspberry Pi Configuration. On the "Interfaces" tab, select to enable SSH. Then on the "Localisation" tab, set your keyboard language settings to match your country. Then reboot your machine. Now you should be able to log in from a remote computer using SSH.
Step 3: Adding the Camera
The camera I'm using is the Raspberry Pi Camera Module v2. I like it because it's very flat in shape and doesn't take up any USB ports. It has it's own dedicated IO port. So with the Pi off, insert the Camera Module (as seen below). Then power your PI back on.
Before we can use the camera, we have to enable it. So after the Pi boots back up, you can SSH into it and run
sudo raspi-config
#Choose Interfacing Options > Camera > Enable
sudo reboot
Once your Pi boots back up, you should be able to utilize the camera.
Step 4: Setting Up the Touchscreen
I'm using an Adafruit 2.8" Touchscreen LCD. It comes connected with header pins that make it easy to fit right on top of the Raspberry Pi GPIO Pins.
Adafruit has some great documentation about setting up the Raspberry Pi, and they even have their own Raspbian Image that you can download and install with everything already on it. Sadly, the pre-made image didn't work for me, which is why I installed a fresh version of Raspbian.
The LCD requires a Kernel in order for it to work, so I'll need to download it manually from the Adafruit website (these steps are also on their instruction page).
sudo apt-get update
curl -SLs | sudo bash
sudo apt-get install raspberrypi-bootloader
Installing the bootloader will take a few minutes, but when it's done, you can shutdown your Pi, and unplug any other external monitors before turning it back on.
Once the Pi boots back up, we'll need to modify the Pi's boot config file and adjust it so that it displays to the LCD properly.
sudo nano /boot/config.txt
and then add this text to the bottom of it:
dtparam=i2c_arm=on
dtparam=i2s=on
dtparam=spi=on
dtoverlay=pitft28-resistive,rotate=90,speed=32000000,fps=20
In order to get anything to display on the LCD, we need to tell the operating system to use it as it's primary display. To do this, you can use these commands:
export FRAMEBUFFER=/dev/fb1
startx
Now we can test it by displaying an image on it using the fbi (not that F.B.I.) image viewer.
sudo apt-get install fbi
wget -O image.png
sudo fbi -T 2 -d /dev/fb1 -noverbose -a image.png
The LCD part works. Now we need to test the touch screen. By default, the touchscreen should work with the Adafruit kernel. But there are a few commands you can run to help calibrate it.
sudo TSLIB_FBDEVICE=/dev/fb1 TSLIB_TSDEVICE=/dev/input/touchscreen ts_calibrate
sudo TSLIB_FBDEVICE=/dev/fb1 TSLIB_TSDEVICE=/dev/input/touchscreen ts_test
These commands will give you visual feedback on your screen that you can touch to calibrate your screen.
Step 5: Issue With Adafruit PiTFT Touchscreens
If you have an Adafruit PiTFT touchscreen like I do, you may find that no matter how much you calibrate the LCD, it still won't work with your Pygame code. This is because there is an issue with the Adafruit touchscreens and the current version of Raspbbian.
The touchscreens work well with the Raspbian "Wheezy" distro, but they don't play well with Raspbian "Jessie". There is a workaround, however, to get it functional again. It involves downloading and installing the "Wheezy" driver.
#enable wheezy package sources echo "deb main " >> /etc/apt/sources.list.d/wheezy.list #set stable as default package source (currently jessie) echo "APT::Default-release \"stable\"; " >> /etc/apt/apt.conf.d/10defaultRelease #set the #install apt-get update apt-get -y --force-yes install libsdl1.2debian/wheezy
Running the above code should fix the issue and the touchscreen will now work with Pygame. So let's go ahead and create our own test script that sets a background, creates a button, and checks for touch input to perform an action.
pygame_test.py
import pygame import os from time import sleep import random os.environ['SDL_FBDEV']= '/dev/fb1' os.environ["SDL_MOUSEDEV"] = '/dev/input/touchscreen' os.environ['SDL_MOUSEDRV'] = 'TSLIB' pygame.init() lcd = pygame.display.set_mode((320,240)) lcd.fill((255,0,0)) def make_button(text, xpo, ypo, color): font=pygame.font.Font(None,24) label=font.render(str(text),1,(color)) lcd.blit(label,(xpo,ypo)) pygame.draw.rect(lcd, cream, (xpo-5,ypo-5,110,35),1) def random_color(): rgbl=[255,0,0] random.shuffle(rgbl) return tuple(rgbl) blue = 26, 0, 255 white = 255, 255, 255 cream = 254, 255, 250 lcd.fill(blue) pygame.mouse.set_visible(False) while 1: make_button("Menu item 1", 20, 20, white) for event in pygame.event.get(): if (event.type == pygame.MOUSEBUTTONDOWN): print "screen pressed" lcd.fill(random_color()) pos = (pygame.mouse.get_pos()[0],pygame.mouse.get_pos()[1]) print pos pygame.display.update()
Step 6: Adding a Microphone
Since the Raspberry Pi doesn't have audio input by default, we're gonna have to use a USB based audio input. I just got a cheap mini USB microphone and plugged it in.
The Pi should automatically detect it and make it useable. I'm going to be using the microphone in conjunction with the Alsa audio library, so we'll need to install that first. Then we can test out the microphone by making a simple 30 second recording (make sure to have some speakers or headphones plugged in in order to hear the playback).
sudo apt-get install libasound2-dev arecord -D plughw:1 --duration=30 -f cd -vv ~/test.wav omxplayer -p -o hdmi ~/test.wav
Step 7: Streaming to Youtube
Although I'm using Youtube in this tutorial, the concept should also work with other streaming services like Twitch.tv and FacebookLive. Most of these streaming services use a protocol called Real-Time Messaging Protocol (RTMP). So in order to stream to Youtube, we'll need the RTMP URL as well as a private key for our specific stream.
To get your key and URL, go to your Youtube Dashboard and select "Live Streaming" and select either "Stream now" or "Events" and create a new event.
Following those steps will allow you to generate a new RTMP URL and private key. With our URL and key, we can now turn back to the Raspberry Pi to make a streaming program using Python. When it comes to streaming from a Raspberry Pi, there are actually several different methods. One of the easier ways is by installing avconv (part of the libav-tools package) and using raspivid to pipe the stream to the RTMP URL. Here's a sample of how that would work from the command line:
sudo apt-get install libav-tools]
This method might work alright through the command line, but whenever I tried to incorporate it into python code, it wouldn't work. There seems to be an issue with avconv and Youtube.
The program that worked the best for me was FFMpeg. Most of you may know that avconv is a 99% compatible replacement for FFMpeg, but Youtube streaming seems to fall within that 1%. Those of you that have worked with FFMpeg on the Raspberry Pi before know how difficult (and how long) it can be to install. I clocked it at just slightly over an hour from beginning to end using a Raspberry Pi 3 using the steps below (based on these steps).
sudo sh -c 'echo "deb <a href=""> </a> jessie main non-free" >> /etc/apt/sources.list.d/deb-multimedia.list' sudo sh -c 'echo "deb-src <a href=""> </a> jessie main non-free" >> /etc/apt/sources.list.d/deb-multimedia.list' sudo apt-get update sudo apt-get install deb-multimedia-keyring sudo apt-get update sudo apt-get install build-essential libmp3lame-dev libvorbis-dev libtheora-dev libspeex-dev yasm libopenjpeg-dev libx264-dev libogg-dev cd ~ sudo git clone git://git.videolan.org/x264 cd x264/ sudo ./configure --host=arm-unknown-linux-gnueabi --enable-static --disable-opencl sudo make -j4 sudo make install cd ~ sudo git clone <a href=""> </a> cd FFmpeg/ sudo ./configure --arch=armel --target-os=linux --enable-gpl --enable-libx264 --enable-nonfree sudo make -j4 sudo make install
Now that you're back from a nice break after letting all this install, we can finally write a simple streaming script to test it out. Basically we can use the subprocess PIPE command to emulate entering the command in a terminal and then "pipe" the camera stream through FFMpeg to Youtube. Getting the FFMpeg command just right is kinda tricky, but the one I used below seems to work well for me. The value that you might need to adjust is the itsoffset value. It's what helps sync the audio with the video. It basically "offsets" the video by a number in seconds. In my example, the offset is for 5.5 seconds. So if your audio and video or out of sync, you can try adjusting this number. NOTE*** If you start getting a lot of "Alsa X Buffer" errors, then that means your itsoffest is probably too high. Adjusting it to lower will fix this issue. Depending on the type of microphone your using, you may also need to change the hw value in the script. Mine is listed as card 1, so my hw value is 1,0 below. You can find what your audio device is listed as by typing the command:
arecord -l
This will list all of your recording devices and tell you what card number they're listed as.
stream_test.py
#!/usr/bin/env python3 import subprocess import picamera import time(resolution=(640, 480), framerate=25) try: now = time.strftime("%Y-%m-%d-%H:%M:%S") camera.framerate = 25 camera.vflip = True camera.hflip = True camera.start_recording(stream.stdin, format='h264', bitrate = 2000000) while True: camera.wait_recording(1) except KeyboardInterrupt: camera.stop_recording() finally: camera.close() stream.stdin.close() stream.wait() print("Camera safely shut down") print("Good bye")
Step 8: Creating a Touchscreen Interface
With the touchscreen, camera, and Youtube streaming all working, all we need now is a simple interface to control it. My vision is to have it so that you can preview the camera, using the touchscreen as a view finder, and then click a button to stream it to Youtube.
The vision I have is very similar to the Adafruit Pi Camera project. I like it because it uses the camera feed as the background of the touchscreen. It basically uses the io.BytesIO library to stream the buffer of camera images to use as background images on the touchscreen. We want to have 3 buttons on the touchscreen:
- Stream - Pressing this will stream the camera and audio to Youtube
- Preview - Pressing this will show a preview of the camera on the LCD screen
- Power - Pressing this will shutdown the Operating System
So combining that with our streaming code, and our touchscreen code, I came up with something like this:
youtube_stream.py
#!/usr/bin/env python import os import time import io import pygame import picamera import subprocess os.environ['SDL_VIDEODRIVER'] = 'fbcon' os.environ['SDL_FBDEV'] = '/dev/fb1' os.environ['SDL_MOUSEDEV'] = '/dev/input/touchscreen' os.environ['SDL_MOUSEDRV'] = 'TSLIB' pygame.init() lcd = pygame.display.set_mode((0,0), pygame.FULLSCREEN) pygame.mouse.set_visible(False) img_bg = pygame.image.load('/home/pi/camera_bg.jpg') preview_toggle = 0 stream_toggle = 0 blue = 26, 0, 255 white = 255, 255, 255 cream = 254, 255, 250() camera.resolution = (1080, 720) camera.rotation = 180 camera.crop = (0.0, 0.0, 1.0, 1.0) camera.framerate = 25 rgb = bytearray(camera.resolution[0] * camera.resolution[1] * 3) def make_button(text, xpo, ypo, color): font=pygame.font.Font(None,24) label=font.render(str(text),1,(color)) lcd.blit(label,(xpo,ypo)) pygame.draw.rect(lcd, cream, (xpo-5,ypo-5,150,35),1) def stream(): camera.wait_recording(1) def shutdown_pi(): os.system("sudo shutdown -h now") def preview(): stream = io.BytesIO() camera.vflip = True camera.hflip = True camera.capture(stream, use_video_port=True, format='rgb', resize=(320, 240)) stream.seek(0) stream.readinto(rgb) stream.close() img = pygame.image.frombuffer(rgb[0:(320 * 240 * 3)], (320, 240), 'RGB') lcd.blit(img, (0,0)) make_button("STOP", 175,200, white) pygame.display.update() try: while True: if stream_toggle == 1: stream() elif preview_toggle == 1: preview() else: click_count = 0 lcd.fill(blue) lcd.blit(img_bg,(0,0)) make_button("STREAM", 5, 200, white) make_button("PREVIEW",175,200, white) make_button("POWER", 200, 5, white) pygame.display.update() for event in pygame.event.get(): if (event.type == pygame.MOUSEBUTTONDOWN): pos = pygame.mouse.get_pos() if (event.type == pygame.MOUSEBUTTONUP): pos = pygame.mouse.get_pos() print pos x,y = pos if y > 100: if x < 200: print "stream pressed" if stream_toggle == 0 and preview_toggle == 0: stream_toggle = 1 lcd.fill(blue) lcd.blit(img_bg,(0,0)) make_button("STOP", 20, 200, white) pygame.display.update() camera.vflip=True camera.hflip = True camera.start_recording(stream_pipe.stdin, format='h264', bitrate = 2000000) elif preview_toggle == 1: preview_toggle = 0 lcd.fill(blue) lcd.blit(img_bg,(0,0)) make_button("STREAM", 5, 200, white) make_button("PREVIEW",175,200, white) pygame.display.update() else: stream_toggle = 0 lcd.fill(blue) make_button("STREAM", 5, 200, white) make_button("PREVIEW",175,200, white) pygame.display.update() camera.stop_recording() elif x > 225: print "preview pressed" if preview_toggle == 0 and stream_toggle == 0: preview_toggle = 1 lcd.fill(blue) make_button("STOP", 175,200, white) pygame.display.update() elif stream_toggle == 1: stream_toggle = 0 lcd.fill(blue) make_button("STREAM", 5, 200, white) make_button("PREVIEW",175,200, white) pygame.display.update() camera.stop_recording() else: preview_toggle = 0 lcd.fill(blue) make_button("STREAM", 5, 200, white) make_button("PREVIEW",175,200, white) pygame.display.update() except KeyboardInterrupt: camera.stop_recording() print ' Exit Key Pressed' finally: camera.close() stream_pipe.stdin.close() stream_pipe.wait() print("Camera safely shut down") print("Good bye")
Customize the script the way you want to make it work for you, and then test it out. Just run it using
sudo python youtube_stream.py
Then click on the "Preview" button to preview your camera. Press "Stop" to go back to the main menu. Then click the "Stream" button to start streaming to Youtube. Now you should be able to go to your Youtube Live dashboard and preview your live stream! Once you're happy with the results, the last thing to do is to make the script executable and add it to the Pi's rc.local file so that it auto-launches whenever the Pi boots up
sudo chmod +x youtube_stream.py sudo nano /etc/rc.local
Towards the bottom of the rc.local file, right before "exit 0", add this line:
sudo python /home/pi/youtube_stream.py &
Save it and reboot the Pi. Once it's through rebooting, you should see your new touchscreen interface!
Step 9: Adding a Power Source
Obviously we want to make this camera portable, so we're going to need a battery. I like to use "emergency cell phone chargers" because they can last for a while, they can be recharged, and a lot of them even have a built in USB cable that can plug directly into the Pi!
The only thing one of these battery banks doesn't have is an an/off switch. There are a couple ways to go about this: You could either solder a switch onto the battery bank yourself, or you could buy a premade micro-usb on/off switch, which is a much safer way to go than soldering near a lithium polymer battery.
This will take care of turning the power on and off, but it's generally not a good idea to cut the power to a Pi while it's running software. This can corrupt the software and/or the Pi itself. You eagle eyed code monkeys may have noticed that the code above generates a "Power" button that can shut down the Raspberry Pi OS.
So you can switch the USB cable "on" to power on the Pi, and then touch the "Power" touchscreen button to turn off the Raspberry Pi OS before switching the USB cable to "off".
Step 10: Making an Enclosure
The finishing touch for this project is 3D printing an epic case to contain everything! There are plenty of great CAD programs out there, but for simplicities sake, I'm using Tinkercad. You'll want to 3D print the enclosure using supports.
The LCD, Raspberry Pi and Camera should basically snap into place, as long as you're using the same parts as me.
The LiPo battery will sit in between the camera and the Pi, but you won't be able to plug the battery directly into the USB port of the Pi because there isn't enough room in the case. As an alternative, we can strip the wires coming from the battery and solder them to the PP2 and PP5 ports on the back of the Raspberry Pi Micro USB port.
I used hot glue to hold everything into place within the camera case, but DO NOT USE HOT GLUE DIRECTLY ON THE LIPO BATTERY!!! Once all the pieces are together, you can test it out. If it works, you can hot glue the two halves of the case together!
Step 11: Testing It Out!
With the pieces together, and your Youtube account open, turn it on and use the touchscreen interface to start streaming! Below is a sample recorded from a live stream done using this device.
Participated in the
Wireless Contest
Participated in the
Raspberry Pi Contest 2017
10 Discussions
1 year ago
I would add a mic jack so I could use my wireless lapel mic, that way I could get better audio. Just a thought.
Question 1 year ago
Hi, how are you? I have a question about this awesome project:
Can you make multiple cameras and use something like OBS to switch between them, still using YouTube live as your output source?
Thanks
1 year ago
Great project
Downfall is not everyone has hdmi moniter/tv like myself
can any version of raspberry pi be used ?
I was thinking of the one with yellow video connection
Reply 1 year ago
the pi 3 has a 4 pin headphone connector that has left right, video and ground. with the right cable you can use a standard monitor
Reply 1 year ago
Which version of pi are you reffering to ?
Thanks for answer(s)
Reply 1 year ago
Even the Raspberry Pi 3 has the ability to connect using a "yellow" connection. You just need to wire it directly to the board.
Reply 1 year ago
How do you do that ?
1 year ago
Wow! That is awesome! I really didn't expect video quality that good from that little camera module.
1 year ago
Very elegant. Exceptionally high standard of explanation and visuals. This I should receive a prize!
1 year ago
Dang, you got skills man! When I need a camera, I think: hmmm, let's see if Amazon has got something for cheap.
You: "guess it's time to make another one." | https://www.instructables.com/id/Youtube-Live-Streaming-Camera/ | CC-MAIN-2019-30 | refinedweb | 3,517 | 65.73 |
Couple of hints:
- Can be done in O(n) -> single pass through data
- No division necessary and single multiplications by R are all that's needed
- Using map(C++) or dict(Java, Python) is a must -> can be unordered map (saves O(logN))
- Try to think forward when reading a value -> will this value form part of a triplet later?
- No need to consider (R == 1) as a corner case
Very interesting problem and it took a while to think it through properly. If anyone is desperate for the code, drop me a message.
Took me forever to figure this out. It's a really cool problem - the breakthrough came when you realize that, since sequentiality is important, then the array should be walked in reverse because the only values you want to check are those at higher indeces than the one you are checking.
The other big thing to realize is that you're checking for two things, not just one - you're checking for the existence of a value r times the current value, or your checking for a pair that exists for the for the value that begin at r times the current value and also contain r times that value.
For example: Let's say r is 3. If you have a the value you're checking while iterating the array that is also 3, and there's a 9 and a 27 in the dictionary that you've been populating, you should have populated another dictionary and entry for the pair of the values (9, 27) because those are a pair where 27 is r times 9 and if we find a 3 at a lower index, then we know we have a triplet.
So the algorithm is: -- keep two dictionaries: 1. a dictionary to store the number of times each single value that is repeated in the array 2. a dictionary to store any pair of values that are i and (i * r) (using i as the key)
-- Walk the array backwards 1. if the pair dictionary has a value for r times the one you're checking, then you add the number of pairs to the overall count. 2. otherwise, if there's add a new pair and add it to the pair dictionary if there's a value r times the one you're checking in the single value dictionary. 3. otherwise, just add the value to the single value dictionary.
And that will do it.
In Python, O(N) time complexity:
def countTriplets(arr, r): count = 0 dict = {} dictPairs = {} for i in reversed(arr): if i*r in dictPairs: count += dictPairs[i*r] if i*r in dict: dictPairs[i] = dictPairs.get(i, 0) + dict[i*r] dict[i] = dict.get(i, 0) + 1 return count
This problem drove me crazy. Finally with the help of editorial and fellow hackerankers I was able to understand the solution. Also I felt this problem is slightly on the difficult side for beginners. The success perecentage of 42% and only around 5.5k submissions justifies it. Don't get disappointed if it doesen't click you. I had spend days trying to get my head over it. Here is the complete logic to help anyone :
Let's take an example to undertsand the core concept behind this problem : {1, 3, 3, 9, 3, 27, 81} . Let common ratio = 3.
1.We will consider every element to be our middle element during our iteration. For any such element a, the number of possible geometric pairs possible are, no. of a/r on the left of a x no. of axr on the right of a.
2.Lets take 9 as our element. 9/3 = 3. 9x3 = 27. The number of 3s present on left of 9 are 2. The number of 27s present on right of 9 is 1. Hence total no. of geometric pairs possible with 9 as the middle element is 2x1 = 2. Do this for all the elements and add them up to get the result.
3.We create an occurence map first and call it rightMap. Now for each element, we first decrement it's count by 1 from the rightMap. Now we check for the number of occurences of axr in the rightMap. ( Let me explain this step with a simple example , say the input is {1,1,1,1 } and ratio = 1, rightMap will be [1->4]. Now we need to check the number of times axr = 1 occurs on the right of a. We do this after decrementing the count of current value by 1 in the rightMap. So rightMap becomes [1->3] . 3 is the number of times aXr occurs on RHS of first 1 )
4.Now we check for a/r counts in left map. We multiply leftCount and rightCount and add them up for each element. The whole idea is that, for each element , leftMap contains the occurence map of the elements on the left of a and rightMap contains the occurence map of the elements on the right of a.
Here's my simple solution in java
static long countTriplets(List<Long> arr, long r) { Map<Long, Long> rightMap = getOccurenceMap(arr); Map<Long, Long> leftMap = new HashMap<>(); long numberOfGeometricPairs = 0; for (long val : arr) { long countLeft = 0; long countRight = 0; long lhs = 0; long rhs = val * r; if (val % r == 0) { lhs = val / r; } Long occurence = rightMap.get(val); rightMap.put(val, occurence - 1L); if (rightMap.containsKey(rhs)) { countRight = rightMap.get(rhs); } if (leftMap.containsKey(lhs)) { countLeft = leftMap.get(lhs); } numberOfGeometricPairs += countLeft * countRight; insertIntoMap(leftMap, val); } return numberOfGeometricPairs; } private static Map<Long, Long> getOccurenceMap(List<Long> test) { Map<Long, Long> occurenceMap = new HashMap<>(); for (long val : test) { insertIntoMap(occurenceMap, val); } return occurenceMap; } private static void insertIntoMap(Map<Long, Long> occurenceMap, Long val) { if (!occurenceMap.containsKey(val)) { occurenceMap.put(val, 1L); } else { Long occurence = occurenceMap.get(val); occurenceMap.put(val, occurence + 1L); } }
It really bugs me that all the examples are sorted but the problem description doesn't say that the array has to be sorted, and there's no human to ask if I'm allowed to assume that.
Python Single Traversal:
- Idea is to traverse in the opposite direction of the array, so that division can be avoided.
- Maintain 2 Dictionaries/Hash Maps:
- map_arr stores the frequency of the numbers encountered yet
- map_doubles stores the count of 2 sized tuples, which are basically the second and third element of a triplet
- As you go through the array in reverse, either the number encountered will be 1st, 2nd or 3rd number of a triplet it can possibly be a part of.
- If it were to be the 1st, that means, all the 2nd and 3rd must've been already seen in the array (which are suitable, since problem restriction i < j < k). So from all the doubles in the map_doubles, find the count of doubles that allow the 1st, i.e. x to be such that the triplet looks like (x, x.r, x.r.r).
- if it were to be the 2nd in the triplet, we would need to find all the 3rd number appropriate found in the map_arr yet.
- if it were to be the 3rd element, we just need to update in map_arr for that number, so that it can be used as a reference for future doubles.
- Count for all the cases when x is the first element, and return.
def countTriplets(arr, r): if len(arr) <= 2: return 0 map_arr = {} map_doubles = {} count = 0 # Traversing the array from rear, helps avoid division for x in arr[::-1]: r_x = r*x r_r_x = r*r_x # case: x is the first element (x, x*r, x*r*r) count += map_doubles.get((r_x, r_r_x), 0) # case: x is the second element (x/r, x, x*r) map_doubles[(x,r_x)] = map_doubles.get((x,r_x), 0) + map_arr.get(r_x, 0) # case: x is the third element (x/(r*r), x/r, x) map_arr[x] = map_arr.get(x, 0) + 1 return count
Sort 595 Discussions, By:
Please Login in order to post a comment | https://www.hackerrank.com/challenges/count-triplets-1/forum | CC-MAIN-2021-10 | refinedweb | 1,347 | 70.02 |
I am new to coding, so apologies if this sounds silly and stupid. Recently I was looking at some codes submitted by top coders at Google CodeJam and I noticed, nearly everyone includes LONG strings of code before the main code (lots #include and template) even if they don’t use it in the code. I understand they do this to make things easier, but I’d like to know what this practice is called and how can I create my own. Any places where I can learn about it?
I don’t think that there’s something special about it. Many of your own codechef submissions started with the following two lines:
#include <iostream> using namespace std;
Do you open an empty text editor and spend time typing these lines manually whenever solving a competitive programming problem? Or do you just copy/paste some code template, which already contains these lines?
It makes sense to prepare a code template with the necessary includes, some frequently used defines, the main function with fast i/o activation and maybe a few other things. Experienced people keep adding more things to their code templates whenever they notice that something can be reused in the future, so their templates grow big. The unnecessary parts of the code template don’t do any harm. And spending time on code cleanup to remove these unnecessary parts from your template is unreasonable during a contest.
So as i learn more and more about coding, I’ll slowly start building my own template overtime | https://discuss.codechef.com/t/what-are-the-huge-lines-of-code-added-before-the-main-code/95501 | CC-MAIN-2021-49 | refinedweb | 257 | 67.28 |
PyTorch item: Convert A 0-dim PyTorch Tensor To A Python Number
PyTorch item - Use PyTorch's item operation to convert a 0-dim PyTorch Tensor to a Python number
< > Code:
Transcript:
This video will show you how to use PyTorch’s item operation to convert a zero-dimensional PyTorch tensor to a Python number.
First, we import PyTorch.
import torch
Then we check what version of PyTorch we are using.
print(torch.__version__)
We are using PyTorch 0.4.1.
Let’s create a zero-dimensional PyTorch tensor.
zero_dim_example_tensor = torch.tensor(10)
Notice that we are not putting the 10 inside of brackets.
If we had, we would then be creating a one-dimensional tensor.
However, since we are creating a zero-dimensional example tensor, we did not use any bracket.
So we use the torch.tensor, and we assign it to the Python variable zero_dim_example_tensor.
Let’s print our Python variable:
print(zero_dim_example_tensor)
And we see that it is a PyTorch tensor with the number 10 inside of it.
Just to make sure, let’s use Python’s type operation to check the type.
type(zero_dim_example_tensor)
So we pass in the tensor created by torch.tensor, we use type, and we see that the class is torch.Tensor.
We’re then going to use PyTorch’s shape operation to check that it is in fact a zero-dimensional tensor.
zero_dim_example_tensor.shape
We can see that it is an empty list which signifies that it has zero dimensions.
To convert the zero-dimensional PyTorch tensor to a Python number, let’s use PyTorch’s item operation.
converted_python_number = zero_dim_example_tensor.item()
So we have our tensor, then we’re going to use the item operation, and we’re going to assign the value returned to the Python variable converted_python_number.
Let’s print this value:
print(converted_python_number)
And we see that it is the number 10.
Then we can use Python’s type operation again to make sure that we have a number rather than a PyTorch tensor.
type(converted_python_number)
And we see that it is a Python class of int.
So this 10 is an integer number.
Perfect! We were able to use PyTorch’s item operation to convert a zero-dimensional PyTorch tensor to a Python number. | https://aiworkbox.com/lessons/pytorch-item-convert-a-0-dim-pytorch-tensor-to-a-python-number | CC-MAIN-2020-40 | refinedweb | 377 | 56.55 |
Rails Form Objects
When I started learning Rails, one the first rules of thumb I’ve stumbled upon was “fat model, skinny controller” rule. Being enthusiastic for new things as I am, I immediately took it for face value. Which obviously led to bloated models and spaghetti callbacks.
Time passed and I was happy with the things they were until I’ve seen Gary Bernhardt talking about Service Objects in his Destroy All Software screencast. At the same time I’ve heard Ruby Rogues podcast where the crew of the podcast was talking about Form Objects (I think it was episode 104).
I’ve bit the bullet and tried both and here are my thoughts on them. I’ll start off with Service Objects: the technique is based on capturing services (or I prefer to call them processes — chains of events logically coupled together) in a plain ruby object. I won’t talk about advantages of using Service Object Pattern and will cut down to the point: the bad thing about it is that it encapsulates only single process. If you want to capture another process you have to create a new Object. In case you have multiple controllers with each controller having few different actions you will end up with huge amount of Service Objects all doing roughly the same thing.
Form Objects to the Rescue
Form Object is very similar to the Service Object; the only difference is the philosophy beneath it. Form Object mimics the HTML form being submitted to the server. It is yet another layer placed between your view and controller taking some responsibilities from both (and from model as well). Here is the list of responsibilities I give to Form Objects in my projects:
- validation of data,
- notifications (both via e-mail and in application),
- audit logging (it gives me bad dreams since there is no clean way to do it via models),
- handling all the CUD (as in CRUD) actions on the object,
- creating nested records (for which you would probably use nested attributes).
As you may have guessed, I mimic almost every model in my project with a Form Object. This way I can keep both my controllers and models free of repetitive logic that simply doesn’t belong there.
Less Words, More Code
There are many ways to implement the Form Object pattern. Here is the way I do it.
First of all lets start with creating the Form Object:
# lib/form_object.rb
class FormObject
include ActiveModel::Model
def initialize(args={})
args.each do |k,v|
instance_variable_set(“@#{k}”, v) unless v.nil?
end
end
end
In the project I am currently working on I’ve few more methods in the object and few concerns included; I’ve even defined CUD (as in CRUD) methods in the main Form Object (since they are reused in every other form).
Now we can move on to creating a Form Object which will inherit from the Form Object:
# app/forms/todo_form.rb
class TodoForm < FormObject
attr_accessor :todo, :comment
validates :todo, presence: true
def self.create_new_todo
if valid?
# Put all logic related to creation of new Todo
# in here — log actions, dispatch e-mails etc
create_todo
end
end
private
def create_todo
# You can even encapsulate the acutual creation of
# the object into it's separate private method; if
# it's needed of course
Todo.new(...)
end
end
Another thing that we need to do before we are finished — to change controller a little bit:
# app/controllers/todo_controller.rb
class TodoController < ApplicationController
def create
TodoForm.create_new_todo(todo_params)
end
private
def todo_params
params.require(:todo).permit(:todo, :comment)
end
end
Now there is last small concern left and that is usage of Form Object in your views; I have created a small helper which renders form for Form Object. With just a little patience and Rails API you will build your own in no time.
Final thoughts
In my current project I’ve ended up using both techniques mentioned earlier — for one-time actions such as user registration or password reset I prefer using Service Objects. For actions that are being repeated through entire model I prefer Form Objects.
I think using either pattern is a great way to clean up and organise your code. After using both of them for a while I came to conclusion that Form Objects are better suited for large projects where Service Objects are ideal for small ones (in terms of processes and object behind the code) or for actions that are rare.
Shameless self-promotion
If you are looking for a place to start learning Ember.js you can try the book I’ve wrote — Ambitious Ember Applications which is a comprehensive Ember.js tutorial. During the course of the book you will build a simple application to help you understand concepts behind Ember.js. After finishing this book you should have enough knowledge to start building complex Ember.js applications. | https://medium.com/@ryakh/rails-form-objects-84b6849c886e | CC-MAIN-2017-34 | refinedweb | 820 | 59.74 |
0
I have this code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace RegexTest { class Program { static void Main(string[] args) { string str = "The quick brown fox."; string pat = "fox"; Regex rgx = new Regex(pat, RegexOptions.IgnoreCase); Match matches = rgx.Match(str); Console.ReadKey(); } } }
It compiles and runs without errors.
I have a breakpoint set at Console.ReadKey(), because I wanted to inspect the variable matches.
But I got the strange error message I put in the title of this thread.
The web wasn't clear about what it meant.
So any help is as always greatly appreciated. | https://www.daniweb.com/programming/software-development/threads/491638/the-name-matches-does-not-exist-in-the-current-context | CC-MAIN-2018-05 | refinedweb | 107 | 55.71 |
As usual while waiting for the next release - don't forget to check the nightly builds in the forum.
The 20 November 2016 build is out. - Windows :
HiQuote from: killerbot on November 20, 2016, 05:45:37 pmThe 20 November 2016 build is out. - Windows : is an error in the link : it should be'
applied Feature/Patch #421: Add dialog for global variables to "Edit Path" dialog
Hi, killerbot, if possible, can you update a new wx dll file? see my suggestion here: Re: The 25 September 2016 build (10912) is out. Thanks.
I?
Quote from: hairuoai on November 22, 2016, 09:32:34 amI?Reproducible? Your own build or a nightly?I don't see any changes in the SVN log that can justify this...
Hi!I build version with wx3.1.0 for Mac OS X 10.11Code::Blocks svn build rev 10922 Nov 22 2016, 16:58:58 - wx3.1.0 (Mac OS X, unicode) - 64 bit
Build information options don't show the compiler version? eg,i use gcc 6.2,and it shows unknow...so will the next nightly builds add few codes can detect the compiler version which is using ?//MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) / //MSVC++ 6.0 _MSC_VER == 1200 //MSVC++ 5.0 _MSC_VER == 1100#ifdef __GNUC__ printf("\nCompiled by gcc-%d.%d.%d\n", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);#elif _MSC_VER // printf("\nCompiled by %d\n", _MSC_VER); if (_MSC_VER == 1900) printf("\nCompiled by VC2015\n"); else if (_MSC_VER == 1800) printf("\nCompiled by VC2013\n"); else if (_MSC_VER == 1700) printf("\nCompiled by VC2012\n"); else if (_MSC_VER == 1600) printf("\nCompiled by VC2010\n"); else if (_MSC_VER == 1500) printf("\nCompiled by VC2008\n"); else if (_MSC_VER == 1400) printf("\nCompiled by VC2005\n"); else if (_MSC_VER == 1310) printf("\nCompiled by VC2003\n"); else if (_MSC_VER == 1200) printf("\nCompiled by VC6.0"); else printf("\nCompiled by Other VC compiler\n");#endif // __GNUC__#ifdef __GLIBC__ printf("Glibc version :%d \n", __GLIBC__);//C Libraries#elif __GLIBCXX__ printf("Glibc version :%d \n", __GLIBCXX__);//C++ Libraries#endif // __GLIBC__ | http://forums.codeblocks.org/index.php/topic,21556.0.html | CC-MAIN-2017-22 | refinedweb | 338 | 74.29 |
Own this business? Learn more about offering online ordering to your diners.
Brooklyns Pizza
with cheese.
by the glass or pitcher.
white or red
import and domestic.
pepperoni, ground beef, canadian bacon, sausage, extra cheese, ham, meatballs, green peppers, black olives, green olives, mushrooms, onions, fresh garlic, fresh tomato, spinach, anchovies and jalapeno peppers.
(square pizza)
chicken, mozzarella cheese, tomato sauce.
meatballs, mozzarella cheese, tomato sauce.
italian sausage, fried peppers and onions.
eggplant, mozzarella cheese, tomato sauce.
steak, onions, provolone cheese.
ham, salami, provolone cheese, lettuce, tomato, onion, salt & pepper, italian dressing.
lettuce, tomato, mushrooms, green peppers, black olives, onions, provolone cheese.
tuna, provolone cheese, lettuce, onion, salt & pepper, italian dressing.
turkey, provolone cheese, lettuce, tomato, onion, salt & pepper, and italian dressing.
ham, provolone cheese, lettuce, tomato, onion, salt & pepper, and italian dressing.
Menu for Brookly. | https://www.allmenus.com/fl/jacksonville/106350-brooklyns-pizza/menu/ | CC-MAIN-2018-39 | refinedweb | 136 | 71.82 |
How to Build and Run Your Docker Image
Stay connected
In this article, I’ll show you how to build and run a Docker image. Docker is a valuable tool for developing and deploying applications. It can seem complicated when you’re first getting started, so I’ll map out the process step-by-step for you. I’ll be using Python code examples, but you can easily adapt this tutorial to your language of choice.
Install Docker
If you want to follow along, you’ll need a system with Docker installed on it. For a Windows or macOS desktop, you can download and install the program from the Docker Desktop website. With Linux, you can install it using the package manager for your distribution. I’ll be using examples from the Linux command line, but they’ll be simple enough that you can adapt them to Windows or Mac.
You’ll also need a text editor for editing your Dockerfile.
Docker "Hello There"
You’ll be running Python inside your Docker containers, but you don’t need Python installed on your development system. That’s your first lesson! You can use Docker to run software that isn’t installed on the host system.
Start with an empty directory and create your first Dockerfile. A Dockerfile contains a list of directives describing how to build your image.
Create a text file named Dockerfile with these contents.
from python:latest
CMD [ "python", "-c", "print('Hi there!')"]
The first line tells Docker which image to start building with. Your Dockerfile will always start with a FROM line. Over at Docker Hub, you can find images with almost any Linux distribution and with almost any software package ready to use. In this case, we’re using the lightweight Alpine Linux distribution with the latest version of Python installed and ready to go.
The second line contains the command that Docker will run by default when this image is loaded. When you use CMD, you pass it an array. The first is the executable, and the rest are the arguments it will pass to Python. You’re running Python with a one-line program. The image puts Python in the search path, so you can call it without worrying about where it’s located.
The -c argument tells Python that the code you want executed follows. Note that “-c print(‘Hi there!’)” wouldn’t work. Each string must be its own item in the array.
Build Your Docker Image
Now, build your image.
$ docker build -t hello_there .
Sending build context to Docker daemon 2.048kB
Step 1/2 : from python:latest
---> a3fe352c5377
Step 2/2 : CMD [ "python", "-c", "print('Hi there!')"]
---> Running in 3977b48d8273
Removing intermediate container 3977b48d8273
---> ebc23857ffda
Successfully built ebc23857ffda
Successfully tagged hello_there:latest
$
Docker build is the command for building an image. It expects to find a file named Dockerfile in the working directory. The second argument, -t, is a tag to use to refer to the image.
As you can see, Docker prints out each directive in your Dockerfile. Once it’s done, the image is placed in your local Docker repository.
Run Your Docker Image
Let’s run it.
$ docker run hello_there
Hi there!
Docker run creates a container using your image. Pass it the name you used in the build step. There it is. Your first Docker image, running in a container!
A More Practical Image
Passing your Python code to Python on the command line isn’t how you would normally structure an application, so it isn’t how you want to build an image either. Let’s make this a bit more practical.
First, put the print statement in a Python source file name hello_there.py.
#!/usr/bin/env python3
print('hello there!')
Now, update the Dockerfile so it can use this source file.
from python:latest
COPY hello_there.py /
CMD [ "python", "hello_there.py"]
The COPY directive tells Docker to copy the source file into the root of your image.
Docker doesn’t accept relative paths that point outside of the build folder. In other words, ../path/to/stuff won’t work. So if you’re going to check your code into source control and run it on a different system, it’s easiest to work with the folder that contains your Dockerfile and build from there.
COPY Customizes Images
You can COPY anything into an image. It will copy in any file, so instead of Python source, you could add jar files, compiled code, or webpages into your image. You could copy a directory full of HTML files into the NGINX image and build yourself a web server.
Here’s an example from the NGINX documentation.
FROM nginx
COPY static-html-directory /usr/share/nginx/html
COPY will copy the contents of a directory if you pass a directory name. It doesn’t copy the name, though, so the contents of static-html-directory are placed in /usr/share/nginx/html. This image will run as a web server even without adding a new CMD because it will inherit the one specified in FROM image.
A Better "Hello There"
Let’s get back to our image.
$ docker build -t hello_there .
Sending build context to Docker daemon 3.072kB
Step 1/3 : from python:latest
---> a3fe352c5377
Step 2/3 : COPY hello_there.py /
---> Using cache
---> 1863d3f0c4eb
Step 3/3 : CMD [ "python", "hello_there.py"]
---> Using cache
---> a125be33ddea
Successfully built a125be33ddea
Successfully tagged hello_there:latest
It built successfully.
Next, rerun it.
$ docker run hello_there
hello there
It still works!
So, you’ve built an image that takes a Python source file and executes it. If you want to update the code, you update hello_there.py and rebuild the image. Your Docker image is your application packaging.
More Docker Image Changes
Let’s take this Docker application one step further.
We’ll add the Python requests library, retrieve a webpage, and print the request status.
#!/usr/bin/env python3
import requests
x = requests.get('')
if x.status_code == 200:
print('yay!')
else:
print('uh-oh!')
Now, rebuild the image.
$ docker build -t hello_there .
[sudo] password for egoebelbecker:
Sending build context to Docker daemon 3.072kB
Step 1/3 : from python:latest
---> a3fe352c5377
Step 2/3 : COPY hello_there.py /
---> 25d512ac21e5
Step 3/3 : CMD [ "python", "hello_there.py"]
---> Running in c9a386222569
Removing intermediate container c9a386222569
---> c475fe142992
Successfully built c475fe142992
Successfully tagged hello_there:latest
Finally, rerun it.
$ docker run hello_there
Traceback (most recent call last):
File "//hello_there.py", line 3, in
import requests
ModuleNotFoundError: No module named 'requests'
The script won’t run because we haven’t loaded the requests module into the Python environment. So, we need to modify the Dockerfile again.
from python:latest
RUN pip install requests
COPY hello_there.py /
CMD [ "python", "hello_there.py"]
If you’re not familiar with pip, it’s the packaging tool for Python. We’re using it to retrieve the latest version of the requests library to call it from inside our script.
The RUN directive in a Dockerfile runs an external program as part of the image build process. It is not related to the Docker run command you’re using to run your container.
So, you’re telling Docker to run pip inside the python:latest container. Rerun the build with this new addition to the Dockerfile.
$ docker build -t hello_there .
Sending build context to Docker daemon 3.072kB
Step 1/4 : from python:latest
---> a3fe352c5377
Step 2/4 : RUN pip install requests
---> Running in 0d6f466d3cb0
Collecting requests
Downloading requests-2.25.0-py2.py3-none-any.whl (61 kB)
Collecting certifi>=2017.4.17
Downloading certifi-2020.11.8-py2.py3-none-any.whl (155 kB)
Collecting chardet<4,>=3.0.2
Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB)
Collecting idna<3,>=2.5
Downloading idna-2.10-py2.py3-none-any.whl (58 kB)
Collecting urllib3<1.27,>=1.21.1
Downloading urllib3-1.26.2-py2.py3-none-any.whl (136 kB)
Installing collected packages: certifi, chardet, idna, urllib3, requests
Successfully installed certifi-2020.11.8 chardet-3.0.4 idna-2.10 requests-2.25.0 urllib3-1.26.2
Removing intermediate container 0d6f466d3cb0
---> 0a5dd2d6afc4
Step 3/4 : COPY hello_there.py /
---> 6f743c7f6182
Step 4/4 : CMD [ "python", "hello_there.py"]
---> Running in 2d559f8a4b61
Removing intermediate container 2d559f8a4b61
---> f8203cf2687a
Successfully built f8203cf2687a
Successfully tagged hello_there:latest
Take a look at step 2 of 4 in the build output. You can see the output from pip as it collects requests and its four dependencies.
RUN works for installing Debian packages with apt or installing RPMs with rpm or yum. You also run any other command, such as setting file permission with chmod to changing file ownership.
Try rerunning the container.
$ docker run hello_there
yay!
You can see that retrieving the Google search page succeeded.
Docker Images for Easier Application Deployment
In this tutorial, you built a simple Docker image. Then you made the script easier to maintain by adding a source file to the image. Finally, you customized the image by installing additional software packages for your script.
Docker is a powerful tool for bundling applications with their dependencies and running them on multiple platforms with no additional changes. Now that you know how to build images, start using it for your projects!
Stay up to date
We'll never share your email address and you can opt out at any time, we promise. | https://www.cloudbees.com/blog/docker-image | CC-MAIN-2022-05 | refinedweb | 1,566 | 68.47 |
Finally I made it to free up some time and create a released version of the WCF Activities I have been working on for some time now. This version is fully tested and already used in multiple projects I am working on including the very demanding ones that run thousands of workflows a day!
First of all I want to thank Martijn Beenes who has been so kind to create a Setup project for me in WIX, so I can hand you a nice installer in stead of a build it yourself version. The setup will also install the sources on your machine so you can make changes if you like J
So what is in the release? Well bottom line a set of Workflow activities you can use to implement service operations using Windows Communication Foundation (WCF). The project provides a WCFInput activity where you can choose an interface and a method you want to implement in a workflow as a WCF service. You can specify certain properties on the method like IsOneWay, AsyncPattern, Action, ProtectionLevel. The input activity will reflect on the method you select from the interface and then will generate dynamic parameters that reflect the method signature. All these parameters can be bound to the workflow so you can work there to provide an implementation of the service operation. To communicate data back to the calling client there is a WCFOutput activity. If you drag that activity to the workflow design, you have the option to select a corresponding input activity it will correlate to to send output. There you can also bind to the return value of the WCF operation. This is where you communicate the result back.
The implementation detects the type of scheduler set for the workflow and if it is the manual workflow scheduler it will asynchronously return after the WCFOutput is done. It will queue the workflow for further execution with a thread pool, so the workflow continues execution after the call is done. This provides a great mechanism to trigger multi step workflows, utilizing the power of the request thread for the handling of the WCF call and the workflow in between the Input and output activity and continuing execution after the call is done. There you can do any background processing until the workflow becomes idle again.
The WCFInput activity also adds two additional properties to the containing root workflow to set the Service namespace and the Service name. It will generate the implementation of the service calls you model in the workflow as a new class that contains the WCF attributes to expose it as a service. The class generated that implements the contract for a workflow has the naming pattern <workflowtypeName>_wcfimpl. This name you use when configuring the service for hosting in a host you like. At codeplex I provided a step-by-step guide how you can use the activities and how you can configure e.g. a web application to host your service using a .svc file.
Last thing to note is that the activities support the correlation of a subsequent call on the workflow by sending a message header when making the subsequent call. You can also find a tutorial on codeplex as to help you get started with these activities. The guide and tutorial will give you all information needed to use the activities in your project.
I hope you will enjoy them, and please if you feel something is not working correctly or you would like to see additional features add them to the issue tracker on codeplex and I will see if I can add them or fix them a.s.a.p.
Enjoy,
Marcel
CTO at Xpirit, Microsoft Regional Director, Visual studio ALM MVP, Speaker, Pluralsight Author and IT Architect Consultant | http://fluentbytes.com/wcf-activities-version-1-0-now-released-at-codeplex/ | CC-MAIN-2019-30 | refinedweb | 632 | 57.3 |
We want to convert to String
returns:
A string that represents the float f
float fvar = 1.17f; String str = String.valueOf(fvar);
2) Method 2: Using Float.toString(float f): This method works similar to the String.valueOf(float) method except that it belongs to the Float class. This method takes float value and converts it into the string representation of it. For e.g. If we pass the float value 1.07f to this method, it would be returning string “1.07” as an output.
Method declaration:
public static String toString(float f)
parameters:
f – float value
returns:
String representing f.
float fvar2 = -2.22f; String str2 = Float.toString(fvar2);
Example: Converting float to String
In this program we have two float variables, we are converting them to strings using different-2 methods. We are converting first float variable to string using valueOf(float) method while we are using toString(float) method to convert the second float variable. This example demonstrates the use of both the above mentioned methods.
package com.beginnersbook.string; public class FloatToString { public static void main(String[] args) { /* Method 1: using valueOf() method * of String class. */ float fvar = 1.17f; String str = String.valueOf(fvar); System.out.println("String is: "+str); /* Method 2: using toString() method * of Float class */ float fvar2 = -2.22f; String str2 = Float.toString(fvar2); System.out.println("String2 is: "+str2); } }
Output:
String is: 1.17 String2 is: -2.22 | http://beginnersbook.com/2015/05/java-float-to-string/ | CC-MAIN-2017-09 | refinedweb | 239 | 70.5 |
Introduction: ( Wrist-watch Enabled) Home Automation Via Twitter
This is an Instructable to make a Twitter controlled Home Automation system for your house in less than 7$ (Rs.450). This tutorial includes setting up Python, Arduino as well as Twitter to build your very own Twitter controlled personal assistant.
The main reason I built this is to turn on the AC and mosquito coils in my room before I get home, so that when i come home, the room is already cooled and free from mosquitoes. But this implementation works for about anything.
Reason for the use of Twitter is because of an already existing twitter Android Wear app. This helps me to tweet by speaking into my watch. That basically means, I control my house talking to my watch!
Usually a home automation system of this sort would cost hundreds of dollars and still be not as good. In this project you will be able to control the appliances in your house right from your watch(if you have an android wear watch like I do).
Be sure to check out the video for an insight.
What goes in?
1) A micro-controller (arduino or arduino clone will do)
2) A laptop (Windows preferably)
3) A relay Shield (optional)
4) Android Wear Watch* (optional)
Step 1: Python Installation
Firstly you will have to download the TwitterHouse.zip file.
NOTE: The zip contains files ONLY FOR WINDOWS and no other operating system. Sorry. Based on your operating system you will have to download the equivalent individual files independently.
Check if you have python already installed on your computer by following the command prompt instruction below. If not continue this step.
Once you have downloaded and extracted the zip file, install python-2.7.9.msi
Open Command Prompt from search and type in "python" and click on enter. You should see that.
Step 2: Twitter Application
This and the next step are important steps where you link twitter to python.
To do so, you'll have to first create a Twitter account(if you don't have one).
Once you're done with that, head over to and hit on "Create New App". Type in a name(any name will do), description(doesn't have to be detailed) and website(any will do) and Create your Twitter application.
Now you go to Application setting and under Access level click on modify app permissions and change that to Read and Write, Update settings. Then click on the Keys and Access tokens tab and note down your Consumer Key and Secret. and scroll down to "Create my access token". Note down your Access token and access token secret as well.
Now you're all set with Twitter's Application Program Interface.
Step 3: Python Twitter Integration
Go back to the folder you had unzipped the downloaded file. And unzip the file tweepy-master.zip
Once you're done with that, open CMD(command prompt) again and navigate to the location of tweepy.
To enter a file, type "cd" and then the file name. and to go to root directory type "cd \".
Once you are in the folder tweepy-master where the file setup.py is located, type in "python setup.py install ". Once its done installing. Close cmd and reopen it. Type
python
once python is opened, type in
import tweepy
If you get ">>>" then you have successfully installed tweepy on your computer. Congratulations.
I suggest you install pyserial-2.7.win32.exe now as well. This you can just install like any other normal executable installation.
Step 4: Arduino Software Setup
In the same downloaded and unzipped folder(TwitterHome), run the installation of arduino. (arduino-1.6.0-windows (1).exe).
Once you're done installing the Arduino IDE, connect your Arduino using the USB serial cable and start the IDE. Select the board you are using and port it is connected on.
NOTE: I am using an Arduino clone and hence my drivers had to be installed separately. If you are also using a clone, download and install the respective drivers too in case it doesn't detect.
Take a note of this port as well.
Now open the file TwitterHome\python-tweet\python-tweet.ino in the IDE. Compile and upload the code to your Arduino.
Now you are done with the coding part of the Arduino.
You may reward yourself with a cookie.
Step 5: Python Coding
This is the part where you may go wrong the most number of times. But don't worry. I did too, because I had to write that code you will use.
Back to the TwitterHome folder, there are 2 files, homeautomationon.py and homeautomationoff.py
This tutorial will show you what to do in one of them and you will have to repeat the same steps for the other file.
So first right click on the file homautomationon.py and click on "edit with IDLE".
Once the editor opens, first thing you'll notice are the comments throughout the code. These comments(## change or ## change optional) are the lines of code you will have to edit based on your preferences and your configuration. The changes are pretty straight forward but in case you have any problems, feel free to comment below.
All the things I asked you to Note down earlier will come in handy now.
Step 6: Hardware
This is the step where you can tailor the hardware to suit your needs.
This step becomes very simple if you have an arduino Relay shield, if not you can make one like I did and use it. The trigger of the relay shield is to be connected to the pin programmed in the arduino program you uploaded to your microcontroller.
Attach the appliance to your relay shield like you would do if you were to put a switch in its circuit. The arduino doesnt drive the appliance but simply acts as an ON/OFF switch. After you're done wiring up the shield and the arduino connect it back to your computer.
Step 7: Watch Integration
Step 8: Magic
Go to the python IDLE editor window that the program you have edited is in, and click on F5. You should see a new window pop up and it will display the contents of any tweet containing the keywords you have specified. When that keyword is detected, python will send a message via serial to your arduino to turn ON/OFF the appliance.
And now you can brag about your personal assistant on twitter. *drumroll* You can try it out by either tweeting on your watch (or any other device). When you tweet with the keyword, your PA will also tweet back to you based on the process undertaken.
Ta-daaaaaa. *bow*
Recommendations
We have a be nice policy.
Please be positive and constructive.
18 Comments
Hello, is it possible, that i use only mobile to tweet rather than using wrist watch? thank you!
Hello there! your project is super damn cool and i'm using it as reference to my final year project! I'm a beginner to arduino! Is it necessary to use the wrist-watch? How to make it works by just tweeting from the phone?
Nice going bro! Will try it some day!
what to attach on the realy shield
Assume that the relay is a mechanical switch and connect it like you would for it. Or disconnect the wall switch for it and connect the two wires you removed to the relay. Be careful with the current that your AC draws and the amount your relay can withstand.
I survived all the way till the last step then this props up when i run it!
Traceback (most recent call last):
File "C:\Users\Gagan Bhat\Downloads\TwitterHome\homeautomationon.py", line 22, in <module>
ser = serial.Serial(usbport, 9600, timeout=1) ##change optional 'COM3': WindowsError(5, 'Access is denied.')
>>>
Did you connect your arduino right? Go over to the arduino IDE and check the port its connected on. Change COM3 in the source code to the right port. If that doesnt fix it then write a small program and check if serial connection with your arduino works alright in the arduino IDE.
Hi
Whenever I type Python or Python setup.py install then it says that python is not recognized as an internal or external command
From your next comment I'm guessing you figured a workaround for this...
of the ac | http://www.instructables.com/id/Twitter-Home-Control-at-7/ | CC-MAIN-2018-17 | refinedweb | 1,414 | 74.59 |
Let’s say you have a Silverlight application that you want to be scaled to the same width and height of your browser window. This way the application takes up the entire window and not just a fixed sized within the window. To illustrate this I have created a sample application that has a number of random UI elements on it.
You can preview and run this application here:
Also, the following screen shots show this sample application scaled to different sizes in the browser (tall, normal, wide). As you can see, each UI element in the application is scaled proportionally to the browser size.
In order to accomplish this, all you have to do is add a RenderTransform of the type ScaleTransform to your Grid or Canvas of your Silverlight control.
For example, add the following code to your Page.xaml file:
<Canvas>
<Canvas.RenderTransform>
<ScaleTransform x:Name="CanvasScale" ScaleX=”1” ScaleY=”1”></ScaleTransform>
</Canvas.RenderTransform>
</Canvas>
Setting ScaleX and ScaleY to “1” is equivelent to a 100% scale. If you set the ScaleX and ScaleY to “0.33” the control would render at 1/3 its original.
Now, as demonstrated in Tip of the Day #9 monitor for your browser resize in your Page.xaml.cs file. Set the CanvasScale ScaleX and ScaleY to be a new percentage of the original width and height:
namespace ScaleTransform
{
public partial class Page : UserControl
{
private int _startingWidth = 800;
private int _startingHeight = 600;
public Page()
{
InitializeComponent();
App.Current.Host.Content.Resized += new EventHandler(Content_Resized);
}
void Content_Resized(object sender, EventArgs e)
double height = App.Current.Host.Content.ActualHeight;
double width = App.Current.Host.Content.ActualWidth;
CanvasScale.ScaleX = width / _startingWidth;
CanvasScale.ScaleY = height / _startingHeight;
}
}
Thank you,
--Mike Snow
Subscribe in a reader
Let’s say you have a Silverlight application that you want to be scaled to the same width and height
What about scrollbars? How do you handle them? Will they appear on resize?
Thanks
Pingback from Silverlight news for August 27, 2008
This example works well with a fairly large range of browser window sizes. I found that it fails to fill the client area of the browser by sizing an IE7 window to 770x811. I got the same result with FireFox 3 by with a slightly taller window, matching up the HTML display spaces. In both cases the bottom edge of the "Don't Click Me" button is cut off and white space fills in above the status bar. At 1143x230, the right side is cut off.
Pingback from Dew Drop - August 27, 2008 | Alvin Ashcraft's Morning Dew
Hey Billvo, I am seeing the same thing and will file a bug for it. Thanks!
Esh- Scrollbars should also scale, everything should.
In any real implementation, you would probably want to maintain the proper aspect ratio.
True, this is probably a corner case.
Michael Washington with Desktop Instances in SilverlightDesktop, and Mike Snow scaling his entire app
Pingback from Silverlight 2.0 RTM? Silverlight vNext « Tales from a Trading Desk
Silverlight Tip of the Day #39 Title : How to Create a Zoom Toolbar Demo: silverlight.services.live.com/.../iframe.html
The purpose of this post is to create an outline summary all the blogs from my Silverlight Tips of the
Pingback from Bookmarks about Tip | http://silverlight.net/blogs/msnow/archive/2008/08/26/silverlight-tip-of-the-day-33-how-to-scale-your-entire-app-and-its-elements-to-your-browsers-size.aspx | crawl-002 | refinedweb | 544 | 63.9 |
Subject: [boost] [next_generation][modularization] Is the community interested in creating a smooth path to a modularized Boost
From: Vicente J. Botet Escriba (vicente.botet_at_[hidden])
Date: 2014-05-31 10:18:32
Hi,
I've started a new thread in response to Julian Gonggrijp post
[modularization] proposal and poll, as I would not answer directly to
his questions.
I'm sure that almost all of us want a modularized Boost. What does this
means? It is up to us to define it:
* what the user can request as a delivered package for its own needs?
* what the authors must state explicitly?
* what must be tested/checked?
The main problem is how to achieve it ensuring backward compatibility .
I'm persuaded that we need a new Boost repository (or whatever we want
to name it) that would include libraries that respect the modularization
constraints we could define.
My question is who would be interested in starting the next generation
of a modularized Boost that starts from a repository of ZERO modularized
libraries. The idea is to add to the current Boost libraries new ones
that respect the modular rules and adapt the current ones to be defined
on top of the modularized ones.
At the end we could deprecate the old ones.
In order to do that we need of course to add new interfaces (a new
namespace mod_boost or whatever is preferred) and so the user would need
to move to these interfaces smoothly.
Before starting we need to
* Define the constraints of a modularized system
- no cyclic dependencies, ....
* Define the tools that can be used to support the modular system
- which build system(s),
- which test system(s),
- which regression system(s),
- which doc system(s), ...
* Define the rules
- who could be able allowed to do the refactoring?
- Should the refactoring be reviewed to ensure a improvement on the
quality of Boost?
- who maintains what?, ...
* Setup the infrastructure ( build system, test system, regression
system, doc system, ... )
Only then we could
* Start from libraries that don't depend on any other library (with
possible refactoring) and adaptation of the refactored libraries from
which these modular libraries have been extracted.
* Deliver them
* Build a second layer of libraries that depend only on first layer
* Deliver them
* ...
Of course, in order to check that the rules and tools are the
appropriated ones we will need to experiment with some examples.
I recognize that this would mean a lot of work, however I hope that the
final result would satisfy better the community expectations and the
quality of Boost libraries.
Best,
Vicente
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk | https://lists.boost.org/Archives/boost/2014/05/213776.php | CC-MAIN-2019-35 | refinedweb | 451 | 55.95 |
Introduction
What is the need of WPF when we had GDI, GDI+ and DirectX?How does hardware acceleration work with WPF?Does that mean WPF has replaced DirectX?So can we define WPF in a precise way?What is XAML?So is XAML meant only for WPF ?Can you explain the overall architecture of WPF?Which are the different namespaces and classes?What is SilverLight ?Come on, even WPF runs under browser why SilverLight ?Can SilverLight run in other platforms other than window?What is the relationship between Silver Light, WPF and XAML?Can you explain Sliver Light architecture?Source code
This article talks about 21 important FAQ from the perspective of WPF and Silver light. lot more feel free to download it and enjoy
First let's
X.
No,XAML is not meant only for WPF.XAML is a XML-based language and it had various variants.WPF XAML is used to describe WPF content, such as WPF objects, controls and documents. In WPF XAML we also have XPS XAML which defines an XML representation of electronic documents.Silverlight XAML is a subset of WPF XAML meant for Silverlight applications. Silverlight is a cross-platform browser plug-in which helps us to create rich web content with 2-dimensional graphics, animation, and audio and video. WWF XAML helps us to describe Windows Workflow Foundation content. WWF engine then uses this XAML and invokes workflow accordingly.
Above figure shows the overall architecture of WPF. It has three major sections presentation core, presentation framework and milcore. In the same diagram we have shown how other section like direct and operating system interact with the system. So let's go section by section to understand how every section works.User32:- It decides which goes where on the screen.DirectX: - As said previously WPF uses directX internally. DirectX talks with drivers and renders the content.Milcore: - Mil stands for media integration library. This section isUIElement handled three important aspects layout, input and events.System.Windows.FrameworkElementFrameWorkElement uses the foundation set by UIElement. It adds key properties like HorizontalAlignment , VerticalAlignment , margins etc.System.Windows.Shapes.ShapeThis class helps us to create basic shapes such as Rectangle, Polygon, Ellipse, Line, and Path.System.Windows.Controls.ControlThis class has controls like TextBox,Button,ListBox etc. It adds some extra properties like font,foreground and background colors.System.Windows.Controls.ContentControlIt holds a single piece of content. This can start from a simple label and go down to a unit level of string in a layout panel using shapes.System.Windows.Controls.ItemsControlThis is the base class for all controls that show a collection of items, such as the ListBox and TreeView. System.Windows.Controls.PanelThis.
In order to understand the different elements of WPF, we will do a small 'hello world' sample and in that process we will understand the different elements of WPF.
Note :- For this sample we have VS 2008 express edition. for the same.
These dependency properties belong to one class but can be used in another. Consider the below code snippet:-
Height and Width are regular properties of the Rectangle. But Canvas. Top and Canvas. Left is dependency property as it belongs the canvas class. It is used by the Rectangle to specify its position within Canvas.
XAML files are usually compiled rather than parsing on runtime. But it also supports parsing during runtime. When we build a XAML based project, you will see it creates g.cs extension in obi\Debug folder. Therefore, for every XAMl file you will find a g.cs file. For instance, a Shiv.XAML will have Shiv.g.cs file in obi\Debug folder. In short, in runtime you actually do not see the XAML file. But if you want to do runtime, parsing.
Figure 16.
Note: - You can get a simple sample in WindowsSimpleXAML folder. Feel free to experiment with the code. experimenting will teach you much more than reading something theoretical.
To access XAML objects in behind code you just need to define them with the same name as given in the XAML document. For instance in the below code snippet we named the object as objtext and the object is defined with the same name in the behind code.
Figure 16.2 Accessing XAML object
Note: - You can get the source code in WindowsAccessXAML folder.
Silver light is a web browser plug-in by which we can enable animations, graphics and audio video. You can compare silver light with flash. We can view animations with flash and it's installed as a plug-in in the browser.
Yes, animations made in SilverLight can run in other platforms other than window. In whatever platform you want run you just need the SilverLight plug-in.
Yes there is something called as WPF browser application which can run WPF in browser. For WPF browser application you need .Net framework to be installed in the client location while for silver light you need only the plug-in. So in other words WPF browser applications are OS dependent while SilverLight is not. SilverLight plug-in can run in other OS other than windows while we all know .NET framework only runs in windows..
Before.. Presentation core: - The core presentation framework has functionalities to display vector 2d animations, images, media, DRM and handle inputs like mouse and keyboard.. Other technologies: - Silver light interacts with other technologies like Ajax and javascript. So it also borrows some functionalities from there technologies...
What are the various basic steps to make a simple Silver Light application?This sample we are making using VS 2008 web express edition and .NET 3.5. It's a 6 step procedure to run our first silver light application. So let's go through it step by step.Step1:- The first thing we need to do is install silverlight SDK kit from Step 2:- Once you install the silver light SDK you should be able to use the silver light template. So when you go to create a new project you will see a 'SilverLight application' template as shown in the below figure.
Step 3 :- Once you click ok you will see a dialog box as shown below which has three options.
Add a ASP.NET web project to the solution to host silver light: - This option is the default option, and it will create a new Web application project that is configured to host and run your Silverlight application. If you are creating a new silver light application then this is the option to go.Automatically generate Test Page To Host Silverlight at build time: - This option will create a new page at run time every time you try to debug and test your application. If you want to only concentrate on your silver light application then this option is worth looking at.Link This Silverlight Control Into An Existing Web Site :- If you have a existing silver light application then this option helps to link the silver light application with the existing web application project. You will not see this option enabled to new projects , you need to have an existing web application.For this example we have selected the first option. Once you click ok you should see the full IDE environment for silver light.
So let's run through some basic points regarding the IDE view what we see. You will see there are two projects one is your web application and the other is the silver light application. In the silver light application we two XAML files one is App.XAML and the other is Page.XAML. App.XAML has the global level information.Step 4:- Now for simplicity sake we just use the TextBlock tag to display a text. You can see as we type in the Page.XAML its displayed in the viewer.
Step 5 :- Now we need to consume the silver light application in a ASPX page. So in the HTML / ASPX page we need to first refer the silver light name space using the 'Register' attribute.
<%@Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %>
We also need to refer the script manager from the silver light name space. The script manager control is functionality from AJAX. The main purpose of this control is to manage the download and referencing of JavaScript libraries.
Finally we need to refer the silver light application. You can see that in the source we have referred to the XAP file. XAP file is nothing but a compiled silver light application which is compressed and ZIP. It basically has all the files that's needed for the application in a compressed format. If you rename the file to ZIP extension you can open the same using WINZIP.
So your final ASPX / HTML code consuming the silver light application looks something as shown below.
<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"
TagPrefix="asp" %>
MyFirstSilverLightApplication
Step 6 :- So finally set the web application as start up and also set this page as start up and run it. You should be pleased to see your first silver light application running.
You can download the source code from the bottom of this article.
.
Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend | http://www.dotnetspark.com/kb/536-21-important-faq-questions-for-wpf-and-silverlight.aspx | CC-MAIN-2017-04 | refinedweb | 1,551 | 67.45 |
Inline:; }
The making this transition.
.
Some compilers actually compile both C and C++ with the same compiler. Microsoft's
cl.exe is one such compiler -- you pass it the <-TP> flag to convince it that you want C++ mode.. or classes within the C++ code.
For more information about the grammar used to parse C++ code, see the section called "Grammar".
The following example shows how C++ snippets map into the Perl namespace:
Example 1:
use Inline CPP => <<'END'; using namespace std;).
Ok, so that takes care of where code can reside within a given file. unfortunate issue is that the C++ class, "
Foo" will be mapped to Perl below the
Some::Foo namespace, as
Some::Foo::Foo, and would need to be instantiated like this:
my $foo = Some::Foo::Foo-new()>. This probably isn't what the user intended. Here's a devious hack (provided by BrowserUk) that eliminates the problem:
package Some::Foo; package Some; # Now we're using the "Some" namespace, and Inline::CPP # will create the Foo class as Some::Foo. use Inline CPP => <<'END_CPP'; // No changes to the C++ code from the previous example. END_CPP package Some::Foo; return 1 if caller; CPP => Config => AUTO_INCLUDE => '#include "something.h"';
Specifies code to be run when your code is loaded. May not contain any blank lines. See perlxs for more information.
use Inline Config => BOOT => 'foo();';
Specifies which compiler to use.
use Inline CPP => Config => CC => '/usr/bin/g++-4.6';
Specifies extra compiler flags. Corresponds to the MakeMaker option.
use Inline CPP => Config => CCFLAGS => '-std=gnu++0x'; to facilitate function overloading. the standard iostream header at the top of your code. Inline::CPP will try to make the proper selection between
iostream.h (for older compilers) and
iostream (for newer "Standard compliant" compilers).
This option assures that it include
iostream, which is the ANSI-compliant version of the header. For most compilers the use of this configuration option should no longer be necessary. It is still included to maintain backward compatibility with code that used to need it..
As mentioned earlier,; }
Obviously.
Here are some examples.
This example illustrates how to use a simple class (
Farmer) from Perl. One of the new features in Inline::CPP is binding to classes with inline method definitions:
use Inline CPP; my $farmer = new Farmer("Ingy", 42); my $slavedriver = 1; while($farmer->how_tired < 420) { $farmer->do_chores($slavedriver); $slavedriver <<= 1; } print "Wow! The farmer worked ", $farmer->how_long, " hours!\n"; __END__ __C.
The
Airplane is a fully-bound class which can be created and manipulated from Perl.
use Inline CPP; my $plane = new Airplane; $plane->print; if ($plane->isa("Object")) { print "Plane is an Object!\n"; } unless ($plane->can("fly")) { print "This plane sucks!\n"; } __END__ __CPP__ using namespace std; /*; } __END__ __CPP__ double avg(...) { Inline_Stack_Vars; double avg = 0.0; for (int i=0; i<items; i++) { avg *= i; avg += SvNV(ST(i)); avg /= i + 1; } return avg; }
Comparing the relative speed of the Perl versus the C++ solution, the C++ solution benchmarks about 10x faster.,
use Inline CPP;"; } __END__ _.6.0 or later. Since Inline::CPP depends on Inline, Perl 5.6.0 is also required for Inline::CPP. It's hard to imagine anyone still using a Perl older than 5.6.0.6.0 Perl.
Occasionally I'm asked if Inline::CPP is ready for the C++11 standard. The short answer may noticed quickly. This is Perl, C++, and XS all sealed into one can of worms. But it can be fun, which is a description never applied githug repo is:
Ingy döt Net <INGY@cpan.org> is the author of
Inline,
Inline::C and
Inline::CPR. He is known in the innermost Inline circles as "Batman". ;)
Copyright (c) 2000 - 2003 Neil Watkiss. Copyright (c) 2011 - 2012 David Oswald.
All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as Perl itself.
See | http://search.cpan.org/~davido/Inline-CPP-0.46/lib/Inline/CPP.pod | CC-MAIN-2013-48 | refinedweb | 655 | 68.87 |
in reply to
Re: Favourite modules April 2003
in thread Favourite modules April 2003
Quantum::Superpositions - Takes a whole class of simple operations that were too complex in Perl and makes them simple again (comparing lists, set operations, etc) - that was a suprise for me. The name does not idicate that it's such a general purpose module.
Think perl 6's junctions.
As dense as I must be, from having read about it earlier, I guess I didn't understand the viewpoint or jargon or whatever from various write-ups, including it's own docs.
I never thought I was stupid... but maybe I should rethink
In fact, I inaugurated the Acme:: namespace (with Acme::Bleach) specifically so that people could tell when I was kidding and when I was serious.
;-)
A foolish day
Just another day
Internet cleaning day
The real first day of Spring
The real first day of Autumn
Wait a second, ... is this poll a joke?
Results (433 votes),
past polls | http://www.perlmonks.org/?node_id=250573 | CC-MAIN-2014-15 | refinedweb | 166 | 70.43 |
def simple_app(environ, start_response):(see Titus's intro on WSGI for more details on what it takes for a Web server and a Web app to talk WSGI)
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!\n']
How do you test this application though? One possibility is to hook it up to a WSGI-compliant server such as Apache + mod_scgi, then connect to the server on a port number and use a Web app testing tool such as twill to make sure the application serves up the canonical 'Hello world!' text.
But there's a much easier way to do it, with twill's wsgi_intercept hook. Titus wrote a nice howto about it, so I won't go into the gory details, except to show you all the code you need to test it (code provided courtesy of twill's author):
twill.add_wsgi_intercept('localhost', 8001, lambda: simple_app)That's it! Running the code above hooks up twill's wsgi_intercept into your simple_app, then drops you into a twill shell where you can execute commands such as:
twill.shell.main()
>>> go("")
==> at
>>> show()
Hello world!
What happened is that wsgi_intercept mocked the HTTP interface by inserting hooks into httplib. So twill acts just as if it were going to an http URL, when in fact it's communicating with the application within the same process. This opens up all kinds of interesting avenues for testing:
- easy test setup for unit/functional tests of Web application code (no HTTP setup necessary)
- easy integration with code coverage and profiling tools, since both twill and your Web application are running in the same process
- easy integration with PDB, the Python debugger -- which was the subject of Titus's lightning talk at PyCon06, where he showed how an exception in your Web app code is caught by twill, which then drops you into a pdb session that lets you examine your Web app code
def simple_app(environ, start_response):(note that BLANKLINE needs to be surrounded with angle brackets, but the Blogger editor removes them...)
"""
>>> import twill
>>> twill.add_wsgi_intercept('localhost', 8001, lambda: simple_app)
>>> from twill.commands import *
>>> go("")
==> at
\'\'
>>> show()
Hello world!
BLANKLINE
\'Hello world!\\n\'
"""
status = '200 OK'
response_headers = [('Content-type','text/plain')]
start_response(status, response_headers)
return ['Hello world!\n']
if __name__ == '__main__':
import doctest
doctest.testmod()
If you run this through python, you get a passing test. Some tricks I had to use:
- indicating that the expected output contains a blank line -- I had to use the BLANKLINE directive, only available in Python 2.4
- escaping single quotes and \n in the expected output -- otherwise doctest was choking on them | http://agiletesting.blogspot.com/2006/04/in-process-web-app-testing-with-twill.html | CC-MAIN-2018-05 | refinedweb | 442 | 59.33 |
I working on part of a code for a much larger project. I understand how to write a program for a password in the simplest form, but I want to have it let the user guess the password up to 5 times and then not let them run a command.
For example if the user guess the password right then he can type debug and get the source code, but if he guess it wrong 5 times the app won't accept the command debug.
This code is in a rough state. What I'm having trouble is having it write out to the file. I know how to write out to a file, but this is driving me nuts. How the code is, it will keep on prompting for the password until 5 wrong guess or the correct password. So I wanted to have a way for the user can get out of that and do something else. So I coded an exit command, but it isn't working right for me. When they type exit I wanted to write the number of wrong guess so far to a file and then when they try again it will check the file and use that current number of guess for the count.
Any help or suggestion would be greatly appreciate.
Sincerely your;
jdm
P.S. If it isn't clear what I'm trying to do just ask.
Code:
#include <iostream> #include <fstream> using namespace std; void debug(); int main() { //open a file to read and write //declare file variables and name of file ifstream inData; ofstream outData; inData.open("guess.txt"); outData.open("guess.txt"); string password;//store password input int number = 0;//store number of guess int num = 0;//store number of guess from file inData >> num;//get number //making sure number of guess isn't 5 if (num == 5) { cerr << "Access Denied" << endl; system("pause"); exit (100); } //A while loop that will prompt for the password as long as the number of guess isn't 5 and the right password isn't entered in while (number !=5 && password != "access") { cout << "Enter password: "; cin >> password; //trying to let the user exit the prompt, but keep track of the number of guesses, but it isn't writing out to the file right. I don't know why if (password == "exit") { outData << number; system("pause");//through in thinking that the app was closing to early to write to the file. exit(100); } //launch the debug, but later it will allow the user the option of entering that command in. else if (password == "access") { debug(); } //increase number of guesses by 1 when wrong password is entered in else { number++; } outData << number << endl cerr << number << endl; } //close files inData.close(); outData.close(); system("pause"); return 0; } //just a test dummy void debug() { cerr << "Debug" << endl; cout << "Code Here" << endl; }
Thanks for the help.
jdm | https://www.daniweb.com/programming/software-development/threads/194539/password-guessing-accessing-command-writing-to-a-file | CC-MAIN-2021-49 | refinedweb | 482 | 73.81 |
Positioning.txt
> Preview
The flashcards below were created by user
jaime.davenport
on
FreezingBlue Flashcards
.
Get the free mobile app
Take the Quiz
Learn more
What are the 4 basic surgical positions?
1. supine
2. prone
3. lateral
4. lithotomy
What is compartment syndrome?
swelling of tissues within a muscular compartment which causes damage to neural and vascular structures
How do you treat compartment syndrome?
fasciotomy
fascia is cut away to relieve pressure or tension
What are some reasons for intraoperative hypotension?
1. the surgeon requests for patient to be hypotensive
2. blood loss
3. decreased tolerance to anesthesia meds
What are some factors that contribute to the risk of development of compartment syndrome?
1. prolonged procedures
2. surgical positions
3. elevation of extremities
4. intraoperative hypotension
5. increasing age
6. extremes of body habitus (very high or low body weight)
If compartment syndrome is not treated what happens?
tissue necrosis which leads to myoglobinuria then acute renal failure
end result -- amputation
Which nerves are most susceptible to nerve injury during surgery??
-superficial nerves
-nerves with a long course (such as brachial plexus)
-nerves in areas where they are poorly covered by overlying tissue
Nerve injury typically occurs because of what two reasons??
poor positioning and poor padding during surgery
but it can also occur when properly positioned and padded if increased risk factors
What nerve is most commonly injured nerve of the upper extremities during surgery??
ulnar and brachial plexus
What nerve is most commonly injured nerve of the lower extremities during surgery??
peroneal nerve
What is important to remember with tourniquets??
it is your responsibility to keep track of timing on tourniquets... make sure to chart when they are up and down.. notify the surgeon when the tourniquet needs to be released
What is the most common site of postoperative neuropathy??
Ulnar neuropathy
What are two causes of ulnar neuropathy?
hyperextension of the elbow and compression on the nerve
How will you know a patient has ulnar neuropathy??
they are unable or abduct to oppose the fifth finger
they have decreased sensation in the 4th and 5th fingers
eventually they will present with atrophy of the hand muscles -- claw hand
How should you position a patients hand to prevent damage to the nerves in the hand??
palm up
How will a patient with brachial plexus injury typically present??
sensory deficit noted in ulnar distribution
Why is the brachial plexus injured during surgery?? Name 4 ways that this damage occurs...
bc it is so long and superficial, it is easily susceptible to stretching or compression due to its length
most often occurs when:
1. the arm is abducted >90 degrees
2. there is lateral rotation of the head,
3. sternal retraction and
4. direct trauma/compression
What causes radial neuropathy??
direct pressure on nerve
Damage to the radial nerve results in?
wrist drop, inability to abduct the thumb or extend the metacarpphalangeal joints
What causes median neuropathy??
IV insertion into the AC area
this is rare
If you have damage to the median nerve how will you patient present??
the patient will be unable to oppose the first and fifth digits, patient will also have decreased sensation over the palmar surface of the lateral three and half fingers
What is the most common injury in the lithotomy position??
peroneal and sciatic neuropathy
What causes damage to the sciatic and common peroneal nerves?
stretching of sciatic nerve with external rotation of the leg, hyperflexion of the hips, extension of the knees
common peroneal nerves is often compressed between the head of the fibula and fetal frame of the stirrups
How will the patient present with injury to the sciatic or common peroneal nerves?
footdrop, inability to extend the toes in the dorsal direction, unable to evert the foot
how does femoral and obturator neuropathy occur??
during lower abd. surgeries with excessive retraction, difficult forceps delivery, or excessive flexion of the thigh to the groin
How will a patient present with damage to the femoral nerve?
will have decreased flexion of hip, decrease extension of knee, loss of sensation of superior aspect of thigh and medial/anteromedial side of leg
how will a patient present with damage to the obturator nerve?
will have inability to adduct the leg
will have decreased sensation over medial thigh
Nerve injuries are generally _____.
transient
only require assurance
How long does it typically take to recover from a nerve injury??
3-12 months
to get full movement and sensation back
What is the position of choice that causes the least amount of harm to the patient??
supine
Where should the safety belt be placed?
2" above the knees while not impeding circulation
should be able to place one hand under belt
Why should you not allow patients to be positioned with their feet/ankles crossed?
decreases perfusion and causes damage
The supine position is aka??
dorsal recumbent
What procedure typically use the supine position??
procedures of the head, neck, extremities and chest
How should you position a patients head if they have decrease cervical mobility??
let the patient position themselves before induction
Why do patients develop back aches during procedures??
bc anesthesia blocks the normal spinal curvature and muscles...this is why you should pad the lumbar spine
The alteration of the supine position to the lounge chair is favorable because??
it helps increase comfort for patient
What are cardiovascular considerations when taking care of a patient in the supine position during surgery??
-increase venous return (in comparison to standing)
-increased preload->increased CO->increased BP
What are some respiratory considerations to be aware of when your patient is in the supine position during surgery??
-decreased FRC and TLC in comparison to a standing or sitting position
-shift of the diaphragm towards the head
-decreased elastic recoil and decreased A-P diameter
-flexion of the head which can cause displacement of the ETT
What should the anesthetist do before the OR staff turns a patient to the prone position??
1. put the patient to sleep on the stretcher
2. turn the gas up and turn the o2 to 100%
3. then move the patient over to the OR table after securing the ETT good!
Where are chest rolls placed in the prone position??
-two are placed lengthwise under the axilla and along the sides of the chest from the clavicle to the iliac crests (to raise the weight of the body off the abdomen and thorax)
-one roll is also placed at the iliac or pelvic level
-should also have pillow under feet
basically support them from the clavicle to the iliac crest and all bony areas
What is important to be concerned about when a patient is placed in the prone position??
the position of the breasts and male genitalia
must be free from pressure and torsion
**you should also check the position of the dependent eye and nose if the patients head is facing to the side as well as monitoring of the ETT to ensure good position
For what kind of surgeries is a patient placed in the prone position??
procedures of the spine, posterior fossa, buttocks or rectum
How do you avoid hyperextension of the neck when a patient is in the prone position???
the shoulders should be position higher than the head
List some modifications of the prone position..
flat back prone position
jackknife position
sitting prone position
The arms should never be ______. or you'll have injury to _____.
abducted more than 90 degrees
will damage the brachial plexus
How are the arms positioned when in the prone position?? and if you use armboards how should they be positioned??
the arms can be tucked parallel to the trunk
or they can be slightly pronated and lateral to the head
armboards should be lower than the shoulders
What are 3 cardiovascular considerations to be aware of with a patient in the prone position during surgery??
decreased CO
avoid pressure over the abdomen
avoid extreme flexion of the hips
What are some respiratory considerations to be aware of with a patient in the prone position during surgery??
-FRC will be decreased compared to sitting but less than that of the supine position
-if the abdomen can hang freely
-the patient will have better diaphragmatic excursion
-there will be less pressure on the abdominal/thoracic region
-this position allows for increased oxygenation --better ventilation-perfusion ratios
Besides respiratory and cardiovascular considerations...what are 4 other complications of the prone position??
1. optic nerve ischemia (due to alterations in perfusion pressure, hypotension, hypovolemia, emboli and increased IOP)
2. venous air embolism
3. brachial plexus injury
4. facial edema (remember---if swollen on the outside..will be swollen on the inside too...be aware of this when planning to extubate)
How does a venous air emboli occur?? how do you treat it?
occurs due to negative pressures that develop if surgical site is higher than the heart
a central venous catheter tip is place at the junction of the IVC and RA to withdraw air from VAE
The lithotomy position is typically used for what procedures??
procedures requiring access to any perineal structures (gyno, urological, colo-rectal)
What should you remember when positioning the legs for the lithotomy position???
make sure to position them at the same time...if not you could cause trauma
use two people to do this
What is hemilithotomy??
only one leg is elevated instead of the typical lithotomy position where both legs are elevated
sometimes used for orthopedic surgeries
rare!
If you tuck a patients arms when in the lithotomy position it is important to remember to pay close attention to....
their fingers...when raising the foot section of the bed... you can crush their fingers if the arms are left to the side
if you place the arms out from the side this allows easier access -- using armboards is recommended
When should you position a patient in the lithotomy position before a procedure???
once you have an airway
if you go ahead and pull the patient down it will be hard for you to intubate the patient...especially if they are a difficult airway.
Whenever a patient's position is changed, what is the CRNA's responsibility???
always recheck the tube placement, listen for breath sounds, ensure that all monitors are attached properly and are reading correctly...then once that patient is finally in a position for the procedure...secure the tube how you want it!
List a few cardiovascular considerations to be aware of for a patient in the lithotomy position...
1. central blood volume will be increase (blood flows down the legs to the abdomen
2. this position doesn't effect healthy adults
3. this position can be detrimental if combined with trendelenburg in a patient with cardiac issues
4. if the patient has PVD there is increased risk for hypoperfusion, ischemia, and compartment syndrome
5. if the patient is hypovolemic, they may not have symptoms until the legs are lowered back into a neutral position--may develop severe hypotension
What are some respiratory considerations to be aware of for a patient in the lithotomy position???
1. this position is very similar the symptoms seen in the supine position (increased venous return so increased CO and ICP)
2. further decrease in FRC if patient in trendelenburg as well
3. diaphragm displacement
What are some noncardiac and respiratory complications of the lithotomy position??
1. hip dislocation (occurs when legs raised individually)
2. hip/back pain
3. femoral nerve or lumbosacral plexus stretch injury
4. arterial or venous occlusion or nerve palsy due to kinking of nerve structures
5. impaired venous outflow
6. compartment syndrome (due to stirrups)
7. peroneal nerve injury
For what procedures would you use the lateral position for surgery??
procedures involving the thorax, kidneys, posterior or lateral spine, craniotomies requiring access to lateral or posterior cranium, and some orthopedic surgeries
A bean bag is often used for the lateral position...what is it??
it is put under patient and they are wrapped in it, it is hooked to suction, the air is sucked out, the bag will harden, it is then used as a holding device to keep the patient in place on the bed
Which leg is flexed in the lateral position??
the depended leg is flexed at the knee and hip..the nondependent leg stays straight.. a pillow should be placed between the legs
how are the arms positioned in the lateral position??
the dependent arm is typically supinated on a padded armboard, abducted less than 90 degrees
the nondependent arm should be parallel with the dependent arm, level with the shoulder on an arm holding device or with pillows/blankets between the two arms
Where should the chest roll be placed when a patient is in the lateral position??
under the dependent thorax
slightly caudad to axilla---not in the axilla
What are some cardiovascular considerations for a patient in the lateral position for surgery??
1. bp changes are usually minimal
2. hypotension is possible with severe flexion (lowering of the legs in comparison to the upper body)
What are some respiratory considerations for a patient in the lateral position for surgery??
1. mediastinum will shift toward the dependent lung, decreasing the FRC in that lung as well as compliance and ventilation
ventilation-perfusion mismatch occurs because gravity pulls blood to the dependent lung but the independent lung is receiving the oxygenation
2. abdominal contents will force the diaphragm towards the head
3.
List 3 complications of the lateral position (other than resp and cardio complications).
1. nerve injury (brachial, ulnar and peroneal are the most common)
2. damage to the dependent eye
3. rhabdo (caused by placing positioning devices against muscle rather than bony prominences)
What surgeries is the sitting position typically used for??
procedures of the posterior fossa, cervical spine, breast reconstruction and shoulder surgeries
You want to avoid extreme flexion of the neck with the sitting position...what two things can be caused bc of excessive flexion???
1. endobronchial intubation
2. jugular venous obstruction
How can you check placement of the tube when in the sitting position??
there should be 2 fingerbreaths between the neck and mandible to prevent endobronchial intubation
What are some cardiovascular considerations for a patient in the sitting position for surgery??
1. there are increased risk of profound hemodynamic effects depending on the level of elevation of the torso (ex. blood will pool in the lower extremities, decreased CI, CVP, PAWP, increased SVR)
2. risk for threatened intracranial perfusion (hypocarbia, increased ICP, hypoperfusion due to hypotension)
Your MAP ___ by ___mmHG per 1 cm of elevation.
decreases
0.75
Where should the transducer be positioned if an art line is used during the procedure?
at the circle of willis
How does a venous air embolism occur??
due to air entering the venous system
negative pressure gradient between veins at the operative site and right atrium
What will you hear when the air emboli gets to the heart with an esophageal stethoscope??
mill-wheel murmur
What can you do preoperatively to rule out the patient has a patent foramen ovale??
TEE
What is the gold standard intraoperatively to check for a VAE?
do a TEE
can also use a precordial Doppler -- 3rd to 6th intercoastal spaces, right of the sternum (this is equally as sensitive as TEE in detecting, but less useful in localizing), a bovi may also pick this up.
What are some complications of the sitting position??
quadriplegia
pneumocephalus
What is the most common cause of postoperative vision loss after surgery in the prone position??
ischemic optic neuropathy
All patients who are place prone for surgey should have a documented discussion r/t _____.
vision loss
Postoperatively... anemia should be corrected to a HCT of ?
32
What should a patient's bp be post op?
20% above preop
THE MAJORITY OF PATIENTS WITH POSTOPERATIVE VISUAL LOSS HAVE BEEN DIAGNOISED WITH ??
ISCHEMIC OPTIC NEUROPATHY
PERFUSION TO THE OPTIC NERVE MIGHT BE LIMITED BY??
HIGH VENOUS PRESSURE OR EDEMA FORMATION
HOW DO YOU CALCULATE CEREBRAL PERFUSION PRESSURE??
MAP-CVP OR ICP (WHICHEVER IS HIGHEST)
IN THE UPRIGHT POSITION, THE EXTERNAL AUDITORY MEATUS IS THE EXTERNAL LANDMARK FOR??
CAN BE USED TO ESTIMATE THE POSITION OF THE BASE OF THE BRAIN
Card Set Information
Author:
jaime.davenport
ID:
251517
Filename:
Positioning.txt
Updated:
2013-12-07 22:07:35
positioning
Folders:
Description:
anesthesia
Show Answers:
What would you like to do?
Get the free app for
iOS
Get the free app for
Android
Learn more
>
Flashcards
> Print Preview | https://www.freezingblue.com/flashcards/print_preview.cgi?cardsetID=251517 | CC-MAIN-2017-43 | refinedweb | 2,753 | 53.71 |
If you have to profile application, in python for example, it’s good to read this blog post which I found very useful information.
The profile is used to compare pytables, a python imlementation of HDF5 and pickle, which is a classic choice which you ran into if you are dealing with saving big files on the harddrive.
The best tool so far seems to be the massif profiler, which comes with the valgrind suite. How valgrind works:
This will run the script through valgrind
valgrind --tool=massif python test_scal.py
This produces a “massif.out.?????” file which is a text file, but not in a very readable format. To get a more human-readable file, use ms_print
ms_print massif.out.????? > profile.txt
So I’ve run some test to check the scalability of HDF5.
[sourcecode language=”python”]
import tables
import numpy as np
h5file = tables.openFile(‘test4.h5′, mode=’w’, title="Test Array")
array_len = 10000000
arrays = np.arange(1)
for x in arrays:
x_a = np.zeros(array_len, dtype=float)
h5file.createArray(h5file.root, "test" + str(x), x_a)
h5file.close()
[/sourcecode]
This is the memory used for one array
This is for two arrays
Four arrays
And this is for fifty
As soon you enter the loop the efficiency is preserved in a really nice way
Summing up:
- one ~ 87 Mb
- two ~ 163 Mb
- four ~ 163 Mb
- fifty ~ 163 Mb
So the problem is not on pytables, but it lies somewhere else..
Recent Comments | https://blog.michelemattioni.me/2011/01/01/ | CC-MAIN-2021-04 | refinedweb | 244 | 72.46 |
How do bindings work in Isolated Process .NET Azure Functions?
In Isolated Process functions, we can use output binding to write our output of our Functions to, but they work a little differently
In my last article, I talked about how we can run our C# Azure Functions in an isolated process that decouples the version of .NET that we want to use from the version of the Azure Functions Runtime ⚡
If you haven’t read that article, you can check it out below:
Developing .NET Isolated Process Azure Functions
We can run our C# Azure Functions in an isolated process, decoupling the version of .NET that we use in our Functions…
dev.to
One thing I didn’t touch on in that article was how bindings work in Isolated Process Functions.
In this post, I’ll explain what Bindings are in Azure Functions, How they currently work with in-process Functions and how for isolated functions, they work a little differently.
What are Bindings?
In Azure Functions, we use Bindings as a way of connecting resources to our functions. We can use input and output bindings and the data from our bindings is provided to our Functions as parameters.
We can be flexible in the way that we use Bindings! We can use a combination of Input and Output bindings or none at all (using Dependency Injection instead).
Input binding pass data to our function. When we execute our function, the Functions runtime will get the data specified in the binding.
Output bindings are resources that we write our output of our function to. To use the, we define an output binding attribute to our Function method.
How do they work in Class Library Functions
In class library functions, we can configure our Bindings by decorating the Function methods and parameters using C# attributes like so:
[FunctionName(nameof("FunctionName"))]
public async Task Run([EventGridTrigger] EventGridEvent[] eventGridEvents,
[EventGrid(TopicEndpointUri = "TopicEndpoint", TopicKeySetting = "TopicKey")] IAsyncCollector<EventGridEvent> outputEvents,
ILogger logger)
{
// Function code
}
In the above code, we’ve got a function that’s triggered by event grid and uses a Event Grid output binding to publish events to. The incoming event is bound to an array of EventGridEvents and the output is published to a IAsyncCollector of EventGridEvent types.
The parameter type is defining the data type for our input data into this function.
How are they different in Isolated Process Functions
Like class library functions, binding are defined by using attributes in parameters, methods and return types.
Bindings in .NET Isolated Project are different because they can’t use the binding classes like IAsyncCollector. We also can’t use the types inherited from SDKs like DocumentClient. Instead we have to rely on strings, arrays and POCOs (Plain Old Class Objects).
Let’s illustrate this with an example. I’ve created a function that receives a HTTP POST request and persists a document to Cosmos DB.
Here’s our function code:
using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace IsolatedBindings
{
public static class InsertTodo
{
[Function("InsertTodo")]
[CosmosDBOutput("%DatabaseName%", "%ContainerName%", ConnectionStringSetting = "CosmosDBConnectionString")]
public static async Task<object> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")]();
return todo;
}
catch (Exception ex)
{
logger.LogError($"Exception thrown: {ex.Message}");
response = req.CreateResponse(HttpStatusCode.InternalServerError);
}
return response;
}
}
}
This function, uses a Azure Cosmos DB output binding. We’re applying the binding attribute to our function method which defines how we write our POST request to the Cosmos DB service.
In order to use the CosmosDBOutput binding we need to install the following package:
Microsoft.Azure.Functions.Worker.Extensions.CosmosDB
Because functions that run in a isolate process use different binding types, we need to use a different set of binding extension packages. We can find the full list of these here:
In class library functions, we would define our output binding in the method attribute where we would define the output type and write our Function output to that binding like so.
In Isolated Functions, the value returned by our method is the value that will be written to our Cosmos DB Output binding. So in our function, we make a POST request containing the Todo item that we want to write to Cosmos DB and when it gets returned from our Function, it will be written to Cosmos DB.
Let’s test this out! I’m using Postman to make the following request:
When our function starts up, we should get a local endpoint to send out POST request to like so:
When I make a POST request to that endpoint, I receive the following response:
Let’s head into our Cosmos DB account and we should see that our document has been successfully written to:
Final thoughts
Personally, I usually opt for using Dependency Injection in Functions over using output bindings when connecting to other resources.
But if we want to do something quick and easy, output bindings are really useful for getting the job done. Hopefully in this article, you can see even though there are small differences when using Bindings in isolated process functions compared to class library functions, they essentially work the same way.
If you want to read more about how the .NET isolated process works, check out this article:
.NET isolated process guide for .NET 5.0 in Azure Functions
This article is an introduction to using C# to develop .NET isolated process functions, which run out-of-process in…
docs.microsoft.com
Happy coding! ☕💻 | https://medium.com/geekculture/how-do-bindings-work-in-isolated-process-net-azure-functions-d0a902de0fc2?source=post_internal_links---------6---------------------------- | CC-MAIN-2022-33 | refinedweb | 924 | 55.13 |
Danny's Blog Pondering Programming and Poetry 2009-07-01T07:00:00+00:00 WordPress This is an XML content feed. It is intended to be viewed in a newsreader or syndicated to another site, subject to copyright and fair use.Links for 2009-06-30 [del.icio.us]2009-07-01T00:00:00-07:00<ul> <li><a href="">Simply Scala</a></li> </ul><img src="" height="1" width="1"/> for 2009-06-26 [del.icio.us]2009-06-27T00:00:00-07:00<ul> <li><a href="">InfoQ: Agilists and Architects: Allies not Adversaries Presentation</a></li> </ul><img src="" height="1" width="1"/> for 2009-06-25 [del.icio.us]2009-06-26T00:00:00-07:00<ul> <li><a href="">Home - Anti-If Campaign</a></li> <li><a href="">#874 (make Scala JSR 223 compliant) – Scala</a><br/> Scala interpreter as scriptengine</li> </ul><img src="" height="1" width="1"/> for 2009-06-22 [del.icio.us]2009-06-23T00:00:00-07:00<ul> <li><a href="">First Issue Blog » Blog Archive » A Directory of Authors on Twitter</a></li> </ul><img src="" height="1" width="1"/> for 2009-06-15 [del.icio.us]2009-06-16T00:00:00-07:00<ul> <li><a href="">Google Fusion Tables (Pre-Alpha)</a></li> </ul><img src="" height="1" width="1"/> for 2009-06-14 [del.icio.us]2009-06-15T00:00:00-07:00<ul> <li><a href="">deNieuweTuin</a></li> </ul><img src="" height="1" width="1"/> for 2009-06-13 [del.icio.us]2009-06-14T00:00:00-07:00<ul> <li><a href="">Ioke_A_folding_language(1of2)</a></li> <li><a href="">Ioke_A_folding_language(2of2)</a></li> </ul><img src="" height="1" width="1"/> Danny <![CDATA[QCon London 2009]]> 2009-03-26T19:54:04Z 2009-03-26T19:54:04Z <![CDATA. Mutable Stateful Objects Are The New Spaghetti Code According [...] Related posts:Domain-driven Ruby on Rails??]]> <p><em.</em></p> <h3>Mutable Stateful Objects Are The New Spaghetti Code</h3> <p.</p> <p><a href=""><img class="alignnone size-medium wp-image-142" title="hickey-snelwandelaars" src="" alt="" width="300" height="189" /></a></p> <p>To clarify his solution, Hickey uses an example of a match of race-walking. A race-walker must always have on of both feet on the ground. Imagine you’d want to validate this in an OO model. First you request the position of the left feet: it’s off the ground. Next you request the position of the right feet. It’s also off the ground. It must be a foul, no? Well, it depends. As state may change over time, you have to be certain that nothing has changed between those two requests. In the meantime the left foot might have already been put back on the ground. So you really want to make a snapshot of the race on a point of time. You could put a read lock on the object (the runner). But that would freeze the match, which is no more possible than freezing sales to request the state of a particular sales order.</p> <p><a href=""><img class="alignnone size-medium wp-image-141" title="hickey-referentie" src="" alt="" width="300" height="61" /></a></p> <p>The solution Clojure offers is to make values within the state inaccessible from the outside, but to refer to them indirectly. If you need to change one or more values within the state, the reference to the old state will be replaced by a reference to the new state, in a single controlled operation. So you don’t change the state itself, you change the reference to the state instead. To safely conduct this change, you use Clojure’s so-called Software Transactional Memory system (STM). This mechanism also allows another thread to safely access the state values at the same time that they are being changed. After all, the other thread is accessing the old state, which in itself is consistent. It’s actually comparable to the way database transactions are being done in Oracle. The STM offers several ways to execute the change, so for instance you could choose to do the change synchronously or asynchronously.</p> <p>It’s an elegant mechanism, which apparently has been written in Java. So you could use it in Java code, although Hickey thinks it’ll look rather weird. I don’t think that should be much of a problem, but I do wonder how you would combine this with ‘real’ persistence, in a database. An object whose state has changed, will want to commit that state to the database at some point. If that database commit is not part of the memory transaction, then what’s the point of the whole operation? At what point in the state’s time line will that state end up in the database? Unfortunately, Hickey had not yet worked on that question.</p> <p>So what about Lisp? I’m sorry, but I’m still not impressed with Lisp, or Clojure for that matter. I have no problem ignoring the parentheses, but it still seems to me that I, as a programmer, must conform to the way of thinking of the compiler/interpreter (because the language is an exact representation of the resulting AST). As consumer of a programming language, I’m not interested in homoiconicity. I prefer an elegant, readable language that allows me to express myself easily; let the compiler/interpreter do some more work if that’s what it takes. We don’t code in assembler either any more, or do we?</p> <p>Sample spelling checker, taken from Hickey’s presentation:</p> <pre class="code">; Norvig’s Spelling Corrector] (for [w words :when (nwords w)] w)) (defn known-edits2 [word nwords] )))</pre> <h3>Scala and Lift</h3> <p>Elegance, readability, expressiveness: these are also the reasons why I’m more interested in Scala. There were two Scala sessions at QCon: Jonas Bonér talked about several nifty features in Scala, and David Pollak talked about his creation: the Lift web framework. Or rather, he showed a demo in which he built a chat application in 30 lines of code, based on Comet (push technology for web pages). Cool, but I’m less and less impressed by all those “look what I can do in my framework in only one and a half line of code” type of demos. On the other hand, a decent overview of Lift was missing: what does it do, how does it work, what does it look like? Because in the Lift code samples I’ve seen so far, it’s not by far as easy to use as, let’s say, Rails. What then is the reason for choosing Lift over Rails or Grails or what have you — other than that it’s based on Scala? I thought we had agreed by now that we use the best tool for the job. For web applications that have to be built fast, I don’t see for now why Lift should be that best tool.</p> <p>Jonas Bonér went over a great number of examples of how much more pragmatic Scala can be, compared to Java code. But he also mentioned some more advanced features, like being able to define in a trait default behavior for java.util.Set methods:</p> <pre class="code">trait IgnoreCaseSet extends java.util.Set[String] { abstract override def add(e: String) = { super.add(e.toLowerCase) } abstract override def contains(e: String) = { super.contains(e.toLowerCase) } abstract override def remove(e: String) = { super.remove(e.toLowerCase) } }</pre> <p>He also showed a sample in which traits are being used to model all possible aspects of a class:</p> <pre class="code">val order = new Order(customer) with Entity with InventoryItemSet with Invoicable with PurchaseLimiter with MailNotifier with ACL with Versioned with Transactional</pre> <p>In this, each trait defines specific attributes for each facet. If you do this well, the traits can be made generic and therefore reusable. It does require a rather different view on how to model your classes. And talking about modeling: how would you model this? You could probably model traits as interfaces or abstract classes in UML.</p> <p.</p> <h3>Ioke en Obama</h3> <p>But the multitude of ‘new’ languages already started on Tuesday night, at a prequel to the conference at ThoughtWorks’ London offices. There, Ola Bini spoke for two hours about developing a new language for the JVM. Although his examples were in JRuby and Ioke (the language he developed), I had expected even more about Ioke itself. Instead, we got a rather generic presentation about developing a language. Nevertheless, those two hours went by in a flash.</p> <div id="attachment_143" class="wp-caption alignnone" style="width: 310px"><a href=""><img class="size-medium wp-image-143" title="iphone-0200" src="" alt="" width="300" height="187" /></a><p class="wp-caption-text">Ola Bini presenting in a crowded ThoughtWorks office</p></div> <p>Besides, I enjoyed the opportunity to look around at ThoughtWorks. The people at ThoughtWorks had somewhat underestimated the number of visitors so there was barely enough room for us all. Still nice to be there.</p> <div id="attachment_144" class="wp-caption alignnone" style="width: 310px"><a href=""><img class="size-medium wp-image-144" title="iphone-0203" src="" alt="Fowler and Exley talking about the Obama campaign software" width="300" height="225" /></a><p class="wp-caption-text">Fowler and Exley talking about the Obama campaign software</p></div> <p>I skipped Fowler’s talk about three years of Ruby experience at ThoughtWorks. It’s sad, I was really enthusiast when I wrote my first lines of Ruby, and I still think it’s a beautiful language, but I don’t think that Ruby is the best language/tool for the code I most want to write (back end domain logic). So.</p> <h3>Not All Of A System Will Be Well Designed</h3> <p.</p> <div id="attachment_140" class="wp-caption alignnone" style="width: 235px"><a href=""><img class="size-medium wp-image-140" title="iphone-0205" src="" alt="Eric Evans: I am a Hands-on Modeller" width="225" height="300" /></a><p class="wp-caption-text">Eric Evans: I am a Hands-on Modeller</p></div> <p>In a second session called Strategic Design, Evans discussed the situation where people who want to keep their application neat and clean, according to its architecture and design, often are being surpassed by the fast ‘hackers’ on the team, hacking something together without much regards for the rules — and who are also appreciated most by the business. Why? Because these hackers work in the Core Domain, adding core features that the business needs most. (I remember doing just that on several occasions, and indeed: users love you, fellow coders hate you). The designers/developers/architects that do care about the rules, are busy in the background fitting in and correcting these quick hacks. Something the business doesn’t really care about — if they even notice. So what can be done? Make sure you work in the Core Domain as well. Accept that not all of the system will be well designed. Isolate parts of the system that haven’t been well designed, map their boundaries, put an abstraction layer on top of them. And start building those core features, supported by a small piece of framework on top of these ‘big balls of mud’, the not so well designed systems that you won’t be able to change. The biggest challenge in a setup like that, I would say, is to prevent any new big balls of mud to take shape.</p> <h3>You Can’t Buy Architecture</h3> <p>Yet another speaker, Dan North, an architect working at ThoughtWorks, described how he eventually did manage to leave a big ball of mud a little bit better than he found it. He used the metaphore of a Shanty Town. You can’t magically turn it into a neatly laid out suburb, but you can for instance attempt to install running water everywhere. But “you can’t buy architecture”. A running gag during the conference was that you could buy SOA in two colors: red (Oracle) and blue (IBM). Fortunately we know there’s more than that: SOA is a concept, not a box you buy off the shelf but something that you can achieve even with quite simple (and cheap) tools.</p> <div id="attachment_139" class="wp-caption alignnone" style="width: 310px"><a href=""><img class="size-medium wp-image-139" title="north-shanty" src="" alt="Shanty Town" width="300" height="202" /></a><p class="wp-caption-text">Shanty Town</p></div> <p.<br /> His last lesson learned: life moves on. Accept that people will make other choices after you’ve left the project. They may make other decisions than you would have done. If, some time after, you maybe get to talk to someone still on the project, you might hear that a theater has been built in the shanty town. Maybe not like you would have built it, but that’s the way it goes.</p> <h3>War On Latency</h3> <p:</p> <ul> <li>The war on latency will become more important than execution profiling.</li> <li>If you have to tune a 9 to 5 system, record user actions during the day. You can use them during evening hours to simulate a representative load on the system.</li> <li>In order to tune well you have to benchmark. Benchmarking must be seen as a project in itself. And benchmarking might turn out to be more expensive than throwing more hardware to the system.</li> <li>If using ‘new’ languages (JRuby, Groovy etc.) causes performance problems, then these problems will be solved. Just like it happened with Java.</li> <li>The problem with marshaling XML in a SOA isn’t the time it takes to (de)serialize XML. It’s the time it takes to (de)serialize XML multiple times in the same request.</li> </ul> <h3>Cloud Databases</h3> <p>I didn’t see much of the sessions about large web architectures: BBC, Guardian, Twitter. Although no doubt very interesting, this isn’t the kind of architecture I deal with on a daily basis. That in itself might not be a reason not to learn about them, it’s more that there were always talks, scheduled at the same time, that were more in my alley. I did see a talk about cloud databases. Cloud computing, delegating parts of your system to services available on the web (just improvising a definition here), is hot..</p> <p>The talk about cloud databases presented several implementations currently available, discussing their advantages and disadvantages. To me it became clear that this is just the beginning of the whole concept. There are many different implementations, but most are just ready or not ready yet. There are obvious disadvantages, especially the fact that you often have to use a custom query language instead of SQL. And the cloud database that seems to be the best — Google’s — is not (yet?) available outside Google.</p> <h3>QCon 2010</h3> <p!</p> <div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> 1 Danny <![CDATA[Devoxx 2008 Takes Off With Flying Rectangles]]> 2008-12-08T12:37:12Z 2008-12-08T12:37:12Z <![CDATA [...] Related posts:In Search of Ruby’s Sweet SpotJavaPolis: Closing Already]]> .”<br />. </p> <p.</p> <div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> 1 Danny <![CDATA[Bastion: Born From Two Takes on DDD]]> 2008-11-01T09:10:33Z 2008-10-31T23:06:09Z <![CDATA [...] Related posts:Domain-driven Ruby on Rails??JavaPolis day 1: mixed feelings]]> <p framework can shield you from the lower level and provides you with an easy to use DSL.</p> <p:</p> <ul> <li>A domain should be ever-expanding, it knows no boundaries. Changes in requirements should lead to additions, not changes to the domain.</li> <li>A domain should always be live, always active.</li> <li>A domain should be able to execute business processes dynamically. As business processes change continually, a dynamic domain model is a better way to support them than a process model, which is static.</li> <li.</li> <li> A domain should be modelled using the time-inversion pattern and the active-passive pattern. That is: start modelling behaviour at the end of the process (in the spirit of <a href="">demand chain management</a>), and model passive objects in the real world as active ones in the domain model.</li> </ul> <p>And there’s much more to it, but you’d better visit <a href="">Vens’ own site</a> (although it is a bit fragmentary, unfortunately).</p> <p>Like I said, these are ideas that you won’t immediately find in Evans’ <a href="">Domain-driven Design: Tackling Complexity in the Heart of Software</a><img src="" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />..</p> <p).</p> <p><a href="">Bastion</a> wants to be that framework.</p> <p><script type="text/javascript" src=""> </script><br /> <noscript><br /> <img src="" alt="" /><br /> </noscript></p> <div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> 2 Danny <![CDATA[So Long]]> 2008-09-15T05:26:42Z 2008-09-15T05:26:42Z <![CDATA [...] Related posts:Who Can Live Without ItArrivalSOS]]> <p it merrier, more youthful, but also less touristy than Stockholm. Of course we may have been under influence of better weather in Göteborg, and we haven’t visited any of its darker parts that travelpedia warns about.</p> <p>As always, fragments of memories remain:</p> <p.<br />.</p> <p>The smell of fish (mussels even, in the entire Stockholm city museum; good thing we weren’t hungry) and dill (particularlt on a small but colorful street market in the Katarina Bangata). Dill seems to be everywhere and on everything in Sweden. Sort of a national herb.</p> <p>The rabarber och hallon paj (rhubarb and raspberry pie) in the Espresso House, accompanied by a capuccino. Forget Starbucks; when is Espresso House coming to Holland?</p> <p>The wild, haunted and/or icy look in the steel blue eyes of so many Swedes (not that many did look directly at me–but that may have been me). Many Swedes have beautiful, expressive faces and dress very fashionably. (An observation by M., of course).</p> <p>The smell of old boats (oil, wood, sea water) on the ships in the Maritiman museum in Göteborg. If you only have time for one museum in Göteborg, go to the Maritiman.<"/> 1 Danny <![CDATA[SOS]]> 2008-09-12T15:40:53Z 2008-09-12T15:40:53Z <![CDATA [...] Related posts:So LongWho Can Live Without ItArrival]]> <p>More things to see and do when you’re in Göteborg: visit the botanical gardens, the design museum and a collection of 19 ships floating in the harbour.</p> <p…</p> <p.)</p> .</p> <p>Today we took it easy, walking around the Slottsskogen park, seeing more elk, and doing some relaxed Saturday afternoon shopping. Luckily there’s enough Swedish design to be admired in the shops, if not in the museum.</p> <p>(Photo below taken during our design field trip in Göteborg’s shopping streets; photos of the Maritiman museum will follow.)<"/> 0 Danny <![CDATA[Who Can Live Without It]]> 2008-09-15T19:11:03Z 2008-09-10T10:09:14Z <![CDATA [...] Related posts:So Long]]> <p>Wifi on our trip to to Sweden is proving to be a mixed pleasure. In Stockholm, free wifi was abundant: in our shabby guest room (don’t know whose router that was, switched over to ssl to be on the safe side), at the <a href="">Espresso Houses</a>, in random shops; just not at <a href="">Skansen</a> and the <a href="">Royal Palace</a> (can the Swedish royal family live without Internet?). In Göteborg, it’s a different matter. Our hotel (not shabby at all, <a href="">hotel Vasa</a>). </p> <p>Yesterday I saw some stunning photography from the <a href="">Farm Security Administration</a> collection at the <a href="">Göteborg city museum</a>..</p> <p class="image"><a href=""><img src="" border="0"/></a><br /> <span>Photo by Walker Evans for the Farm Security Administration, 1935/6</span></p> <div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> 1 Danny <![CDATA[Arrival]]> 2008-09-15T19:02:53Z 2008-09-10T07:34:01Z <![CDATA [...] Related posts:So LongWho Can Live Without ItA Late Arrival]]> <p>I’m in ABBA country. So many Agnetha and Björn look-alikes have passed me by these last couple of days, I swear I wouldn’t have been surprised at all if someone had started singing in the street.<br /> The first half of the trip took us to Stockholm. A wet city, as it’s built on islands, but also because of all the rain we had. We had fun at <a href="">Skansen</a>, a combined park, outdoors museum and mini zoo. It’s located on one of Stockholm’s greener islands, Djurgård, which is also home to the <a href="">Vasa museum</a>..</p> <p>There was a lot of shopping to be done of course, interspersed with cappuccinos at the <a href="">Espresso House</a> and strangely sweet yoghurt ice creams at the <a href="">Gallerian</a>..</p> <p>Yesterday morning we visited the <a href="">City Museum</a>. Not a big museum, but with several creatively designed expositions, it’s a perfect museum if you have one or two hours left. In the afternoon we took a train to Göteborg which, on first impression, looks a bit more laid back. To be continued…</p> <p class="image"><a href=""><img class="alignnone size-full wp-image-364" src="" alt="" width="300" height="225" /></a><br /> <span>The 17th century Vasa warship</span></p> <p class="image"><a href=""><img class="alignnone size-full wp-image-364" src="" alt="" width="300" height="225" /></a><br /> <span>View on Stockholm from Södermalm, the southern island</span></p> <div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> 0 Danny <![CDATA[A Golden Cage]]> 2008-06-11T20:54:49Z 2008-06-11T20:54:49Z <![CDATA [...] Related posts:JavaPolis day 2, Best of Both SidesThe Hot and Cold SummerHow Java is Ruby?]]> <p?</p> <p>At yesterday’s <a href="">RubyEnRails 2008 conference</a>,?</p> <p>No way. It’s not about the language.</p> <div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> 2 Danny <![CDATA[Closures And The Ars Rhetorica]]> 2008-03-26T18:36:55Z 2007-12-23T16:24:27Z <![CDATA: “We have been seeing this for awhile via XDoclet, and [...] Related posts:JavaPolis day 4, More on ClosuresJava Closure ExamplesProper Properties]]> <p:</p> <p><em>.”</em><br /> <a href="">techno.blog(”Dion”)</a></p> <p><em>“While the advantages of annotating the code (JSR 175 - Metadata Facility for Java) are somewhat clear to me, I have been wondering what the drawbacks could be. I don’t deny that being able to specify auxiliary information for classes, interfaces, fields and methods is a good thing. What I question is the means we will supposedly use to achieve this, namely, we will be putting the whole stuff directly within the code. If not used with care, annotations could (and most certainly will) massively contribute to code pollution [...]“</em><br /> <a href="">Val’s Blog</a></p> <p>Next, take a look at this code sample and see if you can make sense of it.</p> <pre class="code"> @C1(C=2) @C2(C=3) @C3(C=4) @Private(access=PUBLIC) public class c { @X1(Y=1) @Y2(Z=2) @Z3(X=3) @Public(access=NONE) private int i; @A1(presentation</a> <a href="">some examples</a> of how closures might actually make life (and coding) a lot easier. Which one do you think is easier to understand and maintain, and is less error-prone?</p> <p><em>With closures:</em></p> <pre class="code"> doTransaction(entityManager, {=> Person p = new Person("Last name"); entityManager.persist(p); });</pre> <p><em>Without closures:</em></p> <pre class="code"> EntityTransaction tx = entityManager.getTransaction(); try { tx.begin(); Person p = new Person("Last name"); entityManager.persist(p); tx.commit(); finally { if (tx.isActive()) { tx.rollback(); } }</pre> <p, <a href="">Java is not dead</a>,.</p> <p class="image"><img src="" alt="Neal Gafter (black hat) watching Josh Bloch’s presentation at JavaPolis 2007" /><br /> <span>Neal Gafter (black hat) watching Josh Bloch’s presentation at JavaPolis 2007</span></p> <div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> 8 Danny <![CDATA[JavaPolis: More About ME]]> 2007-12-13T10:51:18Z 2007-12-13T10:51:18Z <![CDATA [...] Related posts:JavaPolis day 3, Keynotes and KeynotsFinal Thoughts on JavaPolis 2005, Part 2: Is JavaPolis the European JavaOne?JavaPolis day 4, The Monkey in the Details]]> <p in everything with a Flash player on it? Where can I sign up?</p> <p>Stephan Janssen’s keynote on his side project, <a href="">parleys.com<.</p> <p?</p> <ol> <li.</li> <li>“Closures are sexy.” Guess who said that, completely out of the blue? But more importantly, why didn’t the interviewer touch the subject that everyone expected to guarantee some fierceful debate?</li> <li>a < b is not the same as a - b < 0. In C. I think that’s even a better t-shirt text than “There’s only 10 kinds of people: those who understand binary arithmatic and those who don’t.”</li> </ol> <h4>The Keynote Continues</h4> <p>Sun’s Tim Cramer is next on Thursday’s keynote. “Who’s programming Java ME?” he asks the audience. About five people raise their hands. “Who’s done it with NetBeans?” One hand remains in the air.</p> <p.</p> <p>One last observation: while I’m in deep concentration for writing this blog post, I suddenly hear Sun’s Java evangelista Angela Caicedo talk about “moving my guys around.” Huh? Oh, she’s talking about <em>sprites.</em></p> <div class="feedflare"> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> <a href=""><img src="" border="0"></img></a> </div><img src="" height="1" width="1"/> 0 | http://feeds.feedburner.com/DannysBlog | crawl-002 | refinedweb | 4,573 | 63.49 |
java.lang.IllegalArgumentException: Not a file or directory: xxxxxx\.idea\modules\src\test\resources\features 关注
Hi,
I'm getting the above compile error in my Scala test project and just cannot resolve.
My project structure is:
CucumberTest
-.idea
-project (sources root)
-src -> main -> scala
-> test -> resources -> features -> firstFeature.feature
-> scala -> stepdefs (package) -> RunCucumber.scala
My RunCucumber class :-
package stepdefs
import cucumber.api.junit.Cucumber
import cucumber.api.CucumberOptions
import org.junit.runner.RunWith
@RunWith(classOf[Cucumber])
@CucumberOptions(
features = Array("src/test/resources/features"),
glue = Array("stepdefs"),
format = Array("pretty", "html:target/cucumber-report"),
tags = Array("@wip")
)
class RunCucumber {
}
I dont know why its trying to look in the .idea directory path to do the compile or where to change the configuration to resolve this?
When i created the scala project there was no resources directory in test, i had to create it (along with the features directory).
The error occurs when i run RunCucumber
Any advice please for a newbie? I understand the issue, just dont know the cause or how to resolve.
Cheers
I've created a ticket for a further processing. Is it possible to provide the project or at least some of the following information as attachment to the ticket?
Screenshot of
- project view. If it's higher than one screen - show the place where problematic file locates.
- project structure -> modules -> Sources
- project structure -> modules -> Paths
- project structure -> Project
IDEA logs after the error appears (Help menu -> Collect and Show Logs in Finder)
Hi Anton - thanks for taking the time to reply.
I'm trying to complete the Scala SBT Cucumber tutorial that is here:
I've downloaded the latest versions of IntelliJ, JDK9 etc.
When i follow the instructions, no resources directory is created :
I create the resources directory along with features etc but when i run RunCucumber, it throws the error and expects the directory path to be in the .idea path.
I've managed to set up Java Selenium and Scala projects okay but seem to be having a real problem with this.
Any help or pointers much appreciated (I've added the screenshots as an attachment to the ticket)
Got it. Thanks! We'll take a look. | https://intellij-support.jetbrains.com/hc/zh-cn/community/posts/115000609904-java-lang-IllegalArgumentException-Not-a-file-or-directory-xxxxxx-idea-modules-src-test-resources-features | CC-MAIN-2022-40 | refinedweb | 365 | 57.06 |
Hello,
I need to upload a file to my server, and then i need to move this uploaded file to another directory and change the name of it.
The solution I gave you writes in the database the path to the file, but the file is stored on the file system in the specific folder you set.
If this is not what you want, can you make an example? If you just store the file on the file system, you wont' be able to retrieve the file in the Web application using the standard units.
In any case, to do this you have to model a Script Unit that stores the file where you want. You can refer to the official WIKI (Getting started with the Script unit). In the Script Unit you have to write down the Java code necessary in order to save the file in a specific position.
Hi,
you can model in the Data Model an attribute of type BLOB inside an Entity. In the Properties View of the attribute you can set a specific Upload Path. This means that when you upload a file, it will be saved in the folder "upload/images/photogallery". The upload folder is located by default inside the webapps folder of the Web application.
You can change this default and choose a folder outside the webapps one to store files. This can be done configuring the RTXConfig.properties file. This file can be accessed in this way:
You have to change the uploadDirectory writing an absolute path and then the uploadDirectoryIsAbsolute setting it to "true". In this way you can store files in a specific folder on the file system of the server. For further information about the RTXConfig.properties file you can refer to this article on the WebRatio Official WIKI.
Finally, to change the name of the uploaded file with a custom one, you can model an Entry Unit having
two fields:
Then, you place a Create Unit over the Entity containing the BLOB attribute. On the coupling of the link connecting the Entry Unit with the Create Unit you will find two couplings available for the BLOB attribute, one is the file itself, the other is the name to assign to the file once it's uploaded.
You should first decide whether you need to have the file mapped to an entity (and therefore accessible via standard entity-based units) or not.
If you don't want to permanently store the file on DB but still would like to map it to an entity, a solution could be creating an ad-hoc entity with Duration set to volatile (session scope)/volatile (application scope). However, keep in mind that this will last until the user session expires or the application is restarted.
On the other end, if you don't want to map a BLOB property but just need to upload a file, you can use a Script Unit like suggested by michela.
#input RTXBLOBData file, String path
import org.apache.commons.io.IOUtils
def output = null, input = null;
try {
output = new FileOutputStream(path)
input = file.openFileInputStream()
IOUtils.copy(input, output)
} finally {
IOUtils.closeQuietly(input)
IOUtils.closeQuietly(output)
}
Groovy scripts and the RTXBLOBData interface are explained in the WebRatio Wiki.
How to deal with BLOBs.
Try make it using filejam upload. Its good way for transfer files | https://my.webratio.com/forum/question-details/upload-file-and-the-move-it-to-other-location;jsessionid=3386D093FC708B639D9EB8973D29C379?nav=43&link=oln15x.redirect&kcond1x.att11=102 | CC-MAIN-2021-17 | refinedweb | 559 | 61.77 |
love.filesystem.getDirectoryItems not cross platform
love.filesystem.getDirectoryItems seems to not be cross platform between Android and Linux (and I assume OS X and Windows. If someone could test the attached
game.love to confirm that it's an issue with
love-android-sld2 and not love tip,
0.9.1.)
The directory is set up like this:
./main.lua ./animals ./animals/cats ./animals/cats/1.jpg
The expected result of
love.filesystem.getDirectoryItems("animals/cats/") on Android is
{"1.jpg"} but the actual result is
{}.
I have tested this on a Linux, Android [OUYA and Samsung Stellar]. Linux produces the expected result, and Android produces the incorrect result.
Here is a Linux screenshot (
0.9.0):
Here is the Samsung Stellar screenshot (last built c3a21270abcaaf8b22b94f2b7bd7aa55c607e861) :
I have the feeling this may be due to the updates that effected whatever runs behind
love.filesystem. I will test this against tip on both
love-android-sdl2 and
love.
I am marking this as a critical bug as it is a part of the love api failing, and not some system workaround.
love-android-sdl2 should be as cross platform as possible.
If there's anything I can do, please tell me!
The function hasn't changed between 0.9.0 and 0.9.1, however love-android uses PhysFS 2.1 (which is still in development) instead of PhysFS 2.0.
It's possible this behaviour could have changed in between PhysFS versions - or maybe it's some android-specific quirk that PhysFS 2.1's code hasn't accounted for yet (I don't think there is much Android-specific code in PhysFS, if any at all.)
Should I report this to PhysFS?
If we make sure that it's physfs' fault, yeah.
It is a bug in physfs. The filtering of files due to symbolic links vs actual files causes the problems. One quick fix would be to simply allow symbolic links by adding
to void Filesystem::init().
Another workaround (as you already figured out) is to make sure not to have trailing slashes.
I have just sent an email to the physfs developers at
One way or the other this will be fixed!
Edit: And thanks for the test case! Helped a lot figuring out what's happening!
@Martin Felis I'm very happy to do as much as I can. I feel rather useless, as my Java and C/C++ is very rusty!
Workaround added in changeset 3f268eb.
How are we keeping track of these changes from the actual love tag?
I imagine tracking all these changes that we do to the source will be chaos to revert when we want to upgrade to the next version of love.
Perhaps we should have a folder of patches that should be applied to the love branch on build?
The changes related to the android port are not very extensive and are bracketed using #ifdef LOVE_ANDROID ... #endif LOVE_ANDROID.
I have a fork of bartbes' experimental repository at. That fork contains a proper android branch which is mostly based on @Alex Szpakowski 's mobile-common branch. Whatever ends up there will eventually end up here.
From time to time I transfer code from this repository to love-android and vice versa (somewhat outdated atm however). Creating patches to the official LÖVE is very easy using my love-android repository.
Ok, cool, so long as there is a plan of action for providing upstream or pulling downstream. | https://bitbucket.org/MartinFelis/love-android-sdl2/issues/36/lovefilesystemgetdirectoryitems-not-cross | CC-MAIN-2019-30 | refinedweb | 577 | 67.86 |
chown, fchownat - change owner and group of a file
#include <unistd.h>
int chown(const char *path, uid_t owner, gid_t group);
[OH]
#include <fcntl.h>#include <fcntl.h>
int fchownat(int fd, const char *path, uid_t owner, gid_t group,
int flag);.
Upon successful completion, chown() shall mark for update the last file status change timestamp of the file, except that if owner is (uid_t)-1 and group is (gid_t)-1, the file status change timestamp need not be marked for update...
None..
None.
chmod, fpathconf, lchown
XBD <fcntl.h>, .
Austin Group Interpretation 1003.1-2001 #143 is applied.
The fchown/0053 [461], XSH/TC1-2008/0054 [324], XSH/TC1-2008/0055 [278], and XSH/TC1-2008/0056 [278] are applied.
POSIX.1-2008, Technical Corrigendum 2, XSH/TC2-2008/0062 [873], XSH/TC2-2008/0063 [591], XSH/TC2-2008/0064 [485], XSH/TC2-2008/0065 [817], and XSH/TC2-2008/0066 [817] are applied.
return to top of pagereturn to top of page | http://pubs.opengroup.org/onlinepubs/9699919799/functions/chown.html | CC-MAIN-2016-44 | refinedweb | 163 | 75.71 |
We have not heard back from you, but with the data provided we are confident this is a known issue and has to do with versions of the runtime namely System.Data.SqlClient namespace successfully connecting to different SQL Server 2008 pre-release CTPs.
Orcas (Visual Studio) Beta 2 works with SQL Server 2008 July CTP
See this post for the entire support matrix:
The Tabular Data Stream (TDS) version 0x730a0003 of the client library used to open the connection is unsupported or unknown. The connection has been closed. [CLIENT: <local machine>]
This is a connect with the bundled SMS, not Orcas. | https://connect.microsoft.com/SQLServer/feedback/details/306625/katmai-sql-server-error-233 | CC-MAIN-2018-05 | refinedweb | 102 | 59.84 |
CodePlexProject Hosting for Open Source Software
Hi all!
Recently I experienced the same problem as the guy
here, and solved it according to the answer.
Basically I have a record class in a subfolder of the Modules folder. This works as long as the record class is in the root namespace ModuleName.Models. Modifying the namespace to ModuleName.Models.Subfolder causes the persistence error described in the
linked thread. However I think for better organization of the source code it really should be possible to have records in subsequent namespaces as well.
Is this feasibly possible? Should I open an issue for it?
I agree. Please file a bug with some repro steps.
I opened one.
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://orchard.codeplex.com/discussions/274145 | CC-MAIN-2016-40 | refinedweb | 152 | 69.89 |
I am extremely new to python 3 and I am learning as I go here. I figured someone could help me with a basic question: how to store text from a CSV file as a variable to be used later in the code. So the idea here would be to import a CSV file into the python interpreter
import csv
with open('some.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
w = ["csv file text"]
print (list(itertools.permutations(["w"], 2)))'
itertools.permutations() wants an iterable (e.g. a list) and a length as its arguments, so your data structure needs to reflect that, but you also need to define what you are trying to achieve here. For example, if you wanted to read a CSV file and produce permutations on every individual CSV field you could try this:
import csv with open('some.csv', newline='') as f: reader = csv.reader(f) w = [] for row in reader: w.extend(row) print(list(itertools.permutations(w, 2)))
The key thing here is to create a flat list that can be passed to
itertools.permutations() - this is done by intialising
w to an empty list, and then extending its elements with the elements/fields from each row of the CSV file.
Note: As pointed out by @martineau, for the reasons explained here, the file should be opened with
newline='' when used with the Python 3 csv module. | https://codedump.io/share/oUTgP58S2UNs/1/how-to-import-data-from-a-csv-file-and-store-it-as-a-variable-in-python | CC-MAIN-2017-13 | refinedweb | 239 | 72.56 |
My use case is to save sensor data as files to a microSD card. Periodically, connecting to wifi and sending the data files back to a remote MQTT broker.
I am using a Wemos D1Mini and have a shield attached. The SPI connections are standard. The latest version of micropython 1.9.3 is installed. The microSD card is a decent brand, has been checked as OK and has been formatted.
-On initial boot the microSD card is not added to the filesystem; of course.
-Adding the MicroPython driver for SD cards using SPI bus returns an error at the unmount function when trying the suggested sample code
Code: Select all
import machine, sdcard, os sd = sdcard.SDCard(machine.SPI(1), machine.Pin(15)) os.umount() os.VfsFat(sd, "") os.listdir()
Code: Select all
TypeError: function takes 1 positional arguments but 0 were given
the excellent esp8266 tutorial also fails at the same point of unmounting.
The micropython UOS module for the ESP8266 does not contain mount/unmount functions so I am not sure what to do. Should I be creating a SPI object ? | https://forum.micropython.org/viewtopic.php?f=16&t=4392&p=25423 | CC-MAIN-2020-10 | refinedweb | 184 | 65.42 |
When adding another handler in the same namespace, I have been foiled by the built in caching. Turn off the caching, or reset IIS. Maybe that can help.
When adding another handler in the same namespace, I have been foiled by the built in caching. Turn off the caching, or reset IIS. Maybe that can help.
Dave W
Can somebody let me know which is the latest Router Version?
Thanks in Advance
Thomson
Latest "official" code is in post #1 (the 0.6 version)
My latest code with the additions I've mentioned in this thread, which I don't believe the Ext team has had time to evaluate and include, are in this message:
Or on my site at:
because someone had a problem unzipping the version I uploaded.
I would have started a new thread for my "branch" but the changes aren't all that different and I'd rather they just get included in the original code. There was talk about setting up a google code for it, and if someone at Ext wants to do that then I'll happily seed it with my latest copy to eliminate confusion.
D
Hello All,
I have tried using the router version 6 i have tried calling a function using Ext.Direct
In firebug i can see there is a post happening to the handler and immediately i am getting the
uncaught exception: Ext.data.DataProxy: DataProxy attempted to execute an API-action but found an undefined url / function. Please review your Proxy url/api-configuration.
I am loading the store using the following code
The Response will be having a Result attribute which having my json, How do i tell the reader to take only thatThe Response will be having a Result attribute which having my json, How do i tell the reader to take only thatCode:var mystore = new Ext.data.DirectStore({ paramsAsHash: false, root: 'Rows', api: { load: MyApp.Sample.GetOrder('labelle') }, //directFn: , idProperty: 'id', autoLoad: true, fields: [ { name: 'id' }, { name: 'name' } ], listeners: { load: function(s, records) { Ext.MessageBox.alert("Information", "Loaded " + records.length + " records"); }, beforeload: function(t, params) { Ext.MessageBox.alert(t); }, exception: function(current, action, rs, params) { Ext.MessageBox.alert(action); } } }); var grid = new Ext.grid.GridPanel({ store:mystore, cm: new Ext.grid.ColumnModel([ new Ext.grid.RowNumberer(), { header: "+/-", width: 120, sortable: true, dataIndex: 'id' }, { header: "Sel", width: 70, sortable: true, dataIndex: 'name' }, ]), viewConfig: { forceFit: true } });
Thanks in Advance
Thomson
I don't understand the "api" property you have on your directstore. Here's an example of one of mine:
This calls a method that gathers up the note objects and then packs them into a custom JSON object that I use in my C# code. The method returns that, which gets turned into the JSON below and sent back to the browser.This calls a method that gathers up the note objects and then packs them into a custom JSON object that I use in my C# code. The method returns that, which gets turned into the JSON below and sent back to the browser.Code:noteStore: new Ext.data.DirectStore({ directFn : Note.GetNotes, idProperty : 'NoteId', root : 'notes', fields : ["NoteId", "ShortText", "NoteText", "Updated", "Username"] }),
(I'm not using 0.6 btw, I'm using my branch of it, so I don't use ParamsAsHash, etc.)(I'm not using 0.6 btw, I'm using my branch of it, so I don't use ParamsAsHash, etc.:
I took out the assignment in my code and it seems to be working all around - so I think this was an unnecessary step anyway. Will report back if its not.I took out the assignment in my code and it seems to be working all around - so I think this was an unnecessary step anyway. Will report back if its not:
CheersCheersCode | https://www.sencha.com/forum/showthread.php?68161-Ext.Direct-.NET-Router&p=378547&viewfull=1 | CC-MAIN-2016-36 | refinedweb | 635 | 73.37 |
Learning to Use X11
April 26th, 2002 by Philipp K. Janert in
When.
Draw a bare window (without Close, Minimize, Maximize buttons)
On February 11th, 2007 Anonymous (not verified) says:
how to create a window described in the subject? I cannot find out the solution.
thanks and regards
woapxp
x11 man
On January 14th, 2007 renu (not verified) says:
i m new to x11. i m not getting the point how to set the path be4 running x11 prog. and i m not getting the manual pages after writing the man command on the shell.can anybody help me??
how to link xlib
On March 9th, 2005 Anonymous (not verified) says:
how to link xlib
A Simple OpenGL Program Using GLUT and C
On August 25th, 2006 mattv (not verified) says:
On October 9th, 2002 Anonymous
On May 26th, 2003 Anonymous
On May 2nd, 2002 dlc (not verified) says:
What I expected from this article was how to use X, not code an X client. Change the title and you'll have an excellent resource (as how the article employs resources, not how an X user employs resources).
Re: Learning to Use X11
On April 30th, 2002 Anonymous says:
The author must be using Debian because he said the latest version of XFree86 is 4.1.0 not 4.2.0.
Re: Learning to Use X11
On May 1st, 2002 masinick (not verified)
On April 30th, 2002 Anonymous says:
"We therefore explicitly free the allocated resources"
To be fussy, I guess we should call XFreeGC then also.
Looking forward for the next episode
servers and clients ... sure they are software
On April 29th, 2002 Anonymous says:!
On April 30th, 2002 Anonymous says:
On April 29th, 2002 Anonymous
On April 29th, 2002 Anonymous says:
Multiple instances for one user of the WindowMaker window manager are also not supported.
Re: Learning to Use X11
On April 29th, 2002 Anonymous
On November 15th, 2003 Anonymous
On April 30th, 2002 Anonymous says:
it should read #include
Re: Learning to Use X11
On April 29th, 2002 Anonymous says:
Where is the difference between
#include and #include?
Magical whitespace?
Re: Learning to Use X11
On April 29th, 2002 Anonymous says:
I think the HTML of the original poster's comment got "filtered" by PHP nuke.
Re: Learning to Use X11
On April 30th, 2002 Anonymous says:
Yes, sure, but what is the file to #include between the
/ /
then? 8-)
#include or #include
On April 22nd, 2006 Anonymous (not verified) says:
#include <Xlib.h>
or
#include <X11/Xlib.h>
Re: Learning to Use X11
On April 29th, 2002 Anonymous says:
god I think my brain has frozen on monday morning, I found th e source, compiled it and it work!!!!!
doh!!
Re: Learning to Use X11
On April 29th, 2002 Anonymous says:
I'd like to give this a go? but where's the source luke?
Link
On April 30th, 2002 Anonymous says:
The paragraph titles are links, Jar-Jar. Click them with your favourite pointing device.
Me sah
On October 6th, 2006 jar Jar (not verified) says:
Me sah no sah point divvy-sicer onna dee clikkers link.
Post new comment | http://www.linuxjournal.com//article/4879 | crawl-002 | refinedweb | 525 | 78.28 |
java - file delete - Java Beginners
java - file delete I will try to delete file from particular folder... will try to delete these files. But it doesn?t delete from this folder.
My code...){
try {
File delete = new File (incurrentFile);
System.out.println
J2ME delete file - Java Beginners
J2ME delete file How do i delete a textfile on a mobile phone using j2me? Hi Friend,
Please visit the following link:
Hope that it will be helpful for you.
Thanks delete files in Java?
Delete a File using File Class Object
Delete a File using File Class Object
In this section, you will learn how to delete a file.
How to delete a character from a file in java - Java Beginners
/beginners/
Thanks
I...How to delete a character from a file in java I'm not gettting how to remove a character from a file in java....could any one help me out??
delete jsp
delete jsp <%@ page
<title>Delete Student</title>
</head>...;/Controller">
<input type="hidden" name="page" value="delete"/>
<
Java delete file if exists
Java delete file if exists Hi,
Hi how to delete file if exists?
I need example code of java delete file if exists.
Thanks
Hi,
following code can be used:
String tempFile = "C:/mydir/myfile.txt";
//
This Question was UnComplete - Java Beginners
to delete the temporary file). **/
public void deleteFile(String fileName...();
zos.close();
/** Delete the temporary file created
Java - Deleting the file or Directory
Java - Deleting File
... if that exists. We will be declaring
a function called deletefile() which deletes the specified directory or
file.
deletefile(String file)
The function deletefile
Java file delete
Java file delete
In this section, you will learn how to delete a file.
Description of code
Java makes file manipulation easier by providing many useful... we are
going to delete a file. For this, we have created an object of File
Java - Deleting the file or Directory
Java - Deleting the file or Directory
This example illustrates how to delete... the specified file if that exists. We will be declaring
a function called deletefile
java - Java Beginners
();
}
}
/**
* Deletes the object file.
*/
public void deleteFile() {
File
stringbuffer - Java Beginners
://
Thanks... in the StringBuffer.
sb.delete(10, 15);
System.out.println("After delete
java - Java Beginners
java how to delete duplicate rows in excel file to csv using java
delete
delete how delete only one row in the database using jsp.database... type="button" name="edit" value="Delete" style="background-color:red;font-weight... = conn.createStatement();
st.executeUpdate("DELETE FROM employee WHERE empid programming - Java Beginners
links: programming i'm asking for the java code for adding , viewing ,delete, edit and printing information...how can i make this...can you give me
java programming - Java Beginners
java programming im asking for the code of adding , viewing ,delete... the following links:
Exercise - Delete Blanks
Java: Exercise - Delete Blanks
Write a method to delete all blanks from its parameter.
The method signature is
public static String deblank(String s...)
deblank("I'm feeling fine.") returns "I'mfeelingfine."
Delete Blanks
Java delete non empty directory
Java delete non empty directory
This section demonstrates you how to delete a non empty directory.
It is easy to delete a directory if it is empty by simply calling the built
in function delete(). But if the directory is not empty
java programing - Java Beginners
, and pager. Write a java GUI application to add, edit,delete and find the address...java programing How to Design and create a java class for address book object that contains a person's name, home address and phone number
java code - Java Beginners
java code plese provide code for the fallowing task
Write a small record management application for a school. Tasks will be Add Record, Edit Record, Delete Record, List Records.
Each Record contains: Name(max 100 char
preparestatement in jsp - Java Beginners
preparestatement in jsp I'm dyana from Malaysia.I am a Java beginners and I keen to learn and always search and explore through Roseindia.I had try... would like to know the insert,view,delete and update preparestatement.How I could
java programming - Java Beginners
java programming asking for the java code for adding delete... extends JFrame {
JButton add,delete,save,remove;
JTextField t1,t2,t3,t4,t5... JButton("Add Information");
delete=new JButton("Delete Information");
save=new
Delete a file from FTP Server
In this section you will learn how to delete file from FTP server using java
Link List proble, - Java Beginners
/java/beginners/linked-list-demo.shtml
Hope that it will be helpful for you... Node
to your list and Delete to your list......
my brain is bleeding can you
links: How do i make these buttons work?
Update, Delete, Save, Submit
java - Java Beginners
java Develop a template for linked-list class along with its methods in Java. Hi Friend,
Try the following code:
class Link...;
first = link;
}
public Link delete
java beginners - Java Beginners
the following links: beginners what is StringTokenizer?
what is the funciton
Hibernate Delete Query
Hibernate Delete Query
In this lesson we will show how to delete rows from the
underlying database using the hibernate. Lets first write a java class to delete
a row from
Java source code - Java Beginners
Java source code Write a small record management application for a school. Tasks will be Add Record, Edit Record, Delete Record, List Records. Each... is, total file should not be re-written for every add/delete operation
java - Java Beginners
);
link.lk = first;
first = link;
}
public Link delete() {
Link temp = first
java - Java Beginners
java how to insert and delete a number in between an array Hi Bhavana,
You can write two seperate methods for inserting and deleting with three parameters. one as the index and the other the entire array
java - Java Beginners
in Java. PROGRAM TO IMPLEMENT LINKED LIST
Implementation File...");
}
}
public void deletefirst() /*To delete the first element...);
System.out.println(" is deleted.");
}
}
public void deletelast() /*To delete
Delete image from folder - JSP-Servlet
Delete image from folder Hi
Thanks Rajnikant
to given me... user id going to logout then at that time i need to delete image
Pie(userid).png
if you have any java code for deleting this please send me. not JDBC code
reply me - Java Beginners
reply me Hi,
user enter vend_id in text box ten open the addform.jsp
In the addform.jsp have two button Update and delete... is incorrect
user click delete button then file is not called
please send
java database pblm - Java Beginners
java database pblm Hi,
I have 5 records in database with the same ID. I want to delete third record. what should i do.plzz help me. thank u... the code to delete the record by getting all the column values of that record
java - Java Beginners
");
b1=new JButton("Insert");
b2=new JButton("Delete");
b3=new...();
PreparedStatement pst=con.prepareStatement("delete from test where
Java array - Java Beginners
Java array Q 1- write a program that counts the frequency...--
programming
java
hello
would be displayed as
hello java programming... if statement?
Q7-write aprogram to delete all occurences of an element and shift
Delete image from folder - JSP-Servlet
Delete image from folder Dear All,
i used some coding... some time its burden for server.
so dear friends i want to delete that image when user will logout using java code.
anybody having idea about then please
java setup - Java Beginners
java setup Hi,
Iam created a desktop
login application using swings.
pls observe the following code:
import javax.swing.*;
import...("Delete");
b3=new JButton("Update");
b4=new JButton("Single");
b5=new JButton
java time - Java Beginners
java time Hi,
Iam created a desktop login application using swings.
pls observe the following code:
import javax.swing.*;
import java.awt....("Delete");
b3=new JButton("Update");
b4=new JButton("Single");
b5=new JButton
java Big - Java Beginners
java Big Hi
pls observe the following coed:
import mysql.DataAcc;
// import package class for getting database connection
import...");
b1=new JButton("Insert");
b2=new JButton("Delete");
b3=new
java desktop - Java Beginners
java desktop Hi,
Iam created a desktop login application using swings.
pls observe the following code:
import javax.swing.*;
import...("Delete");
b3=new JButton("Update");
b4=new JButton("Single
java desktop - Java Beginners
java desktop Hi,
Iam created a desktop login application using swings.
pls observe the following code:
import javax.swing.*;
import...("Delete");
b3=new JButton("Update");
b4=new JButton("Single");
b5=new JButton
Delete and edit data in xml file using JSP
Delete and edit data in xml file using JSP I want to know how to delete and edit data from an XML file by use of JSP.
I have XML file having tasks... in the xml file,I want to delete and edit some tasks using task id then how can i do
Servlet - Java Beginners
Servlet i'm a new boy in java. i have a question which is about the servlet. i have make a simple web application which is user can input data... delete function to delete the data on the list but i don't know how to do it. could
Delete a Column from a Database Table
\jdbc\jdbc\jdbc-mysql>java DeleteColumn
Delete columns example... Delete a Column from a Database Table
... to delete a
column from a database table. We are not going to create a new table
java - Java Beginners
");
b1=new JButton("Insert");
b2=new JButton("Delete");
b3=new
Java Project Questions - Java Beginners
Java Project Questions Hello sir ,I want Course Form in JAVA SWING that includes following contents-
1)Course Id -Numeric
2)Course NAME-TEXT
3)Course Duration-NUMBERS
4)Course Fees-NUMBERS
I want to to add,Update,
school mangement application - Java Beginners
school mangement application record management application for a school IN JAVA + SOURCE CODE.add, delete,modify. No database should be used. All... for every add/delete operation. Listing records should print the names of the users
HIiiiiiiiii - Java Beginners
form and two button update and delete one text box of vend_id
2:- if user enter the vend_id in text box and press delete button then this recordd..."
To delete the record page "process.jsp"
<
runtime error - Java Beginners
file: " + f);
}
else
System.out.println("Cannot delete: " + f... file: " + f);
}
else
System.out.println("Cannot delete: " + f...: " + f);
}
else
System.out.println("Cannot delete: " + f);
}
}
}
Thanks
code - Java Beginners
code hello sir
i am doing project on java
for that i want...
System.out.println("Cannot delete: " + f);
}
}
}
please verify...: " + f);
}
else
System.out.println("Cannot delete: " + f);
}
}
}
Thanks
Java for beginners
Java for beginners Java for beginners
Which is the best resource... Java video tutorial for beginners.
Thanks
Hi,
Here are the best resources for Learning Java for beginners:
Java Video tutorial
Java tutorials
JDBC Delete Row In Table Example
JDBC Delete Row In Table Example :
In this tutorial we will learn how delete... or more specific row delete from
table that follow any given condition...
Mysql query "DELETE FROM user where user_id=1 "
abt proj - Java Beginners
the following link:... to go on home page on home page containe some tab like add, delete, update,etc... Record",p1);
tp.addTab("Edit Record",p2);
tp.addTab("Delete Record",p3);
add(tp
runtime error - Java Beginners
);
}
else
System.out.println("Cannot delete: " + f);
}
}
} Hi
Deployment - Java Beginners
:794: Unable to delete file D:\WorkSpace\Struts\WebApplication1\build\web\WEB-INF
Java for beginners - Java Beginners
://
Thanks...Java for beginners Hi!
I would like to ask you the easiest way to understand java as a beginner?
Do i need to read books in advance
Java XML modification - Java Beginners
Java XML modification hey I want to delete the nodes in Xml file...;
public class Delete {
public static void main(String [] args... class Delete{
static Transformer tFormer;
static DocumentBuilder builder
On HTML - Java Beginners
delete the default value and enter the name.But later if I again focus on the text... code:
delete default text from textbox
function make_blank
javascript - Java Beginners
,n with everyclick of delete buton the row shud get deleted tis is working fine...; Hi Friend,
Try the following code:
1)person.jsp
Add/
Convert To Java Program - Java Beginners
Convert To Java Program Can anyone convert this C program codes to Java codes,please...thanks!
#include
int array[20];
int dcn;
int cntr=0... the value you want delete: ");
scanf("%d",&s);
for(j=0; jro;js
Delete Account
Delete Account How to delete account
Add Edit And Delete Employee Information
, edit and delete the Employee's
information from the database using java swing...
Add Edit and Delete Employee Information Using Swing
... updated. In the third tab, we have allowed the user to delete the particular
employee
servelets - Java Beginners
e){}
}
}
3)
Add
Edit
Thanks
javascipt - Java Beginners
');
newDelButton.type ="button";
newDelButton.value = "
Java Project Questions - Java Beginners
Java Project Questions Hello sir ,I want Course Form in JAVA SWING...,Delete Course Details into to Access Database,and then this course table connected... JButton(" Save");
deletebtn=new JButton("Delete");
p1.add(l1);
p1.add(tf1
Java Project Questions - Java Beginners
Java Project Questions Hello sir ,I want Course Form in JAVA SWING...)Course Duration-NUMBERS
4)Course Fees-NUMBERS
I want to to add,Update,Delete...(" Save");
deletebtn=new JButton("Delete");
p1.add(l1);
p1.add(tf1);
p1.add(l2
Java-mysql coding - Java Beginners
Java-mysql coding Dear Sir,
Suppose I have Employee master file... employee joins, his master details are putted in Java-Swing Form, how I can insert in Mysql employee master table & also tell me edit & delete option also.
regards
JSP Code - Java Beginners
JSP Code can i show list of uploaded files in java then view one by one and after delete it?
thanks for support Hi Friend,
Try the following:
1)page.jsp:
Display file upload form to the user | http://www.roseindia.net/tutorialhelp/comment/22776 | CC-MAIN-2014-10 | refinedweb | 2,312 | 57.16 |
On Fri, Oct 28, 2011 at 01:41:49PM +0400, Stanislav Kinsbursky wrote:> 28.10.2011 13:30, J. Bruce Fields пишет:> >On Fri, Oct 28, 2011 at 01:24:45PM +0400, Stanislav Kinsbursky wrote:> >>This patch-set was created before you've sent your NFSd plan and we> >>disacussed Lockd per netns.> >>So, this sentence: "NFSd service will be per netns too from my pow"> >>is obsolete. And Lockd will be one for all.> >> >I believe lockd should be pert-netns--at least that's what the server> >needs.> >> >(The single lockd thread may handle requests from all netns, but it> >should behave like a different service depending on netns, so its data> >structures, etc. will need to be per-ns.> >> > Sure. Looks like we have misunderstanding here. When I said, that> Lockd should be one for all, I meaned, that we will have only one> kthread for all ns (not one per ns). Private data will be per net> ns, of course.> > BTW, Bruce, please, have a brief look at my e-mail to> linux-nfs@vger.kernel.org named "SUNRPC: non-exclusive pipe> creation".> I've done a lot in "RPC pipefs per net ns" task, and going to send> first patches soon. But right now I'm really confused will this> non-exclusive pipes creation and almost ready so remove this> functionality. But I'm afraid, that I've missed something. Would be> greatly appreciate for your opinion about my question.Sorry for the delay--it looks reasonable to me on a quick skim, but I'massuming it's Trond that will need to review this.--b.> > >--b.> >> >>Or you are asking about something else?> >>> >>>--b.> >>>> >>>>And also we have NFSd file system, which> >>>>is not virtualized yet.> >>>>> >>>>The following series consists of:> >>>>> >>>>---> >>>>> >>>>Stanislav Kinsbursky (3):> >>>> SUNRPC: move rpcbind internals to sunrpc part of network namespace context> >>>> SUNRPC: optimize net_ns dereferencing in rpcbind creation calls> >>>> SUNRPC: optimize net_ns dereferencing in rpcbind registering calls> >>>>> >>>>> >>>> net/sunrpc/netns.h | 5 ++> >>>> net/sunrpc/rpcb_clnt.c | 103 ++++++++++++++++++++++++++----------------------> >>>> 2 files changed, 61 insertions(+), 47 deletions(-)> >>>>> >>>>--> >>>>Signature> >>> >>> >>--> >>Best regards,> >>Stanislav Kinsbursky> > > -- > Best regards,> Stanislav Kinsbursky--To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | https://lkml.org/lkml/2011/11/4/308 | CC-MAIN-2015-18 | refinedweb | 381 | 73.98 |
Improving Google Maps Performance on Large Datasets
If you've ever built an app that plots data on a map, you've probably noticed that performance tends to slow down as your dataset grows larger. Zooming out too far causes thousands of map markers to display, slowing your map to a crawl, or perhaps your data is so dense that overlapping markers make even small areas hard to interact with.
In this post, I'll cover several techniques you can use to improve the performance of maps with large datasets. I'll be using Google Maps and Vue, but most of these concepts will apply to other map providers and frameworks.
To start, let's pretend we're building an application that displays a map of homes for rent across the country. First we'll create a Vue component for our map. Here's an example:
Show Code
App.js
import Vue from 'vue'; import * as VueGoogleMaps from 'vue2-google-maps'; Vue.use(VueGoogleMaps, { ... }); Vue.component('my-map', require('./components/MyMap.vue').default); const app = new Vue({ el: '#app', });
MyMap.vue
{ props: { homes: { default: [], type: Array, } }, data() { return { markers: [], map: null, }; }, computed: { google: googleMapsApi, mapReady() { return this.google && this.map !== null; } }, watch: { mapReady(value) { if(! value ) return; this.plotMarkers(); } }, methods: { plotMarkers() { if (!this.homes.length || this.markers.length) return; this.markers = this.homes.map(home => { let marker = { position: { lat: parseFloat(home.latitude), lng: parseFloat(home.longitude) }, }; return marker; }); } }, mounted() { this.$refs.googleMapRef.$mapPromise.then((map) => { this.map = map; }); }, }; </script>
Quick Note: I am using the vue2-google-maps library here which provides a great, ready to use Google Maps component. It also provides access to the
Mapinstance – both of which will be very important later. Don't worry too much about the particulars of this component. We'll be primarily focused on updating the code within our
plotMarkersmethod.
As it stands, our test data is currently returning 2,000 records that we pass into our component through its
homes prop. In the
plotMarkers method, we map over those homes, create a map marker for each, and add them to our map component.
Use Raster Images for Custom Marker Icons
This first tip comes straight from the Google Maps Platform list of best practices. Whenever you're using custom images for your markers, it's recommended to stick to raster images (
.jpg,
.jpeg,
.png) instead of Scalable Vector Graphics (
.svg). The Google Maps library provides built-in optimizations for rendering raster image markers, which will minimize any map tile rendering lag as a user pans and zooms on the map.
Taking advantage of this optimization would be beneficial for us since we're displaying thousands of homes at once.
Let's update our code to specify a custom image for our markers. To do so, we'll add an
icon property to the marker object we defined in our
plotMarkers method:
this.markers = this.homes.map(home => { let marker = { position: { lat: parseFloat(home.latitude), lng: parseFloat(home.longitude) }, + icon: { + url: '/img/house-icon.png', + }, }; return marker; });
We'll also update the
GmapMarker component to accept our icon as a prop:
<GmapMarker :
If you're using an SVG icon as the source for your raster image, here's a quick hack for maintaining the icon's crispness during conversion – save your SVG out at two times its size using a program like Sketch or Figma. After exporting, use a tool like ImageOptim to create the smallest possible lossless version of your image (using too large of an image might hurt your map's performance). Then, back in the code, you can use the
scaledSize property on the icon associated with your marker object to size your marker appropriately. For example:
icon: { + scaledSize: new this.google.maps.Size(18, 18), url: '/img/house-icon.png', },
Now that we've got that set, let's go a step further. The overcrowding of the markers makes this map unusable unless the user zooms in, but no worries! The next section outlines how we can make this better.
Group Markers Using a Clusterer
MarkerClustererPlus is a library provided by the Google Maps Platform team that we can use in combination with the Maps JavaScript API to group markers in close proximity. The clusters themselves are created and managed based on the zoom level of the map. As you zoom out, the map will consolidate the markers into these clusters that will display a number indicating how many markers it contains. Zooming in decreases the number of clusters formed, and individual markers are displayed again.
Adding the clusterer library to our map is simple. First, we need to install the package via npm:
npm i @googlemaps/markerclustererplus
Next, we can import the library in our
app.js file:
import Vue from 'vue'; import * as VueGoogleMaps from 'vue2-google-maps'; + import MarkerClusterer from '@google/markerclustererplus';
Instead of our markers being added directly to the map, we’ll initialize our clusterer object and add the markers to it inside of the
plotMarkers method. Doing so allows us to reduce the template returned from the
MyMap component down to the Google Map itself:
{ data() { + clusterer: null,); + }); }, }, } </script>
Ahhh, much better!
This particular optimization is a must for maps that display a large number of markers. Not only is it a great way to help your map's performance, but it makes the visual representation of a larger dataset less challenging to parse. You can read more about configuring when and how your clusters render in the Maps JavaScript API documentation. If you decide to use custom icons to represent clusters on the map, the same tips outlined for custom marker images will apply.
Only Plot Markers for Data Within the Current Bounds
This tip might seem obvious, but it can be easy to forget and just as easily kill performance. Our map object gives us access to a
getBounds method on the current instance that allows us to determine the visible portion of the map based on its position and zoom level. Since we'll already have access to all of the markers we defined and saved to state, we can update our call that adds the markers to our clusterer object to only include those whose current position is within the map's current bounds. Doing so will significantly reduce the amount of data added to the map on the first render.
export default { data() { clusterer: null, + currentMarkers: [],); + this.clusterer.addMarkers(this.currentMarkers = this.markers.filter(marker => + marker.getVisible() && this.map.getBounds().contains(marker.getPosition()) + )); }); }, }, }
Alternatively: Return Initial Data Within a Specified Radius
Let's switch gears and change our application's purpose to be one that displays a map of nearby homes for rent to your user based on their location. Assume that we've updated our code to retrieve the user's current location when our map component is mounted. We can post those coordinates to an endpoint in Laravel, using Axios, for example, that will only return homes within an x mile radius from the user.
To do this, let's add a
nearLocation scope to our
Home model that will take in a latitude and longitude. In this scope, we can use the MySQL distance function,
ST_Distance_Sphere, to do the heavy lifting of finding the homes to show our user. In the example below, we're restricting the homes returned to be within 100 miles of the provided location.
Logan Henson gives a great overview of the
ST_Distance_Spherefunction in this post here. I encourage you to check it out if you haven't already.
Home.php
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Builder; class Home extends Model { public function scopeNearLocation(Builder $query, $latitude, $longitude) { return $query->whereRaw(' ST_Distance_Sphere( point(longitude, latitude), point(?, ?) ) * 0.000621371192 < 100 // desired delivery max range ', [ $longitude, $latitude, ]); } }
Here's an example of a single-action controller that returns our results to the frontend:
GetNearbyHomesController.php
<? php namespace App\Http\Controllers; use App\Models\Home; class GetNearbyHomesController extends Controller { public function __invoke() { return response()->json([ 'homes' => Home::nearLocation( request('latitude'), request('longitude'), )->get(['latitude', 'longitude']), ]); } }
Note: For the best user experience, allow the user to pick the mile radius they'd like to restrict their results to and pass that into the request along with their location.
Bonus: Access Individual Markers With the Same Coordinates
While Marker Clustering provides a great solution for grouping markers in close proximity, there is no out of the box solution provided by the Google Maps API that handles interacting with markers with the same coordinates. No matter how close you zoom in, you'll always see just one marker with the others hidden beneath it. Any events registered to the markers will only apply to the topmost marker in the stack. So how can you reveal the remaining markers?
Overlapping Marker Spiderfier to the Rescue
Disclaimer: At the time of writing this post, Overlapping Marker Spiderfier has not been actively contributed to, but is a great starting point should you decide to fork it and add additional features or try your hand at contributing to the original!
Overlapping Marker Spiderfier, or OMS, is a cool open-source package that will add enhanced listeners to your map allowing overlapping markers to spring apart when the topmost marker in the stack is clicked. Luckily for us, OMS plays very nicely with the clustering we have included, too. Let's add it to our example code to see it in action.
First, we'll add a
script tag to our main view file with the link to the package file's minified version. Alternatively, you may download a compiled, minified version of the package from the OMS Github page and host the file yourself.
<script src=""></script>
Note: Feel free to pause here to read the package's documentation to see the available configuration options.
Next, we'll update our map component to set the initial values and options of our OMS object:
export default { data() { return { clusterer: null, currentMarkers: [], markers: [], map: null, + spiderfier: null, + spiderfierOptions: { + basicFormatEvents: true, + circleFootSeparation: 40, + keepSpiderfied: true, + markersWontHide: true, + markersWontMove: true, + }, }; }, }
Then we'll revisit our
plotMarkers method, create a new instance of OMS, and track each of our markers with it:
methods: { plotMarkers() { if (!this.homes.length || this.markers.length) return; + this.spiderfier = new OverlappingMarkerSpiderfier(this.map, this.spiderfierOptions); this.markers = this.homes.map((home) => { let marker = new this.google.maps.Marker({ position: { lat: parseFloat(home.latitude), lng: parseFloat(home.longitude), }, icon: { url: "/img/house-icon.png", + anchor: new this.google.maps.Point(7.5, 7.5), scaledSize: new this.google.maps.Size(18, 18), }, }); + this.spiderfier.trackMarker(marker); return marker; }); // ... }, },
Our last step here to get this working is very important. We'll return to the code that creates a new instance of our clusterer object and pass in a new option limiting the max zoom level. Without this limit, no matter how far into the map the user zooms, the cluster will always appear in cases where two or more markers are at the same point. To see OMS in action when we click the markers, we set the max zoom level so that this is not the case.
methods: { plotMarkers() { // ... this.clusterer = new MarkerClusterer(this.map, [], { imagePath: "", + maxZoom: 16, }); }, },
And there you have it! In the example below, you can see that we have a cluster of three homes in the same location.
When the cluster is clicked, the map zooms in at a level beyond where the clustering can happen, thanks to our new
maxZoom restriction. Once zoomed in, clicking the marker reveals all of the homes at that location.
Hopefully these tips have helped you improve your maps' performance. If you have questions or want to share your own mapping tips, you can find me at @nadrarvre on Twitter. | https://tighten.co/blog/improving-google-maps-performance-on-large-datasets/ | CC-MAIN-2021-21 | refinedweb | 1,968 | 53.71 |
I am aware of the KeyPreview property of a Windows Form, and this allows the Form to receive the key events before they get passed to the focused control.
However, I want the Form to receive the event after it has been to the focused control.
As a test I have placed a TextBox on a Form. Upon typing in the TextBox it should perform it's default behavior, upon pressing certain key commands. Ctrl-S, F1, etc, I want those to bubble through the TextBox up to the Form to be handled at a higher level. These commands are those that the TextBox doesn't do by default.
I do need the events to go through the TextBox first though. The application this functionality is needed in is more complex than this simple example. For example, when the TextBox is the focused control it should perform the default Copy & Paste using Ctrl-C and Ctrl-V. However, when various other controls are focused these commands need to end up at the top-most Form-level to be processed there.
Edit: It seems that input events go from Form to Focused Control and not the other way around like I was expecting. If it went from Focus to Form I probably wouldn't be having the problem I have.
Edit2: Having read (briefly) though this article: I am now assuming that the sort of 'bubbling' that I was expecting to just 'be there' is only available in WPF, and not standard C#. I think I'm going to have to re-think the way in which the users interact with my app as opposed to writing swathes of ugly code.
Big points to anyone who can reply on doing WPF-style bubbling in C# without ugly code.
You may still use KeyPreview property but check which control is focused, if it is a textbox then do nothing, else if it is another control - say RichTextBox - then handle the pressed keys. To get the currently focused control, you may need to access Win32 API. Example: Created a new Windows forms application, add a text box and a richtext box in the form, set the KeyPreview property of the form to true, add an event handler for the KeyDown event of the form, the textbox, and the richtextbox. Also the following using statement:
using System.Runtime.InteropServices;//for DllImport
then replace the code of the form by the following code:
public partial class Form1 : Form { // Import GetFocus() from user32.dll [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.Winapi)] internal static extern IntPtr GetFocus(); protected Control GetFocusControl() { Control focusControl = null; IntPtr focusHandle = GetFocus(); if (focusHandle != IntPtr.Zero) // returns null if handle is not to a .NET control focusControl = Control.FromHandle(focusHandle); return focusControl; } public Form1() { InitializeComponent(); } private void Form1_KeyDown(object sender, KeyEventArgs e) { Control focusedControl = GetFocusControl(); if (focusedControl != null && !(focusedControl is TextBox) && e.Control && e.KeyCode == Keys.C)//not a textbox and Copy { MessageBox.Show("@Form"); e.Handled = true; } } private void richTextBox1_KeyDown(object sender, KeyEventArgs e) { if(e.Control && e.KeyCode == Keys.C) MessageBox.Show("@Control"); } private void textBox1_KeyDown(object sender, KeyEventArgs e) { if (e.Control && e.KeyCode == Keys.C) MessageBox.Show("@Control"); } } | https://www.codesd.com/item/how-to-pass-key-events-from-a-control-to-a-form.html | CC-MAIN-2019-18 | refinedweb | 531 | 54.93 |
I intend on cleaning it up by doing away from the gawk abuses. I am either going to make it (Plan 9) rc based (with Plan 9 awk and some C for the networking) or perhaps Haskell. That is quite a choice, eh?
I've done a bit of Haskell over the past few months and feel strong enough to do the next generation BLOGnBOX, but the main problem is actually getting the thing going. (This is a nighttime CFT and, well, I have to get into a Haskell frame of thinking).
The first task up is a parser for mime encoded email. I plan on using regular expressions (yes, I know -- use Parsec or something more Haskell-ish). Awk is somewhat of a natural for this, but Gawk has a little more "oomph". I can visualize how I would do it in Awk, but the Haskell is not coming naturally.
Well, it isn't all that difficult to get started in Haskell:
module MailParser where
import Text.Regex
import qualified Data.Map as Map
type Header = Map.Map String [String]
header_regex = mkRegex "^(From|To|Subject)[ ]*:[ ]*(.+)"
parseHeader :: String -> Header -> Header
parseHeader s h = case matchRegex header_regex s
of Nothing -> h
Just (k:v) -> Map.insert k v h
Well, that is a beginning. Of course, I should be using ByteStrings for efficiency... and, yes... I know... I know... I should be using Parsec
/todd
1 | http://toddbot.blogspot.com/2011/03/notes-on-mail-header-and-mime-parsers.html | CC-MAIN-2019-04 | refinedweb | 235 | 75 |
In my previous posts, I described the new WinHttp proxy, tracing and client certificate configuration story for Windows Vista Beta2. The syntax of the netsh commands used to configure WinHttp proxy and tracing settings have changed for Vista RTM and this post describes the changes in command syntax since the beta.
WinHttp Netsh Context
From the previous posts you might be aware that in Windows Vista, the WinHttp proxy and tracing configuration tools, proxycfg.exe and winhttptracecfg.exe respectively, have been replaced with netsh commands. All the WinHttp related netsh commands live under the “winhttp” netsh context. To navigate to it, open an administrator command prompt and type “netsh” then “winhttp”:
C:\Windows\system32>netsh
netsh>winhttp
netsh winhttp>
You can type “?” in this context and display the list of available commands there. You can also type “?” at the end of any command to get a detailed description of the command syntax.
Displaying current settings and restoring the defaults
You can use the “show” netsh commands to display the current settings. “show proxy” will display the current proxy settings, while “show tracing” will display the current tracing settings. You can also use the “reset” netsh command to restore the default settings. “reset proxy” will set the WinHttp proxy settings to DIRECT, while “reset tracing” will disable the tracing.
Setting WinHttp proxy settings
Use the “set proxy” command to configure the proxy settings. You can type the command followed by a question mark to see the syntax:
netsh winhttp>set proxy /?″ bypass-list=”*.foo.com”
Just follow the examples listed in the samples above to set your proxy settings.
Note that importing proxy settings from IE is now accomplished by the “import” command (importing from IE is the only available option there):
netsh winhttp>import proxy /?
Usage: import proxy [source=]ie
Parameters:
Tag Value
source – from where the setting is imported
Examples:
import proxy source=ie
Setting WinHttp tracing settings
To set the WinHttp tracing settings, use the “set tracing” command from the netsh winhttp context:
netsh winhttp>set tracing /?″ level=verbose format=hex
set tracing output=debugger max-trace-file-size=512000 state=enabled
Please note that you can use the “state” parameter to disable / enable the tracing. For example, “set tracing state=disabled” will disable the tracing.
Also, your process needs to have enough permissions to create the trace file, so it is recommended to specify a folder via the “trace-file-prefix” parameter that you know your process has write access to.
-Nesho Neshev
Regards to setting up the proxy server address, so how to set up the http proxy authentication data: both the user name and the password?
HTTP proxy authencation (HTTP 407) has always been problem so far in Windows platform.
Is there any effort to unify this network setting to become ONLY in one place?
Now, I see this in WinHttp Configuration. I’ve seen this also in IE. Why would I set the same information in more than one place?
Any thoughts?
Thanks!
Thanks for the clues about netsh/winhttp !
> Why would I set the same information in more than one place?
Well, it’s a matter of win-history 🙂 You can separate your proxy settings for the "user browser" and for the "core services".
@NMI
> Well, it’s a matter of win-history 🙂 You can separate your proxy settings for the "user browser" and for the "core services".
The problem is there’s no consistency among the two. For example, for system proxy (set through proxycfg in WinXP), there’s no way you can set your authentication data (user name and password), while you can do this in IE.
The idea I’m bringing is to create a standardized system proxy manager where you can put all standardized proxy information (the address, port, user name, password, etc.). Then, a user can create many proxy configurations so that (for example):
– "core service" can choose "proxy configuration a"
– "user browser" can choose "proxy configuration b"
What do you think? Still each apps can still choose different proxies but IMHO it’s a more scalable solution. Yet, it’s more well-defined than current approach taken in Windows (even Vista; I haven’t seen WinServer 2008 yet).
Further, I’ve reported it here:
I would love to see a named entity that represents a logical collection of proxy settings (or other http/networking settings, such as autologon policy, SSL client certificate, etc.) like this. Then any client application could configure its HTTP settings by binding to a single logical name rather than hardcoding settings or having to provide its own elaborate configuration UI. It also be nice if one collection of settings could inherit defaults from another collection and refine them, rather than becoming a full copy of settings. This would help keep shared settings in one place and would improve the backwards compat story when new settings are added.
Rather than hiding everything in the registry, it would also be nice if at the time I bind to WinHTTP or create a session, I could point at a config file or just provide a blob of XML to describe an entity. But that may be too abstract for WinHTTP.
Hi!
How can I unset the proxy after executing
netsh winhttp>set proxy myproxy ?
I’ve tried the command unset proxy but I’ve an error as result.
Please advice.
Thanks in advance!
Bruce.
Bruce
The command to reset your proxy settings is
netsh winhttp reset proxy
Thanks
-Jonathan Silvera
WinHTTP Program Manager
Is there way to set or use authentication over the winhttp proxy settings? I have a scenarion where if I my proxy doesn't require authentication, the winhttp proxy settings work fine, but if the proxy does require authentication, the service doesn't send auth to the proxy. (ie. does work though)
It's almost like winhttp doesn't work in a "interactive mode" with the proxy.
Can you confirm or deny?
I wonder why the team remain silent if being asked with such question (about proxy authentication), such as the one asked by @Steve Gombotz above and me myself.
I can't hardly remember if they ever say a thing in my suggestion I've reported in Connect (I even can't see my suggestion anymore; not sure where it goes…) | https://blogs.msdn.microsoft.com/wndp/2007/03/21/winhttp-configuration-for-windows-vista/ | CC-MAIN-2016-44 | refinedweb | 1,049 | 60.85 |
Posted Oct 5, 2009
By Danny Lesandrini
If your database has a table with "person"
information, odds are it has an email column. If your users collect email
addresses, odds are they want to send emails to persons in the database and
before long, someone's going to get it into their head to send out an email
"blast" or batch.
There are several approaches to this request and over the
years, I've used them all. The easiest solution is to create a function that
returns a semi-colon delimited text string of emails and plunk in into the
recipient's field of the email created in Microsoft Outlook. This is simple to
implement and easy for users to understand, but carries with it the likelihood
that the recipient's spam filter will reject it.
What you really need is an engine to send individualized
emails, one at a time. That's the subject of this month's article, and one
solution (of many potential solutions) is in the attached download. <BulkBatchEmail.zip>
The first step is to set up some tables. It's assumed you
have a table with the person-email information. In the demo this table is
named tblContacts. To implement the demonstration code you'll have to make a
few edits, if your table is not thus named. Simply do a search in all code
modules for the word "tblContacts" and you'll see the edit points you
need to address.
In addition to your own contacts table, you'll need to
import the following tables into your MDB application:
tblEmail: Contains the email content and delimited
recipient list
tblEmailRecip: Used to display the recipients as
rows in a table
tblEmailAttachment: Lists the attachments for an
tblEmailDefault: A single row with default text to
be used with all emails
I've found that this approach has some advantages. Users
like to look back to see what messages were sent and to whom, so tblEmail
serves as a correspondence history of sorts.
The recipient list behaves as it does in other mail apps,
showing email addresses as a semi-colon delimited list, but the inclusion of
tblEmailRecip adds the flexibility of viewing the addresses as a sorted list
with a lookup to the contact's full name.
Default text may be saved in tblEmailDefault, such as an
email signature and company contact info, as well as a confidentiality
disclaimer.
The application has two forms, frmEmail and frmRecip,
which do all the heavy lifting. There are also two code modules, basFnsAPI
and basUtilities, which provide support services. Credit has been given
where code has been borrowed from websites and newsgroup postings.
Both forms are shown below and appear as one might expect an
email application to look. The creativity here is not in the cosmetic
appearance, but in the functionality, which includes the following:
1. Fast
and easy access to the Defaults table. In this example, only two defaults are
given, email signature and company address, but more could be defined and
used. Additionally, one could create a personalized row of defaults for each
user.
2. The
after-update event of the Recipient List text box takes action to clean up the
list, removing spaces and replacing commas with semi-colons.
3. Double-clicking
the recipient list opens/loads the Recipient List form with a lookup to the
contacts table. While this list is not editable, one may delete rows from the
pop-up form and see them disappear from the semi-colon delimited list in the
4. The
attachments listbox is loaded using the Add and Delete buttons to its left.
The file navigation common dialog box is implemented for this process.
Double-clicking an entry opens the attachment for viewing.
5. While
it's not obvious from the UI, the body text will be inserted as HTML. This
allows for some creativity for those who know a little about HTML tags.
6. The
most important feature is the use of placeholder tags. In the email body text box
you will see references to <name>, <email sig> and <co
address>. When the email is created, these tags will be replaced with data
that is looked up, so that the text "Dear <name>" will become
something like "Dear Lamont Cranston".
This feature is extensible, of course. We once ran a batch where user's login credentials
were inserted into 400 emails for clients who were being given access to our
new web portal. I simply added a tag with the text <site login> and
modified the code to do the appropriate lookup and substitution.
The beauty of using tags is that they may be employed, or not. If left out of
the body text, the substitution will not take place. Leave off the <co
address> and the company address will not show. Leave off the <name>
tag and you can simply begin the email with "Dear Sirs". (Do we
still start letters that way?)
7. Pre-Batch-Send
safety valve. (We'll discuss this in the next section.)
8. The
record is locked after the email(s) are sent. Though not shown here, the
controls back-color is toggled to light yellow and their contents are locked
after the request to send has been executed. This avoids the likelihood that
the email will be accidentally sent a second time.
My biggest fear in creating this user interface was that
users might click Send and then regret it for one reason or another.
Accordingly, I engineered (maybe over-engineered) a system of warnings and
stop-gaps.
Rather than just initiating the send of these merged-data
emails without previewing, I give the user the option to view them or cancel
the entire operation. They see the message shown below, and if they click Yes,
then the emails are displayed, not sent, as illustrated by the screen shot
below.
Here we can see the effect of the tags. The name tag was
replaced with real names, the email signature and company address tags also
show our defined text. Also note that the email body is in HTML format, so
where we added BOLD tags in our defaults, the text is bold.
There is quite a lot of code involved so I won't be
reproducing it all here, but if you get the download, you'll see it includes
code to perform the following functions:
The code used in the download employs Outlook Automation, as
shown in the code snippet below.
With objEmail
' refresh the local body text variable with the template value.
strBody = Replace(sBody, vbCrLf, "<br>")
' lookup the contact name ... if not found, derive from email
strSQL = "SELECT TOP 1 [FirstName] & ' ' & [LastName] AS Contact " & _
"FROM tblContacts WHERE [Email]='" & strRecip & "' "
SetRstA strSQL ' function for loading recordset named rstA
If rstA.BOF And rstA.EOF Then
strName = Left(strRecip, InStr(1, strRecip, "@") - 1)
Else
strName = Nz(rstA!Contact, Left(strRecip, InStr(1, strRecip, "@") - 1))
End If
Set rstA = Nothing
strName = StrConv(Replace(strName, ".", " "), vbProperCase)
' here is where body text tags are replaced with looked up values
strBody = Replace(strBody, "<name>", strName)
strBody = Replace(strBody, "<email sig>", "<br>" & strEmailSig)
strBody = Replace(strBody, "<co address>", "<br>" & strCoAddress)
.To = strRecip
.Subject = sSubject
.BodyFormat = 2 ' olFormatHTML = 2
.HTMLBody = strBody ' use HTMLBody, not Body property.
'.Body = strBody
.Save
' loop through listbox, adding attachments to email
For lngItem = 0 To Me!lstAttachments.ListCount - 1
strName = Nz(Me!lstAttachments.Column(1, lngItem), "")
strFile = Nz(Me!lstAttachments.Column(2, lngItem), "")
If strFile <> "" Then
.Attachments.Add strFile, 1, 1, strName
End If
' here is where we decide whether to show or send the email
If fPreviewAll Then
objEmail.display
Else
If intPreviewLimit >= cPreviewLimit Then
If fSend = True Then
objEmail.send
Else
objEmail.display
End If
Else
objEmail.display
End If
End If
intPreviewLimit = intPreviewLimit + 1
End With
As was mentioned at the outset, there are other ways to send
an email. One is to loop through your list of addresses and call the DoCmd.SendObject
that is native to Access. This will certainly work, but I don't believe I was
ever able to get it to display HTML body content the way I wanted.
Another send mail method involves CDO. This code is also
very good and not dependent upon having Microsoft Outlook configured for each
user. Below is a partial code example of how CDO might be implemented. It's a
nice alternative to Outlook automation.
Dim sch As String
Dim rrc As String
Dim rrn As String
Dim cdoConfig As Object
Dim cdoMessage As Object
sch = ""
rrn = "urn:schemas:mailheader:disposition-notification-to"
rrc = "urn:schemas:mailheader:return-receipt-to"
Set cdoConfig = CreateObject("CDO.Configuration")
With cdoConfig.Fields
.Item(sch & "sendusing") = 2 ' cdoSendUsingPort
.Item(sch & "smtpserver") = "YourMailServerNameHere"
.Item(sch & "smtpserverport") = 25
.Update
End With
Set cdoMessage = CreateObject("CDO.Message")
With cdoMessage
.Fields(rrn) = strFrom
.Fields(rrc) = strFrom
.Fields.Update
Set .Configuration = cdoConfig
.ReplyTo = strFrom
."
.To = sRecipName & " <" & sRecipEmail & ">"
.Subject = sSubject
.HTMLBody = sBody
If Dir(sAttach) <> "" And sAttach <> "" Then .AddAttachment (sAttach)
.Send
End With
Set cdoMessage = Nothing
Set cdoConfig = Nothing
SendEMailCDO = Err.Number
If you implement this email form, the next thing you'll
likely be asked to do is to provide an interface for loading a list of emails.
This demo application doesn't include such a device but the screen-shot that
follows shows one I had built for one of my clients.
For this client, the key to selecting email addresses was
the category they were assigned to. I also supplied a text box for a cut-off
date, to exclude really old records. The list box updates automatically when
the category is selected or a date edited.
The Load Emails button does nothing except loop through the entries
creating a semi-colon delimited text string of email addresses, and then plunks
it into the Recipients text box on the email form. It's handy, but a very
custom job.
As long as emails are with us, the need for sending out
batches of them will be too. This feature has been embedded into most of my
applications. I have found it to be invaluable and I suspect you will too.
»
See All Articles by Columnist Danny J. Lesandrini
MS Access Archives
Please enable Javascript in your browser, before you post the comment! Now Javascript is disabled.
Your name/nickname
Your email
Subject
(Maximum characters: 1200). You have characters left. | http://www.databasejournal.com/features/msaccess/article.php/3841991/Bulk-Batch-Email-From-Microsoft-Access.htm | CC-MAIN-2015-06 | refinedweb | 1,727 | 64.3 |
If your application needs to perform frequent background task execution then creating a new thread every time can be very CPU intensive. The solution here is to use a pool of threads and keep using them.
In iOS, Grand Central Dispatch gives you thread pooling. The system maintains a separate pool for different priorities. Most of the time you will need to use the pool with default priority. Example code:
- (void) someEventHandler { dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ @autoreleasepool { NSLog(@"Starting short background work"); //... } }); }
Don’t forget to create a new auto release pool for the task.
In Android, use the concurrency API (instead of AsyncTask which creates a new thread every time. Edit: Well, this is not true. Please read a latter post). For example:
public class MainActivity extends Activity { ExecutorService threadPool; public void onCreate(Bundle state) { threadPool = Executors.newCachedThreadPool(); } void someEventHandler() { threadPool.execute(new Runnable() { public void run() { //Start short background work } }); } }
Advertisements
One thought on “Background Execution in a Thread Pool” | https://mobiarch.wordpress.com/2012/06/04/background-execution-in-a-thread-pool/ | CC-MAIN-2018-13 | refinedweb | 162 | 50.94 |
I have this sample from my project and I need to know why the result is what it is.
public class Main
{
public static void main(String[] args)
{
//url:, websiteList:, URL Contains Returns bool: false
String url = "";
String contains = "";
System.out.println("Returns bool: " + url.contains(contains));
}
}
Returns bool: false
Code is always doing what you ask it to do:
String url = "-
but
String contains = "";
https versus http!
So the real answer is: especially when you are a beginner, chances that your code uncovered "some Java bug" is relatively small (very close to zero in reality!)
There is a much higher chance that your assumptions are wrong. You either don't fully understand the methods you are calling, or there is a subtle flaw in your input data.
Finally: also work on your naming. contains isn't a very good name here; you better call it expectedUrl, or something alike! | https://codedump.io/share/sv18YUYqz7h8/1/boolean-not-returning-as-expected-in-stringcontains | CC-MAIN-2017-47 | refinedweb | 150 | 63.9 |
.
The Output cell size can be defined by a numeric value or obtained from an existing raster dataset. If the cell size hasn’t been explicitly specified as the parameter value, it is derived from the environment Cell Size, if it has been specified. If, it will be projected based on the selected Cell Size Projection Method.
This tool always uses the cell center to decide the value of a raster pixel. If more control is needed.FeatureToRaster(in_features, field, out_raster, {cell_size})
Code sample
Converts features to a raster dataset.
import arcpy from arcpy import env env.workspace = "c:/data" arcpy.FeatureToRaster_conversion("roads.shp", "CLASS", "c:/output/roadsgrid", 25)
- Basic: Yes
- Standard: Yes
- Advanced: Yes | https://pro.arcgis.com/en/pro-app/latest/tool-reference/conversion/feature-to-raster.htm | CC-MAIN-2022-05 | refinedweb | 115 | 51.14 |
I have searched the recent archives and I haven't seen anyone else with this
problem. I therefore assume I have done something stupid. This is my first
attempt at mod_python and I am new to python as well.
Background:
Python 2.2 , configured --with-threads=no
mod_python 2.7.6
Apache 1.3.22-2 , (rpm)
Apache-devel 1.3.22-2 , (rpm) for apxs
My configure line looks like this:
./configure --with-apxs=/usr/sbin/apxs --with-python=/root/tar/Python-2.2
no errors here.
I do a make and get no errors.
On make install I get this:
python /usr/local/lib/python2.2/compileall.py
/usr/local/lib/python2.2/site-packages/mod_python
Traceback (innermost last):
File "/usr/local/lib/python2.2/compileall.py", line 147, in ?
exit_status = not main()
File "/usr/local/lib/python2.2/compileall.py", line 104, in main
import getopt
File "/usr/local/lib/python2.2/getopt.py", line 101
possibilities = [o for o in longopts if o.startswith(opt)]
^
SyntaxError: invalid syntax
make[2]: *** [install_py_lib] Error 1
make[2]: Leaving directory `/root/tar/mod_python-2.7.6'
make[1]: *** [install_dso] Error 2
make[1]: Leaving directory `/root/tar/mod_python-2.7.6'
make: *** [install] Error 2
Does anyone have a clue as to what I have (or have not) done?
It says syntax error but no-one else seems to be having difficulty. Any help
is greatly appreciated.
--
Lewis Bergman
Texas Communications
4309 Maple St.
Abilene, TX 79602-8044
915-695-6962 ext 115 | https://modpython.org/pipermail/mod_python/2002-January/012347.html | CC-MAIN-2022-21 | refinedweb | 254 | 63.86 |
CGTalk
>
Software Specific Forums
>
Autodesk Mudbox
> import from maya - get very big brushsize!
PDA
View Full Version :
import from maya - get very big brushsize!
Geuse
05-04-2007, 12:57 AM
When I import objects in mudbox from maya the brushsize in mudbox have to be set at 0.1 to get a size you can work with. I tried to scale up my object with a factor of 10 in maya (I work in cm) and that made it more suitable once in mudbox, but then my maya object is 10 times bigger than I want. What is the right approach to do this. Can you change the settings of the brushsize in mudbox or scale up your model?
PenguinVisuals
05-04-2007, 01:45 AM
Easiest to scale proportionly in Maya when you export/import. Don't think you can scale objects in mud box.
Geuse
05-04-2007, 08:55 AM
But how do you know what scale it should be?
How do you guys do?
brassi
05-04-2007, 10:30 AM
simply i scale my model 5 times in maya.freeze transform then export it(this is my magical number though.it suits my needs in mudbox).
when import back to maya scale your model down 1/5. but the trick is, in the displacement maps alpha gain you have to put this scale factor also. 1/5=0,2.
this should work
cheers.
Geuse
05-04-2007, 11:18 AM
Thanx alot. So there is no magical trick to it, gotcha!
What units do you work in?
PenguinVisuals
05-05-2007, 07:13 AM
Normally I work in CM. the models always turn out really huge because I try to follow real life scale. A character will be around 170CM height for example. Unless I'm trying to match the unit with game engines.
Geuse
05-06-2007, 08:51 PM
thank you very much for your response! I Appreciate it!
CGTalk Moderation
05-06-2007, 08. | http://forums.cgsociety.org/archive/index.php/t-492540.html | CC-MAIN-2015-18 | refinedweb | 333 | 85.59 |
In this article I am demonstrating the new features in C# 3.0. This demo is created as a simple C# console application to understand the new features of C# 3.0.
I am a regular participant of Microsoft web casts and developer conferences. These web casts gives me a better understanding of new technologies. Also I was able to implement all these successfully in my projects. This article helps you understanding what are the new language features of C# 3.0
Ok... Here we go…
If you don't have licenced Visual Studio 2008 installed on your machine, I would suggest you to download and inslall Visual Studio 2008 Express Edition ( Free).
This sample demo application starts with creating an Employee class. This has few properties in it. I would suggest you start doing it while going through this article.
public class Employees
{
#region AUTO IMPLEMENTED PROPERTIES
//C# 3.0 - Auto implemented properties.
public string EmployeeName { get; set; }
public int EmployeeID { get; set; }
public string Department { get; set; }
#endregion
}
Here I have inroduced a language feature called Auto Implemented properies. You can notice that there is no private fields been declared for these properties. The compiler will creates the private backing fields for you.
Now we have created our Employee class. Lets create our main Program class now.
Program
public class Program
{
static void Main(string[] args)
{
List<Employees> employees = LoadEmployees();
}
}
In the program main method, I have declared a List of Employees. I am using the method LoadEmployees to get the Employee list. Normally in C#2.0 we will use the following code to create an Employee object and will add to the List.
LoadEmployees
// In C# 2.0
private static List<employees /> LoadEmployees()
{
Employees emp1 = new Employees();
}
Here we need to set the values to the properies using the Employee objects emp1. ie For example emp1.EmployeeName = "Albert"; Finally we will add the employee objects to an Employee List.
emp1
emp1.EmployeeName = "Albert";
Now we will see the magic of C# 3.0
private static List<Employees> LoadEmployees()
{
// C# 3.0 Collection Initializers
List<Employees> employees = new List<Employees>()
{
// C# 3.0 Object Initializers.
new Employees{ EmployeeName="Albert", EmployeeID=1234,
Department="Software Testing"},
new Employees{EmployeeName="Justin", EmployeeID=1234,
Department="Development"}
};
}
Here I have introduced a new language feature called Object Initializers and Collection Initializers.
One more change…
Please note this line
List<Employees> employees = new List<Employees>() { ....
You can see the repetition of List<Employees>. The type of List<Employees> is mentioned twise. Lets see how can we avoid this in C# 3.0
List<Employees>.
List<Employees>
I am rewriring the above line as
var employees = new List<Employees>() { ....
Ohh..whats that!..This is called Local variable Type Inference.
Don’t worry it will not break our type safety. You cannot assign any other types to employees as the compiler strongly typed the employees as the type assigned in its right side.
Ok…Now we can see different ways of querying this list of Employees using the LINQ feature of C# 3.0 We will go back to or Main method.
# 1.
static void Main(string[] args)
{
List<Employees> employees = LoadEmployees();
// C# 3.0 Lambda Expressions -- Where is an Extension method of Enumerable class
var results = Enumerable.Where(employees, e => e.Department == "Development");
}
C# 3.0 introduced a new class called Enumerable with some methods. This can be used on any IEnumerable types. Here I am using a method called Where. This method filters the collection by using some predicates. This predicates are created inline using another language feature known as “Lambda Expressions”. This simplifies the syntax of anonymous methods which we used in C# 2.0. This returns a list of Employees whose department is “Development”.
Enumerable
# 2
The Where method can be used as an extension method on the employees object. Yet another feature of C# 3.0 which we will cover later in this article.
static void Main(string[] args)
{
List<Employees> employees = LoadEmployees();
// C# 3.0 Lambda Expressions -- Where is an Extension method of Enumerable class
var results = employees.Where(e => e.Department == "Development");
}
# 3.
One more improvement on this. Ie called a query expressions. I am re-writing the above code as
static void Main(string[] args)
{
List<Employees> employees = LoadEmployees();
var query = from e in employees
where
e.Department == "Development"
select e;
}
I am not covering all the capabilities of LINQ here. We can use this query expressions to query against databases, XMLs, objects or any types of data that a third party can extend to work with LINQ. Lets try to print this result in a console.
foreach (var item in query)
{
Console.WriteLine("{0},{1},{2}", item.EmployeeName, item.EmployeeID,
item.Department);
}
Finally… we will see another feature called Extension Methods
Ok..What is Extension methods?
Extension methods are static method that can be invoked using the instance method syntax.
How can add an extension method?
namespace ExtensionMethodDemos
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public static class SampleStringExtensionClass
{
public static string SayHello(this string s)
{
return "Hello" + s;
}
}
}
Here I have a static class which has static method named SayHello.
Extension methods are defined as static methods but are called by using instance method syntax.
Note that the parameter to the extension method that is prefixed with the "this" keyword - this tells the compiler which type we are "extending" with our extension method.
Ok.. Let see how we can use in our code. I will take the same main program we used above.
namespace CSharp3._0Features
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExtensionMethodDemos;
public class Program
{
static void Main(string[] args)
{
string sampleString = " Albert";
string strExtended = sampleString.SayHello();
Console.WriteLine();
Console.WriteLine("****EXTENSION METHODS*******");
Console.WriteLine(strExtended);
Console.ReadLine();
}
}
}
Note that I have used the namespace ExtensionMethodDemos whch we created earlier. I have created a variable of string type. This new string type is now having the method “SayHello()” as its extension method.
ExtensionMethodDemos
If you do implement extension methods for a given type, remember the following two points:
Extensions
using Extensions
Reference: Microsoft MSDN, Microsoft MSDN Web. | https://www.codeproject.com:443/Articles/34774/New-features-of-C-3-0?display=Print&PageFlow=FixedWidth | CC-MAIN-2022-40 | refinedweb | 1,025 | 51.75 |
I recently came across a key feature of object-oriented programming that has been implemented in some programming languages and is commonly known as function overloading or method overloading.
In a nutshell, it allows defining multiple functions or methods with the same name but different implementations.
It could come quite handy in situations where a method may take in different configurations of arguments and return a different type in each case.
What’s even more interesting about function overloading is that while it is considered illegal in many programming languages like Python and PHP, others like C++, C#, Java, Swift, and Kotlin have it built-in.
I found out about polymorphism and function overloading in a Java course through a multiple-choice question.
Here’s the example they used:
public class Zap { static boolean zap() { return true; } static int zap(boolean x) { return 0; } static double zap(int x) { return 0.5; } static String zap(double x) { return "Zap!"; } static boolean zap(String x) { return false; } public static void main(String[] args) { System.out.println(zap(zap(zap(zap(1))))); } }
What do you think is the output?
a. true
b. 0
c. 0.5
d. Zap!
e. false
With the help of a debugger we can trace our nested method calls:
Java determines which method definitions to use for each method call based on the type of the actual argument.
The inner-most zap takes in an integer, so Java will choose the third method definition. It returns type Double and therefore the next zap is going to use the fourth method definition, and so on.
This post was originally published on my blog where I write all about tech.
Top comments (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/themreza/function-overloading-47kc | CC-MAIN-2022-40 | refinedweb | 283 | 60.85 |
Post your Comment
CSV tables
CSV tables hello,
What are CSV tables?
hii,
CSV Tables cannot be indexed.CSV Tables are the special tables, data for which is saved into comma-separated values files
storing csv into oracle database
storing csv into oracle database i want jsp code for storing csv file into oracle database
HTML Form data into .CSV?
HTML Form data into .CSV? how to store data from html form to csvfile in java... q is request parameter .425 Bingeman Centre Drive is address.e. rows and columns
how to convert .xml file to csv file
how to convert .xml file to csv file how to convert .xml file to csv file
How create csv format in jsf ?
How create csv format in jsf ? Dear Friends , Good morning to all of you?
I have a problem to create .CSV format in jsf. Actully I have... the pdf file now I want to create .csv format using this data ?
Please Help me
java code to convet to CSV
How to load Arabic csv to MYSQL
How to load Arabic csv to MYSQL I tried the following
set session collation_database=utf8_general_ci;
set session character_set_database=utf8... as "?????? ????????????????".
I am sure that the csv file is encoded to utf8
Java Write To File CSV
Java Write To File CSV
In this tutorial you will learn how to write to file csv
CSV (Comma Separated Value) files stores the value in rows and columns that
is in a tabular form. In java to create a csv file is simple, you would require
reading a csv file from a particular row
reading a csv file from a particular row how to read a csv file from a particular row and storing data to sql server by using jsp servlet
extracting column and sorting csv data alphabetically
extracting column and sorting csv data alphabetically hi
here is my code and csv data save it as country.csv file
*Australia;AU;1.5
Thaialnd;TH...*
public class Csv {
public static void main(String[] args) throws Exception
how to export the query result in SQL Server to .csv file?
how to export the query result in SQL Server to .csv file? how to write table data into CSV file using SQL SERVER 2008
Export Data into CSV file uing JDBC in JSP
Export Data into CSV file uing JDBC in JSP
CSV file : A CSV file is commonly known... : 3.Create a Page ("CsvJdbcFile.jsp") to export data into CSV
SQL Bulk Insert csv
SQL Bulk Insert csv
... to the same
format table in a Mysql database.
Understand with Example
The Tutorial covers an example from 'SQL Bulk Insert CSV'.To understand
and grasp this example
Post your Comment | http://www.roseindia.net/discussion/23616-Mysql-CSV.html | CC-MAIN-2016-07 | refinedweb | 452 | 65.12 |
The Falcon Programming Language is a typeless language born for rapid development, prototyping, and ready-made integration. We may also describe Falcon as a "scripting" language with features that enable the programmer to create even complex multi-threaded applications. It mixes several different programming paradigms into an unique blend of constructs, overcoming the limitations and partialities of other languages.
The objective of this brief article is to be very practical with code examples as well as step by step simple instructions. I won't reprise the historical and technical details that led us to developing this new programming language. Please feel free to visit the main Falcon Programming Language site for plenty of details.
The Falcon p. l. presents multiple programming paradigms with a unique blend of interconnected concepts. Procedural, functional, both prototype and class based-object oriented, message oriented and tabular programming. Each of these extending into the others gives you the freedom to choose the perfect blend to represent the problem at hand. Falcon allows you, the programmer and the real human, to overcome the limitations of many programming languages that force you to restrict your thinking. Falcon allows you to just follow the flow of your thoughts. "Apply Mind over matter" is the motto for Falcon. It is not the programmer's mind that must reduce down to the simplified representation of the design, forced by single-minded programming languages, regardless of how mathematically elegant those representations may be. It is the language that must cope with the complexities of a non-linear thought. Falcon gives human thought the means to express itself via the computer paradigm. We feel that Falcon may be the cure for the common computer.
The Basics
Falcon has native strings, numbers, arrays and dictionaries. Falcon has a set of single line and block (multi line) imperative statements. Since version 0.8.12, Falcon provides an experimental interactive mode, useful for fast tests and for learning the expressions in this new language. We can jump right in with a tutorial with the command "falcon -i". You are now in interactive mode where the following code can be entered:
array = ["Have", "a", "nice", "day"] // (1) for elem in array // (2) >> elem // (3) formiddle // (4) >> " " end forlast > "!" // (5) end end
Here is what you will see on the command line of your OS (Solaris is used in this example):
bash-3.2$ falcon -i Falcon compiler and interpreter. Version 0.8.14.2 (Vulture) Welcome to Falcon interactive mode. Write statements directly at the prompt; when finished press CTRL+D to exit >>> >>> array = ["Have", "a", "nice", "day"] : Array >>> for elem in array ... >> elem ... formiddle ... >> " " ... end ... forlast ... > "!" ... end ... end Have a nice day! >>>
We have just created an array of strings in line (1). Then we iterate (2) over the list taking one element at a time and printing on the standard output (3). The double greater-than symbol ">>" prints the given item to the standard output; the single ">" will add also a new-line.
The for/in block is divided into four regions, three of which are optional; the forfirst area (executed when the loop is started and just once), the main area (always executed), the formiddle area (executed after the main area for all the elements except the last) and the forlast area (executed after the main area for the last element has completed).
All Falcon block statements can be shortened in case they contain just one statement through the ":" symbol. So, we may re-write the above loop in a more compact way (and adding a forfirst block) :
for elem in array forfirst: >> "Contents of the array: " >> elem formiddle: >> " " forlast: > "!" end
Here is what you will see on the command line of your OS (Solaris again):
bash-3.2$ falcon -i Falcon compiler and interpreter. Version 0.8.14.2 (Vulture) Welcome to Falcon interactive mode. Write statements directly at the prompt; when finished press CTRL+D to exit >>> array = ["Have", "a", "nice", "day"] : Array >>> for elem in array ... forfirst: >> "Contents of the array: " ... >> elem ... formiddle: >> " " ... forlast: > "!" ... end Contents of the array: Have a nice day! >>>
As in the vast majority of modern languages, functions can be called by applying parenthesis to a symbol; print and printl are two functions equivalent to ">>" and ">", fast-print operators respectively, we can write:
for elem in array forfirst: print( "Contents of the array: " ) print(elem) formiddle: print( " " ) forlast: printl( "!" ) end
But a very important working principle of Falcon is that computational units (functions) are actually expressions; as such, we can be a bit fancy and pick the best function to employ as the result of an expression:
for i in [ 0 : array.len() ] // (1) /* A bit naive, but this is just a sample */ if i == array.len() - 1 // (2) separator = "!" else separator = " " end // (3) ( i != array.len()-1 ? print : printl ) \ ( array[i], separator ) end
In (1), the code performs a loop in a "range", declared as [n:m]; the i variable gets the values between n and m-1 ( one less than m ). In (2) there is a simple "if" statement in which we assign a space or a terminal character to the variable "separator". This simply depends on the value of "i" in this loop and clearly we are looking for the last element in the array. Then, we see the principle at work in (3). The ternary if, <a> ? <b> : <c> expression can either resolve in the "print" (if i is not array.len() ) or
printl value, which is immediately called with two parameters: the i-th element in the array and the separator. Both functions print all the parameters they receive, and so we see another important principle of Falcon: computational units can be called with an arbitrary number of parameters. Parameter binding is resolved (efficiently) at runtime, and many functions are prepared to receive different parameter sequences.
Falcon also has a wide set of "standard" statements:
- the "while" loop,
- if-elif-else,
- break/continue statements in loops,
- a powerful "switch/case" statement
- and many more ...
We are skipping them right now, as they do nothing unexpected or extraordinary (well, not quite; many, as the "continue dropping" statement, have received some power ups in Falcon). We'll see some of the most interesting and peculiar statements as we continue the exposition of the conceptual Falcon framework.
Callables & bindings
A less formal, but convenient, term to refer to "computational units" in Falcon is Callable. Falcon callables can be divided in two classes: direct and indirect. The first ones are items referring directly to computational units; the second are callables storing parameters. For example:
printl( "Hello", " ", "world" ) //(1) fcall = [printl, "Hello", " ", "world"] fcall() //(2)
The call in (1) is direct, while printl is called indirectly with its parameters in (2).
As you can imagine, an array declaration is also an expression and as we can call expressions we can easily print our "hello world" thus (from the interactive shell):
>>> [printl, "Hello", " "]( "world" ) Hello world
The "Have a nice day!" loop can compose the sequence to be called and then call it. Here we can see this in action on a Solaris machine with the Falcon package from [Blastwave.org] ()
bash-3.2$ falcon -i Falcon compiler and interpreter. Version 0.8.14.2 (Vulture) Welcome to Falcon interactive mode. Write statements directly at the prompt; when finished press CTRL+D to exit >>> array = ["Have", "a", "nice", "day"] : Array >>> fcall = [ print, nil, " " ] : Array >>> for i in [ 0 : array.len() ] ... if i == array.len()-1 ... fcall[0] = printl //(1) ... fcall[2] = "!" ... end ... ... fcall[1] = array[i] //(2) ... fcall() ... end Have a nice day! >>>
The program uses the default call modifying the central element (2), but in the last loop it also changes the surroundings. However, in complex expressions it may be hard to track the index of a call that must be changed. In fact, array elements can also be known by name, through the late bindings:
array = ["Have", "a", "nice", "day"] fcall = [ print, &word, &separator ] // (1) // prepare the default fcall.separator = " " // (2) for i in [ 0 : array.len() ] if i == array.len()-1 fcall[0] = printl fcall.separator = "!" end fcall.word = array[i] fcall() end
The
& operator (1) creates a late binding, which can be assigned a dynamic value via the
. dot accessor (2). Late bindings are language items, and can be assigned dynamically, and the dot accessor does not need to be applied on an already existing binding. The following code works on a different principle, switching in the desired binding at the right time.
fcall = .[ printl "I am " nil ] //(1) fcall.happy = "happy :-) !" fcall.sad = "sad... :-(" for count in [0:5] fcall[2] = random( &happy, &sad ) //(2) fcall() end
With a test run:
I am happy :-) ! I am happy :-) ! I am sad... :-( I am sad... :-( I am sad... :-(
In (1) notice the
.[ comma-less array declaration; it works exactly as the other declarations seen so far, but tells the compiler that commas around elements are optional. The random function (2) selects (randomly) one of the late bindings matching the name of a previously assigned value. In fact, there is also a function called lbind() which creates a late binding by name; so (2) is equivalent to:
fcall[2] = lbind( random( "happy", "sad" ) )
String indirects and expansions
Composing dynamically late binding names is quite a powerful feature. It is similar to the ability to compose dynamically arbitrary symbol names with the indirect operator
#; see an example from the interactive
compiler:
>>> data = [ "cross", "head" ] : Array >>> for count in [0:5] ... d = # random( "data[0]", "data[1]" ) //(1) ... printl( "Launch " + count + ": ", d ) //(2) ... end Launch 0: head Launch 1: cross Launch 2: head Launch 3: cross Launch 4: cross >>>
The
# indirect expansion operator can be applied directly to symbols, array accessors as in (1), dot accessors or any arbitrary sequence of symbols, square and dot accessors. So, the effect of (1) is that of evaluating either the element 0 or 1 in the symbol called "data" and returning it into d.
The same expansions are available inline to strings via the "@" string expansion operator. We can rewrite (2) in a more comprehensible form, which expands the elements following the dollar marker "$" into their value:
> @ "Launch $(count): $d"
You'll remember the fast print operator (">") from the first example. The parenthesis around
count are necessary to disambiguate the surroundings (the colon has a special meaning), and are optional. We can therefore rewrite the above program thus:
data = [ "cross", "head" ] for count in [0:5] id = random( 0, 1 ) > @@ "Launch $(count): $$(data[ $id ])" //(1) end
What is happening here? -- In (1), the first application of
@ expands the items prefixed with a single dollar sign into their current local value, substitutes
$$ into
$ and returns the composed string. Now we have something like
Launch 0: $(data[1]), which is expanded again by the other
@.
Notice also that string expansion can also apply string formatting on the fly. Let us therefore change (1) with the following code:
> @@ "Launch $(count): $$(data[ $id ]:r6)"
that is, adding ":r6" inside the last parenthesis pair, Falcon applies the "r6" format to the expanded string. This means to right justify the expanded string in a fixed field size of 6 characters, like in the following sample run:
Launch 0: head Launch 1: cross Launch 2: head Launch 3: cross Launch 4: head
As a final statement, format codes are managed by the Format class, which can work similarly to the formatter classes in the Java SDK.
Defining functions
Falcon has many ways to define a function. A procedural-like approach is the "function" block statement:
function hail( name ) > "Hello ", name, "!" end
See an example run in the command line interpreter:
>>> function hail( name ) ... > "Hello ", name, "!" ... end >>> for name in .[ 'Tom' 'Ed' 'Sam' ]: hail(name) Hello Tom! Hello Ed! Hello Sam! >>>
Notice the combination of
.[ comma-less declaration and the usage of single quotes. In fact,
double quotes strings are merged when they are separated only by white spaces or newlines, so
.[ "Tom" "Ed" "Sam" ]
and
.[ "TomEdSam" ]
are the same. To separate strings it's also possible to use the dot-string notation
.", or use the comma to separate elements, or to use the international string marker
i". This feature make it possible to internationalize programs easily through an integrated translation tool.
We know that every function can be called with a variable set of parameters, regardless of its declaration. Thus:
function hail( name, age ) if age == nil > "Hello ", name, "!" elif age > 0 and age < 12 //(1) > "Hi little ", name, "!" elif age <= 18 > "Yo ", name, "!" elif age <= 150 > "Good morning, Mr. ", name ,"." else > "Ehm, you don't have a proper age." end end // Let's call this function with two parameters... for name, age in .[ .['Ed' 10] .['Sam' 15] .['Smith', 30] ] //(2) hail( name, age ) end // and also call it with just one parameter hail( "Mark" ) //(3)
Notice in (2) that the for/in loop can also expand multiple variables, provided that the elements in the lists have all the same number of elements (as in this case). Also, see in (1) that the
> sign is normally used to compare the value of items, and the
and operator binds logic expressions. In fact
> is considered a fast print only if found at the beginning of a line.
In (3) the function
hail is called with just one parameter, and Falcon doesn't complain; instead, it sets "age" to nil and proceeds. The program can determine this fact and take proper actions.
The function keyword can be used to declare globally-visible functions only at top level, but as expected from a functional language, it is also possible to define functions on the fly, and then consider them to be expressions. As expressions, we can assign them to variables. We can use them as parameters for other functions or call them directly.
There are three ways to create functions locally (and possibly nested). Lambda expressions are parametric expressions, which can be seen as one-expression-only functions. They work like this:
inspect( map( lambda x => x * 2, .[ 2 3 4 5 ] ) )
The
lambda x => x * 2 expression says that our parametric expression receives one parameter and returns it times 2. The
map function takes the computational unit passed as first parameter and creates an array by applying it to all the items in the array it receives as second parameter. The
inspect() function is a useful debug function traversing and displaying the contents of deep items.
A lengthy list of functions within Falcon may be seen at:
Out of curiosity, you may see a lambda in action by itself (from the interactive interpreter):
>>> (lambda x,y => x*y)(2, 3) : 6 >>> mul = lambda x, y => x * y : Function _lambda#_id_2 >>> mul( 4, 5 ) : 20
The function keyword followed directly by parameter declaration can be used to create a more complex callable:
>>> absmul = function( x, y ) ... n = x * y ... if n < 0: return -n ... return n ... end : Function _lambda#_id_8 >>> absmul( 2, 3 ) : 6 >>> absmul( 2, -3 ) : 6 >>>
The "innerfunc" keyword works as nameless function, but it doesn't perform a closure. This means that lambda expressions and nameless functions can remember the variables set by their parent and use them later on (this is called closure), while innerfunc grants a complete local variable scope protection. In the following example we create a multiplier function by closing the parameter in the parent creating it:
>>> function makeMultiplier( value ) ... return lambda x => x * value ... end >>> multBy2 = makeMultiplier( 2 ) : Array >>> divBy2 = makeMultiplier( 0.5 ) : Array >>> multBy2(2) : 4 >>> divBy2(2) : 1
This happens because the returned lambda remembers the
value variable. The
function keyword does that also:
>>> function rememberMe( value ) ... return function( prompt ) ... if prompt ... return prompt + " " + value //(1) ... end ... return value ... end ... end >>> func = rememberMe( "Hello" ) : Array >>> func() : Hello >>> func( "::::" ) //(2) : :::: Hello
In (1) we check if
prompt is a true value; the
nil value is always considered false, so we'll return a string with a prompt prefixed with the closed "value" variable only if prompt is not
nil, as in (2).
It may be interesting to inspect the contents of
func now; calling
inspect( func ), you'll see that the item is actually an array composed of the actual code and its closed parameters:
Array[2]{ Function _lambda#_id_15 "Hello" }
When the Falcon compiler finds a closure it creates a prepended ghost parameter and stores the actual value of the closed variable in an array that can then be treated and called as a normal function. However, if we need to, we can still access the closed variables and change them:
func[1] = "Hello again" func()
Talking about closure, let me just write a note on Falcon scoping. Global variables are normally accessible by every level of the program. Local variables are visible only in functions declaring them (and in their immediate nested children lambda and functions) while innerfunc declaration provides full isolation and local scoping:
val = "A global value" function test() > val //(1) k = 1 return innerfunc( k ) > k * 2 //(2) end end f = test() f( 2 ) //(3)
In (1) we get the value of the global variable, (2) will use its own version of "k" rather than using the owner local variable through closure, and (3) will just print 4.
However, assigning a variable in any scope declares the variable as local of that scope. To alter the value of a global variable, or to read it in a place where the variable has still not been assigned, the global keyword can be used:
function test() global val val = "Set by test()" end test() > val //(1)
As can be seen in (1), we're using a global variable created from inside test().
Call conventions
Talking about functions, Falcon has three primary calling conventions. They are named parameters, pass-by-reference and variable parameter conventions.
Suppose we have a function inspecting its parameters:
function whatParams( alpha, beta, gamma ) > "Alpha was: ", alpha > "Beta was : ", beta > "Gamma was: ", gamma end
To send only beta, we may nil alpha:
whatParams( nil, "Hello" )
Or we may tell exactly what to send:
whatParams( beta|"Hello" )
The "|" pipe operator creates a "future binding", which is an object similar to a late binding (remember "&<symbol>"?), but having a value that may be used "in the future". This "future", in function calls, are the actual parameters. In fact, we may even create dynamic future bindings with the
lbind() function (passing a second parameter), and/or store the future binding in a variable for later usage. For example:
alphaFuture = alpha | "The future value of alpha" whatParams( beta | "Hello", lbind( "gamma", "Gamma value" ), alphaFuture )
We see the future binding value (which can be any expression) assigned to an item (alphaFuture) and then generated through the "lbind" function.
Named and unnamed parameters can be mixed in the same call. In this case, unnamed parameters will fill the available parameters and after that all the parameters are assigned, the named parameters are taken and applied. So, the result of the following test:
whatParams( "will go in alpha", gamma | "Gamma value", "will go in beta" )
would be:
Alpha was: will go in alpha Beta was : will go in beta Gamma was: Gamma value
As you can guess, since future bindings are themselves Falcon items, they can be cached in array calls and mixed with normal parameters:
.[ whatParams beta|"in beta" gamma|"in gamma" ]()
Notice that lists in round and square parenthesis can be broken on multiple lines.
Falcon supports also pass-by-reference protocol. In other words, it is possible to let the called function modify the incoming value, returning something else in "output parameters". As with many other things, this is done in Falcon via a special binding called Item alias or reference.
In the following code, typed directly in the interactive interpreter, we modify the
b variable, and see what happens to
a:
>>> a = "Value" : Value >>> b = $a //(1) : Value >>> b = "New value" //(2) : New value >>> > @ "We have a => \"$a\" and b => \"$b\"" We have a => "New value" and b => "New value"
In (1), the alias value to
a is created and stored into
b. Now, the assignment in (2) acts as if
a was directly assigned; in fact we see that "a" is now changed, and both
a and
b can be used to change the same value. Along this principle:
>>> //(1) >>> function mul2(x,y,result);result = x*y;end >>> value = nil : Nil >>> mul2( 2, 4, $value ) >>> > value 8
Notice the ";" separating statements that should go on different lines in (1).
We already scratched variable parameter convention. It is possible to access directly the parameters passed to a function via a set of functions, the most important of which are parameter() and paramCount().
function varCall() for i in [0 : paramCount()] > i, ": ", parameter( i ) end end varCall( "one parameter" ) varCall( "one parameter", "two parameters" ) varCall( "one parameter", "two parameters", "three parameters" )
Static function data
Function local variables are normally reset each time the function is called but each function may have a "static" block; this block is executed only once, that is, the first time the function is called and all the local variables declared in the static block retain their values between calls. For example:
>>> function counter() ... static ... > "Counter initialized!" ... c = 0 ... end ... return c++ ... end >>> > "First call: ", counter() First call: Counter initialized! 0 >>> > "Second call: ", counter() Second call: 1 >>> > "Third call: ", counter() Third call: 2
The falcon VM has support for serialization and restore of function items; when serialized, the value of their static data are safely stored and re-created so it's possible to preserve the state of the program across different sessions.
Object oriented programming
Enough of functions for now (we'll see more in functional programming). Let's talk now of that very funny thing that is the
object.member notation that is so glamorous as to have conquered the vast majority of many programming language market areas.
Falcon allows both for class/type based object-oriented programming and prototype-oriented programming; that is, you can both create classes, derive from them, do interface-like inheritance, have private members, and the kind of things you usually expect in strongly typed object-oriented languages on one hand; and on the other, have loose objects created out of the blue, with shifting and changing members. Even more, we'll see how tabular programming integrates and extends OOP into something quite new.
Basically, classes are a collection of properties, methods and attributes; once declared they become callable and calling them creates an instance:
class Alpha prop = 0 end item = Alpha() item. item.prop
As with any Falcon item, classes are values and can be cached elsewhere and then instantiated by calling the cached item; continuing the above program we may see:
class Beta; pbeta = 1; end the_class = random( Alpha, Beta ) inspect( the_class ) item = the_class()
We have a 50% chance to create an item of class Alpha or Beta.
See the result of an
inspect() on the last
item on a test run:
>>> inspect( item ) Object of class Alpha { prop => int(0) } >>>
A more complete class declaration is like the following:
class Name ( ... parameters ... ) \ from ClassA( ...params... ), \ ClassB( params ) ... ... properties ... ... init ... ... methods ... ... attributes ... end
Actually, the distinction between properties and methods is not very important in Falcon, as callable items aren't treated specially. It is more a visual convention to have properties separated from methods. The following example is more complete:
class Vector( a, b, c ) x = a ? a : 0 y = b ? b : 0 z = c ? c : 0 init > @ "Vector initialized as $self.x, " "$self.y, $self.z" end function modulo() return ( self.x * self.x + self.y * self.y + self.z * self.z ) ** (1/2) end end v = Vector( 1, 2, 3 ) > v.modulo()
Properties can be initialized through even complex expressions, using the passed parameters as initializers; the
a ? a : 0 parameter allows you to set a default value if a parameter is not given (nil). The
init block receives the same parameters that are seen by the properties initialized and it is executed immediately after all the properties are set. The following function declaration creates a property containing a computational unit (callable); we may call this method, but the distinction between non-callable and callable data is very thin in Falcon. In fact, the vector class declaration is equivalent to:
class Vector( a, b, c ) x = a ? a : 0 y = b ? b : 0 z = c ? c : 0 modulo = function() return ( self.x * self.x + self.y * self.y + self.z * self.z ) ** (1/2) end init > @ "Vector initialized as $self.x, " "$self.y, $self.z" end end
Or even:
class Vector( a, b, c ) x = a ? a : 0 y = b ? b : 0 z = c ? c : 0 modulo = nil init > @ "Vector initialized as $self.x, " "$self.y, $self.z" self.modulo = function() return ( self.x * self.x + self.y * self.y + self.z * self.z ) ** (1/2) end end end
Other than instances, in Falcon it is possible to create classless objects, either directly or deriving them from one or more classes.
object AnObject prop = 100 init > "The object has been created" end function inc(): self.prop++ function dec(): self.prop-- end AnObject.inc() > AnObject.prop
The main difference between stand-alone objects and normal instances is that their initialization is performed before the main code of a script is executed.
Falcon supports multiple inheritance with explicit order overloading:
class Base1 prop = 100 function common(): > "From Base1" function b1(): > "Personal b1" end class Base2 prop = 200 function common(): > "From base 2" function b2(): > "Personal b2" end class Derived from Base1, Base2 end instance = Derived() > instance.prop instance.common() instance.b1() instance.b2()
As seen, the class declared last in the "from" clause (in our case, Base2) takes precedence over the others in forming the final instances. It is possible to acess an arbitrary base class element by explicitly naming it; continuing the previous example:
instance.Base1.common()
One very important concept in Falcon OOP model is the method persistence. Look at this example typed at the interactive interpreter:
>>> array = [1,2,3] : Array >>> method = array.len : <?> >>> array += 4 : Array >>> > "Current array len: ", method() Current array len: 4
The method taken from the array instance (
len is a method available for any Falcon item) continues to refer to the given item also if the item changes.
That's enough for now. I won't go into more technical aspects of the class and object definitions or the static members, static calls and static function blocks, or the initialization and inter-module class resolution sequence. Just notice that Falcon classes are seen internally as types and it is possible to determine the type of an object and its inheritance structure through language facilities. For example,
select is a special statement that switches over the type of a variable; as such, it is possible to write something like the following:
select item case StringType ... case Derived ... case Base2 ... case Base1 ... end
One quite useful language feature is the "provides" operator which checks for a property being actively offered by an instance. For example:
if instance provides method instance.method(...) ... end
Class instances and objects can be given one or more attributes. Attributes are binary qualities that can be checked for quite effectively and can be assigned to every class and object instance. Also, it is possible to iterate through all the items having the same attribute at a certain moment and record the list of items with language functions. Look at the next example (not suitable for the interactive compiler):
attributes isReady end class CanBeReady( id ) id = id //(1) init //(2) if random(true, false): give isReady to self end function hail() > "Hello from CanBeReady ", self.id end end object BornReady function hail() > "Hello all" end has isReady //(3) end // create some instances. insts = [] for i in [0:10] inst += CanBeRead( i ) end // ok... who's ready? for item in isReady //(4) if item provides hail item.hail() end end
Notice that properties can be named after the parameters of the class initializer as in (1). In (2) I use the "give" statement that can assign or remove one or more attributes to/from one or more objects. In (3), I declare the object has having the
isReady attribute from the start. The same "has" clause can be specified also in classes, so as to make their instances have an attribute since their creation. In (4) I use the for/in loop to traverse all the items having an attribute. There are various other ways to scan the "attributed set", or the set of instances having a certain
attributes; in this example, it is possible to generate an iterator (Java-like list traverse facility object), or call the
having(...) function that returns an array containing all the items in an attributed set. The
has and
hasnt operators can be used to check for an instance having a certain attribute.
Prototype-oriented programming
Prototype-oriented programming is "light object oriented programming" where emphasis is set upon the exposition of commonly agreed interfaces rather than on class and derivation.
There are two devices in Falcon that work like that: blessed dictionaries and array bindings. Falcon dictionaries are collections of pairs of unique keys and values. Keys can be any valid Falcon item, possibly providing an internal ordering (a compare method), or, in case this is not provided, ordered on their unique memory representation. Try this sample to get an idea:
date = CurrentTime() dict = [ 1 => "Data for key 1", "alpha" => "Data for key alpha", date => "Data for a timestamp" ] inspect( dict )
They can be accessed and modified like arrays:
> dict[ "alpha" ] dict[ "alpha" ] = "Changed" > dict[ "alpha" ]
For the matter at hand, it is simply possible to create objects by creating methods which refer to
self and access the inner data both as dictionary items and as properties. It is just necessary to "bless" the dictionary; in this way, we tell Falcon that we want the dictionary to use its own string keys as properties:
instance = bless( [ "prop" => 0, "inc" => function(); self.prop++; end, "dec" => function(); self.prop--; end ] ) instance.inc() > instance.prop
An interesting property of Prototype OOP is that it is possible to change the definition of the instances after their creation; continuing the above example:
//(1) instance[ "reset" ] =function();self.prop = 0;end instance.reset() > instance.prop
In (1), a new entry in the dictionary is created and it is set to a method resetting a property. As in full blown OOP, Prototype OOP is subject to method persistence, but method persistence is not mandatory. In simpler words, it is possible to extract a complete method, recording the original instance from which the method was taken, or just take the data as if the item was a simple dictionary, breaking the method-instance unity. Still continuing the above example:
method = instance.inc method(); method(); method() //(1) > instance.prop
In (1) we're using the method unity, but...
func = instance[ "inc" ] func() //(2)
doing this would raise an error in (2), as
self becomes unassigned. This means we can take methods stored in blessed dictionaries and assign them to other objects or blessed dictionaries, and the
self item stored inside them will refer to the target item. For example, instead of (2) we can do:
other = bless([ "prop" => 0, "inc" => func ]) other.inc() > other.prop
If we used
instance.inc to get the inc method in instance, putting it in any object would have cut the method unity, and...
method = instance.inc other = bless([ "prop" => 0, "inc" => method ]) other.inc() > instance.prop //(3)
In (3) we see that
self still refers to
instance, even if called from
other.
Notice that the
self object is resolved as the original item in which the method refers to the actual dictionary where the method is stored. So, it is possible to modify dynamically the dictionary from within a method; see this example:
instance = bless( [ "counter" => 0, "addMethod" => function(); x = ++self.counter; //(1) self[ "newMethod" + x ] = function(); > "I am new method " + x; end; end ]) instance.addMethod() instance.addMethod() instance.addMethod() instance.newMethod2() //(2)
The
"newMethod" + x expression in (1) will cause a new entry to be generated by concatenating the string "newMethod" and the string literal value of "x" (1, 2, 3 etc). Notice that the
; at the end of the statements inside the dictionary declaration is necessary, as the parser suspends the recognition of end of lines when it enters a set of parenthesis or square brackets.
The second mean of prototype oriented programming merges with the array bindings we have seen previously. In fact, other than data, array bindings may also contain functions and functions referring to
self stored as array bindings become methods. See the following "doubler" example:
doubler = .[ map &func ] doubler.func = lambda x => x * 2 inspect( doubler( [1,2,3,4] ) ) //(3)
The "map" function uses the first parameter it receives, applying it to each element of the second parameter. So, if the parameter is a binding it can be configured later on via assignment to the given binding. The effect of (3) will be that of doubling each element in the given array and showing the result. However, array bindings are not limited to being used internally via the
& operator. They can work very similarly to blessed dictionaries:
instance = [] instance.prop = 0 instance.inc = function(); self.prop++; end instance.inc() > instance.prop
We'll see how this is integrated in functional programming and tabular programming in the following paragraphs.
One last note: to create multiple instances of a prototype object we just need the language-wide "clone" method. Continuing the previous example:
copy = instance.clone() copy.inc() > @ "Original value: $instance.prop; Modified value: $copy.prop"
Functional programming
We can just touch upon this deep topic here. This programming paradigm would require a specific introduction course. However, we have seen some functional aspects in Falcon while describing other characteristics.
The Falcon functional programming model is based on evaluation of sequences, which can contain normal function calls or special functions called Eta, which redefine internally the functional evaluation process.
For example, the functional if (iff) resolves one branch or another depending on the evaluation of a comparand. Some usueful functions for functional programming can be found in the "funcext" Falcon standard module. The following example uses
gt (greater than) from the funcext module:
load funcext iff ( .[gt .[readNumber] 10 ], //(1) .[printl "The nubmer is > 10" ], .[printl "The number is <= 10" ] ) function readNumber() while true >> "Please enter a number: " try //(2) return int( input() ) end end end
The code in (2) is a "neutral" try, discarding any error coming from the code in its block; in fact,
int() would raise an error if the user doesn't input a number, in which case we'd just ignore the error and loop again. The
gt function in (1), from the funcext module, performs a "greater than" check on the two elements, and is equivalent to:
gt = lambda x, y => x > y
Notice in (1) the fact that readNumber function is itself in stored in a separate sequence; in this way, the evaluation engine working on the comparison code sees that the item must be reduced, and does so by resolving (calling) the function
readNumber.
The simplest and most generic interface to the functional engine in Falcon is the
eval() function and the evaluation operator
^*. Supposing we store the sequence for a later evaluation, it is possible to configure them via late bindings. Continuing the previous example:
seq = .[iff .[gt .[readNumber] &limit ] .[printl "The nubmer is > " &limit ] .[printl "The number is <= " &limit ] ] seq.limit = 5 eval( seq ) //(1)
Or instead of the eval function in (1):
^* seq
The
^* eval operator is quite useful whenever you are unsure about the nature of a property or of a variable. If the variable is a value, then that value is returned; if it's a function, a method, a functional sequence or any callable item, it is called and its return value is set as the result of the expression.
Falcon provides a rich and ever growing set of functional operators and Eta functions. The following code shows the functional version of a for/in loop counting only pair numbers.
^* .[times ,[0:11] &n .[ .[ (lambda x => x % 2 != 0 ? oob(1):0) &n ] .[ printl "Pair number: " &n ] ]]
The
times function calls repeatedly the functions listed in its third parameter, assigning the binding passed as second parameter a value determined by the first parameter. In this case, we used a range. To avoid confusion with a ranged access to the "times" symbol, we used an explicit comma to separate it.
Times then assigns 1, 2, 3 and so on to the
&n binding, calling each time the functions in the following sequence. In our case, the first function may return either 0 or an
Out of band 1.
Out of band items are items with special meaning in functional sequences or in your program. I can't delve into details about their usage patterns here but the out-of-band flag can travel with an item, be it stored as an array or dictionary value, as a property, passed as parameter or returned from a function, to signal the algorithms involved in the process about "special meanings". For example, many functions may return legally any Falcon item, including nil, but they may wish to inform the caller about an "invalid" data or a return value to be ignored without being forced to raise an error. In these cases, the processor function may return an out of band nil item to tell the caller to ignore the value.
The "times" functions, and all the other functional loops provided by the standard library of Falcon, interpret an out of band "1" as a request to restart the loop advancing the loop count variable. In other words,
oob(1) is a sort of "functional continue". So, when the
&n binding parameter passed to the lambda as "x" is found to be impaired, the lambda expression returns an out of band 1, asking "times" to skip the rest of the sequence.
Similarly, an
oob(0) is considered a functional break. The next example exits as a pair number > 5 is found:
^* .[times ,[0:11] &n .[ .[ (lambda x => x % 2 != 0 ? oob(1):0) &n ] .[ printl "Pair number: " &n ] .[ (lambda x => x > 5 ? ^+ 0 : 0) &n ] //(1) ]]
Notice the "^+" operator in (1); this operator works exactly as the
oob() function, making the following item an out of band item.
Tabular programming
Tables are simple but powerful means to represent facts and to organize things. Columns are properties, and row instances; a cell can contain any Falcon item, including OOP instances, classes, functions and even other tables. So, cells can be data but also algorithms or even whole programs. Tables are also an excellent way to select behaviors between a finite set of choices, or to mix behaviors and merge them, providing ready-made fuzzy logic engines.
The heart of tabular programmings is the Table class and Falcon arrays, which performs as table "rows". Arrays used as table rows know the table which they come from, and their elements can be accessed by name through the dot accessor, or still be referred by numbers (column indexes).
For example, let's create an employee table which includes a configurable payment method:
function normal_salary( work_hours ) return work_hours * self.hourly_pay //(1) end function extra_salary( work_hours ) if work_hours <= self.daily_hours return work_hours * self.hourly_pay else return self.daily_hours * \ self.hourly_pay + \ (work_hours - self.daily_hours) * \ self.extra_pay end end Employees = Table( //(2) .[ 'name' 'hourly_pay' 'extra_pay' 'daily_hours' 'payment' ], .[ 'ed' 20 24 8 normal_salary ], .[ 'frank' 18 24 6 extra_salary ] ) //(3) > "Ed's pay for 9 hours: " + \ Employees.find( 'name', 'ed' ).payment(9) > "Frank's pay for 9 hours: " + \ Employees.find( 'name', 'frank' ).payment(9)
You can see that table rows can be accessed as objects, their properties being the column names of the table in which they are stored. The function in (1) is set as part of a row, and it retrieves the value of the "hourly_pay" column of the active entity. The call in (2) creates the table. In (3), the "find" method gets the table row where the entity with the given name is found, and then it calls the "payment" property, resolving in one of the two calculation functions. It is also possible for a row to refer the owning table via "self.table()".
Tables can be widely manipulated; rows and column can be inserted and removed, and a set of table specific algorithms is provided. As the model has been just recently introduced, the algorithms are currently limited to essential searches but it is also possible to perform a bidding or choice depending on the best row given a choice algorithm. Tables make a great base from which to pick different partial solutions and mix them. Simple, ready-made fuzzy logic engines can be built by selecting a row depending on the fitness of some of its elements. Then, several functions residing in the chosen row can be applied and a weighted mean value can be then determined. The next versions of the engine will have a strong support for this table-wide operations.
Rows in tables are still Falcon arrays. Continuing the above example, we can simply...
>> "Data regarding ed: " for item in Employees.get(0) >> item formiddle: >> ", " forlast: > "." end
And, as normal arrays, it is possible to give them bindings that are not part of the table structure. For example:
ed = Employees.find( 'name', 'ed' ) frank = Employees.find( 'name', 'frank' ) ed.wife = "mary" frank.fiancé = "jenny"
But mangling the array indexes is immediately reflected in the corresponding table property, and the other way around:
ed.daily_hours = 9 > "New daily hours for ed: ", ed[3] frank[3] = 8 > "New daily hours for frank: ", ed.daily_hours
Tables can be ordered into pages, to store dataset that are suitable under some conditions and can be switched when other conditions occur.
Message oriented programming
As tabular programming, this model has been recently introduced and is being extended and reviewed.
The idea beyond message-oriented programming is that of creating a set of agents which can compete or co-operate on messages, which can carry any Falcon data. Instead of calling directly a target method in a certain object, a sender generates a message that can be received by one or more receivers. The data traveling along with the message is not read-only; this means that participants to the broadcast process may contribute in creating a common solution, rather than immediately providing one.
Attributes are currently the means by which subscription to messages are performed. By having an attribute, an object declares it is willing to receive broadcasts on that attribute. Broadcasts are then sent to a processing method in the object, which has the same name of the attribute:
attributes listening end class Agent( id ) id = id init > "I am agent ", id end function listening( p1, p2, p3 ) //(1) > @"Processing message $p1 $p2" if p3.type() == ArrayType p3 += self.id //(2) end end has listening //(3) end
The method, having the same name as the attribute in (1), will be called back when a message on the attribute (3) is broadcast. The code in (2) just shows a sample of co-operative creation of a shared data. Each agent participating in the broadcast just adds its ID to a list being formed.
A sample usage of this class may be:
alpha = Agent( "alpha" ) gamma = Agent( "gamma" ) delta = Agent( "delta" ) cooperate = [] broadcast( listening, "Hello", random(100), cooperate ) //(1) // who did cooperate? for agent in cooperate > "Agent ", agent, " participated." end
The function broadcast (1) passes the parameters that follow to all the "listening" methods registered by giving the attribute with the same name to an instance. As the third parameter is an array, it will be filled with the ID of the items receiving the message. Of course, it may be any Falcon item, including a method, a whole functional sequence, a class or an instance and so on.
There are several mechanisms associated with the broadcast function. Let me just enumerate them:
Returning "true" from a receiving method makes it possible to stop the message being sent to further receivers. This allows to consume the message in a non-cooperative (exclusive) message management mode.
It is possible to send messages to "priority queues". The first parameter of the broadcast function is a list of attributes; then the message broadcast is repeated for each attribute until a method responding to the message returns true.
It is possible to perform asynchronous broadcasts by using the launch keyword, which starts a co-routine calling the required function. For example,
launch broadcast( listening, "Hello", random(100), cooperate )would immediately return preparing the VM to perform the broadcast via a co-routine.
To subscribe or unsubscribe a broadcast, it is possible to either add or remove the attribute from an instance, or eventually nil the receiving method.
One of the things that is already implemented in this model is the event marshaling system. When an application needs to send articulated messages to a relatively constant set, instead of listening on different attributes, it is possible to use the event Marshalling mechanism, which also provides facilities to raise errors in case of unhanded events. Events are structured as an array whose first element is a string, which will be the event name. The other elements of the event array will be received as parameters of the event handlers.
For example, suppose that we want to send two "orders", activate and deactivate, to all the listeners. Continuing the previous example:
class ActiveAgent( id ) from Agent( id ) // (1) listening = .[marshalCBR "on'"] // (2) function onActivate( p ) > self.id, " activated with ", p end function onDeactivate() > self.id, " deactivated." end end aa1 = ActiveAgent( "active one" ) aa2 = ActiveAgent( "active two" ) broadcast( listening, [ "activate", random(10)] ) broadcast( listening, [ "deactivate" ] )
The inheritance declaration in (1) spares us some detail, as adding the listening attribute. The code in (2) overloads the listening method with the
marshalCBR function. The first parameter,
on' just tells the system to marshal the incoming event to the method starting with
on and the first letter of the event capitalized. When the listening method is called with the event as an extra parameter, the event is decomposed and the proper method is called.
We're working at a more complete message-oriented model which should make it possible to write programs that don't require calling or prior knowledge of any non-system module.
Other stuff I couldn't squeeze in
Even if what has been discussed to date is detailed, Falcon has still more important features that cannot be covered in this article. The most important are:
- FTD - Falcon template documents (php-like template-based scripting).
- Exception management (try/catch/raise statements).
- Co-routines (we have seen the
launchcommand).
- Native support for internationalization.
- Multi-platform native zero contention multi-threading.
- Module loading, relative naming and active namespaces.
- On-the-fly compilations.
- Plugin-ability (dynamically loadable modules).
- Meta-macro compiler.
The engine offers an unmatched level of facility for embedding applications, which can extend the virtual machine, create streams that can be fed into the virtual machine to manage directly its I/O, co-operative time slice management, limits control, periodic callback control, direct C++ structure reflection into language classes and more. Even more support is granted by a
Service class hierarchy which shares the code offered to Falcon scripts with
embedded applications or simply with foreign applications; that just need to use the Falcon dynamic library loader to access a set of multi-platform and virtualized services that Falcon modules offer to scripts.
There are many things that Falcon has to offer to the community, but we need the community to support Falcon. The project is young but we have already a wide and flexible codebase. If you want to get your hands dirty in a project like this, bring your own ideas and help us to make them a reality. We will welcome you.
Giancarlo Niccolai ( The Falcon Programming Language)
Dennis M. Clarke ( Blastwave.org Inc. )
Common Lisp
You know, after reading the first paragraph I thought you were talking about Common Lisp. ;) | http://www.freesoftwaremagazine.com/articles/falcon_programming_language_brief_tutorial | CC-MAIN-2015-48 | refinedweb | 8,027 | 61.46 |
This is the mail archive of the binutils@sourceware.org mailing list for the binutils project.
Hi Cary, thanks. Attached the updated patch. The only diff from patch2 is the "hash_value" functionï which I directly pasted below for ease of review. --- a/gold/aarch64.cc +++ b/gold/aarch64.cc @@ -496,26 +496,20 @@ class Reloc_stub // Return a hash value. size_t hash_value() const { - // This will occupy the lowest 20 bits in the final hash value. - size_t name_hash_value = 0XFFFFFF & gold::string_hash<char>( + size_t name_hash_value = gold::string_hash<char>( (this->r_sym_ != Reloc_stub::invalid_index) ? this->u_.relobj->name().c_str() : this->u_.symbol->name()); - // We only have 4 stub types, so we allocate 2 bits for it in the final - // hash value, and they will occupy bit 21 - 22. + // We only have 4 stub types. size_t stub_type_hash_value = 0x03 & this->stub_type_; - // 5 bits for r_sym_, even if it's a invalid_index. - size_t r_sym_hash_value = this->r_sym_ & 0x1F; - // 5 bits for addend_. - size_t addend_hash_value = this->addend_ & 0x1F; - return name_hash_value - | (stub_type_hash_value << 20) - | (r_sym_hash_value << 22) - | (addend_hash_value << 27); + return (name_hash_value + ^ stub_type_hash_value + ^ ((this->r_sym_ & 0x3fff) << 2) + ^ ((this->addend_ & 0xffff) << 16)); } // Functors for STL associative containers. struct hash { On Wed, Oct 15, 2014 at 9:59 AM, Cary Coutant <ccoutant@google.com> wrote: > + return name_hash_value > + | (stub_type_hash_value << 20) > + | (r_sym_hash_value << 22) > + | (addend_hash_value << 27); > > Please add parentheses around the whole expression, then line up the > "|" operators just inside the open paren (standard Gnu style for > continued expressions). > > My concern with the previous hash function wasn't about XOR'ing the > additional bits into the string hash, but with the fact that, e.g., > r_sym, stub_type, and addend were all effectively XOR'ed together > without any multiplicative factor to keep them from canceling one > another out. Your new function avoids that, but drops all but the > lower 5 bits of addend and r_sym. I'm not sure what distribution > you're expecting, so it's not immediately clear to me how good this > hash is. If you go back to XOR, there's no need to mask or shift away > any of the bits of the string hash -- just do something to keep the > three other fields from canceling. One way is to mask and shift them > into non-overlapping positions, as you've done here, but you can keep > more of the bits; something like this: > > size_t name_hash_value = gold::string_hash<char>(...); > return (name_hash_value > ^ stub_type_hash_value > ^ ((r_sym & 0x3fff) << 2) > ^ ((addend & 0xffff) << 16)); I choose to use this straightforward and faster implementation. > > A more robust approach would be to use a hash combine function. > Unfortunately, I don't think STL provides one, but Boost has > hash_combine(), and libiberty has an equivalent, iterative_hash() > (#include "hashtab.h"). You could use iterative_hash something like > this: > > hashval_t h = static_cast<hashval_t>(gold::string_hash<char>(...); > h = iterative_hash_object(this->stub_type, h); > h = iterative_hash_object(r_sym, h); > h = iterative_hash_object(addend, h); > return static_cast<size_t>(h); > > It's only a 32-bit hash function, but that's probably sufficient. If > you don't want to throw away the full string_hash value, you could do > this instead: > > hashval_t h = 0; > h = iterative_hash_object(this->stub_type, h); > h = iterative_hash_object(r_sym, h); > h = iterative_hash_object(addend, h); > return (gold::string_hash<char>(...) > ^ static_cast<size_t>(h); > > Using iterative_hash might be noticeably slower than the simpler XOR > strategy, so I'm OK with either. > > -cary > > > On Mon, Oct 13, 2014 at 1:31 PM, HÃn ShÄn (ææ) <shenhan@google.com> wrote: >> Hi Cary, thanks. All done in below. >> >> Attached modified patch - relaxation.patch2. Also attached the diff >> from patch2 to patch1 for ease of review. >> >> Thanks, >> Han >> >> On Fri, Oct 10, 2014 at 4:28 PM, Cary Coutant <ccoutant@google.com> wrote: >>> >>> > Here we have the patch for gold aarch64 backend to support relaxation. >>> > >>> > In short relaxation is the linker's generation of stubs that fixes the >>> > out-of-range jumps/branches in the original object file. >>> > >>> > With this implementation, we are able to link a 456MB aarch64 application >>> > (correctness of the result file, though, hasn't been verified.) >>> >>> Thanks. Here are my comments... >>> >>> -cary >>> >>> >>> + struct >>> + { >>> + // For a global symbol, the symbol itself. >>> + Symbol* symbol; >>> + } global; >>> + struct >>> + { >>> + // For a local symbol, the object defining object. >>> >>> I know this is actually unchanged code from before, but this >>> comment looks wrong. Should probably be "the defining object" >>> or "the object defining the symbol". >> >> >> Done >>> >>> >>> + // Do not change the value of the enums, they are used to index into >>> + // stub_insns array. >>> >>> In that case, you should probably assign values explicitly to each >>> enum constant. Enum constants like this should generally be all >>> upper case (like macros and static constants). >> >> >> Done - Changed to all upper case and explicitly assigned values to them. >>> >>> >>> + // Determine the stub type for a certain relocation or st_none, if no stub is >>> + // needed. >>> + static Stub_type >>> + stub_type_for_reloc(unsigned int r_type, AArch64_address address, >>> + AArch64_address target); >>> + >>> + public: >>> >>> Unnecessary: everything above this was also public. >> >> >> Done >>> >>> >>> + // The key class used to index the stub instance in the stub >>> table's stub map. >>> + class Key >>> + { >>> + public: >>> >>> "public" should be indented one space. >> >> >> Done >>> >>> >>> + // Return a hash value. >>> + size_t >>> + hash_value() const >>> + { >>> + return (this->stub_type_ >>> + ^ this->r_sym_ >>> + ^ gold::string_hash<char>( >>> + (this->r_sym_ != Reloc_stub::invalid_index) >>> + ? this->u_.relobj->name().c_str() >>> + : this->u_.symbol->name()) >>> + ^ this->addend_); >>> >>> I know this is just copied from arm.cc, but it looks to me like >>> this hash function might be a bit weak. In particular, >>> stub_type_, r_sym_, and addend_ might easily cancel one another >>> out, causing some preventable collisions. r_sym_ is also >>> unnecessary (but harmless, I guess), when it's equal to >>> invalid_index. I'd suggest at least shifting stub_type_, r_sym_, >>> and addend_ by different amounts, or applying a different >>> multiplier to each to distribute the bits around more, and >>> applying r_sym_ only when it's a local symbol index. >> >> >> Done by placing name hash at bit 0-19, stub_type 20-21, r_sym 22-26 >> (even if it's a invalid_index) and addend 27-31. >>> >>> >>> + struct equal_to >>> + { >>> + bool >>> + operator()(const Key& k1, const Key& k2) const >>> + { return k1.eq(k2); } >>> + }; >>> + >>> + private: >>> >>> "private" should be indented one space. >> >> >> Done. >>> >>> >>> + // Initialize look-up tables. >>> + Stub_table_list empty_stub_table_list(this->shnum(), NULL); >>> + this->stub_tables_.swap(empty_stub_table_list); >>> >>> It's simpler to just use resize(this->shnum()). The "swap" idiom >>> is useful when you need to release memory, but not necessary for >>> initialization. >> >> Done >>> >>> >>> + // Call parent to relocate sections. >>> + Sized_relobj_file<size, big_endian>::do_relocate_sections(symtab, layout, >>> + pshdrs, of, pviews); >>> >>> Indentation is off by one. >> >> >> Done. >>> >>> >>> + unsigned int reloc_size; >>> + if (sh_type == elfcpp::SHT_RELA) >>> + reloc_size = elfcpp::Elf_sizes<size>::rela_size; >>> >>> For REL sections, reloc_size will be left uninitialized here. >>> If you don't expect REL sections, you should assert that. >> >> >> Done. >>> >>> >>> + const unsigned int shdr_size = elfcpp::Elf_sizes<size>::shdr_size; >>> + const elfcpp::Shdr<size, big_endian> text_shdr(pshdrs + index * shdr_size); >>> + return this->section_is_scannable(text_shdr, index, >>> + out_sections[index], symtab); >>> >>> The naming doesn't really make it clear that >>> section_needs_reloc_stub_scanning is looking at the REL/RELA >>> section, while section_is_scannable is looking at the PROGBITS >>> section that is being relocated. You've used text_shdr for the >>> section header, so I'd suggest using text_shndx instead of index, >>> and text_section_is_scannable for the function name. >> >> >> Done. >>> >>> >>> + // Currently this only happens for a relaxed section. >>> + const Output_relaxed_input_section* poris = >>> + out_sections[index]->find_relaxed_input_section(this, index); >>> >>> This continuation line needs indentation (4 spaces). >> >> >> Done. >>> >>> >>> + // Get the section contents. This does work for the case in which >>> + // we modify the contents of an input section. We need to pass the >>> + // output view under such circumstances. >>> >>> Should the comment read "This does *not* work ..."? >>> >>> I don't see you handling the case where you modify the contents, >>> so maybe that last sentence is not necessary? >> >> >> Done by removing the confusing last 2 sentences. >>> >>> >>> +// Create a stub group for input sections from BEGIN to END. OWNER >>> +// points to the input section to be the owner a new stub table. >>> >>> "OWNER points to the input section that will be the owner of the >>> stub table." >> >> >> Done. >>> >>> >>> + // Currently we convert ordinary input sections into relaxed sections only >>> + // at this point but we may want to support creating relaxed input section >>> + // very early. So we check here to see if owner is already a relaxed >>> + // section. >>> + gold_assert(!owner->is_relaxed_input_section()); >>> + >>> + The_aarch64_input_section* input_section; >>> + if (owner->is_relaxed_input_section()) >>> + { >>> + input_section = static_cast<The_aarch64_input_section*>( >>> + owner->relaxed_input_section()); >>> + } >>> >>> Given the assert above, this code can't be reached. If you want to >>> leave it in as a stub for the future, I'd suggest removing the above >>> assert, and replacing the then clause with gold_unreachable(). >> >> >> Done by replacing gold_assert by gold_unreachable inside the if clause >> also updated the comments. >>> >>> >>> + do >>> + { >>> + if (p->is_input_section() || p->is_relaxed_input_section()) >>> + { >>> + // The stub table information for input sections live >>> + // in their objects. >>> + The_aarch64_relobj* aarch64_relobj = >>> + static_cast<The_aarch64_relobj*>(p->relobj()); >>> + aarch64_relobj->set_stub_table(p->shndx(), stub_table); >>> + } >>> + prev_p = p++; >>> + } >>> + while (prev_p != end); >>> >>> Suggest renaming begin/end to maybe first/last? It took me a minute >>> to understand that "end" doesn't refer to the same "end" that an >>> iterator would test against, and that you intended this to be an >>> inclusive range. >> >> >> Done renaming. >>> >>> >>> Why not just "do { ... } while (p++ != last);"? >> >> Done. >>> >>> >>> +// Group input sections for stub generation. GROUP_SIZE is roughly the limit >>> +// of stub groups. We grow a stub group by adding input section until the >>> +// size is just below GROUP_SIZE. The last input section will be converted >>> +// into a stub table. If STUB_ALWAYS_AFTER_BRANCH is false, we also add >>> +// input section after the stub table, effectively double the group size. >>> >>> Do you mean "the last input section will be converted into a stub >>> table *owner*"? >>> >>> And "we also add input section*s* after the stub table, effectively >>> *doubling* the group size." >> >> >> Done. >>> >>> >>> + case HAS_STUB_SECTION: >>> + // Adding this section makes the post stub-section group larger >>> + // than GROUP_SIZE. >>> + gold_assert(false); >>> >>> You can just use gold_unreachable() here. >>> >>> + // ET_EXEC files are valid input for --just-symbols/-R, >>> + // and we treat them as relocatable objects. >>> >>> For --just-symbols, shouldn't you use the base implementation >>> of do_make_elf_object? >> >> >> Done by invoking parent implementation. >>> >>> >>> +// This function scans a relocation sections for stub generation. >>> >>> s/sections/section/ >> >> >> Done. >>> >>> >>> + // An error should never aroused in the above step. If so, please >>> + // An error should never arouse, it is an "_NC" relocation. >>> >>> "arise". >>> >>> + gold_error(_("Stub is too far away, try use a smaller value " >>> + "for '--stub-group-size'. For example, 0x2000000.")); >>> >>> Either "try using" or "try to use" or just "try a smaller value". >> >> >> Done. >> >> >> >> -- >> Han Shen | Software Engineer | shenhan@google.com | +1-650-440-3330 -- Han Shen | Software Engineer | shenhan@google.com | +1-650-440-3330
Attachment:
relaxation.patch3
Description: Binary data | http://www.sourceware.org/ml/binutils/2014-10/msg00111.html | CC-MAIN-2017-43 | refinedweb | 1,718 | 57.67 |
Custom Windows Forms Controls: ColorPicker.NET
March 2005
Chris Sano
Microsoft Developer Network
Summary: Chris Sano introduces you to ColorPicker.NET and demonstrates techniques that were used to build some of the custom controls in the application. (27 printed pages)
Applies to:
Microsoft .NET Framework 1.1
Visual Basic .NET
Visual C#
Code Sample
There are two different sets of code samples that accompany this article:
1. A recent snapshot of the ColorPicker.NET source tree (C# only).
2. The code discussed in this article (C# and Visual Basic .NET).
Download CustomWindowsFormsControls_ColorPicker.msi.
Contents
Introduction
How the Application Works
The Color Slider
Using the Color Slider in Your Application
Color Slider Infrastructure
The Color Slider in ColorPicker.NET
Drag and Drop
Drag-and-Drop Infrastructure
Drag and Drop in ColorPicker.NET
Conclusion
About the Author
Introduction
ColorPicker.NET, as seen in Figure 1, is the result of a small personal project that I undertook in an attempt to reverse engineer the functionality in the Adobe Photoshop color picker. I do a lot of user interface design work, and in place of firing up Photoshop every time I needed to experiment with some colors, I wanted a lightweight application that would allow me to adjust and sample colors from the HSB and RGB color spaces, and provide the ability to save the colors that I liked best to a swatch panel for future use.
Figure 1. Main ColorPicker.NET interface
I wrote this article to provide insight into the implementation of some of the more interesting parts of the application. First I will discuss the color slider, and then I will describe the drag-and-drop experience involved in dragging the currently selected color to the color swatch panel. Future installments will cover other areas of the application.
How the Application Works
Before we get started, I'm going to provide a brief overlook of the functionality available in ColorPicker.NET, as well as the different terminology used throughout the article.
ColorPicker.NET has two different color spaces, which are theoretical three-dimensional color systems in which coordinates are used to represent colors. The red-green-blue (RGB) color space is created by mapping those colors onto a three-dimensional Cartesian coordinate system. The hue-saturation-brightness (HSB) color space works differently, as it is mapped onto a cylindrical coordinate system. Hue represents the actual color, saturation expresses the strength or purity of the color, and brightness is the relative brightness or darkness of the color.
The color slider represents the range of values of the selected color space component. The other two components are represented on the axes in the color field, which is the area on the far left of the interface in Figure 1. For instance, if you select the green color space component in the RGB color space, the range of values of the green coordinate would be represented by the color slider, and the red and blue coordinates would be represented by the x and y axes respectively, in the color field. As another example, by selecting the hue color space component, the range of the hue values would be represented by the color slider and the saturation and brightness values would be represented by the x and y axes respectively, in the color field.
When you click on the color field, a circular marker appears. The very center point of this marker represents the color that is selected. This color appears in the currently selected color window above the HSB color space. If you change the value of the selected color space component using the color slider, the currently selected color window will reflect the color that resides at the location of the circular marker.
You can change the values of the individual color space components by keying in the desired values in the component textbox. You can also type or paste HEX values in the HEX textbox.
The color swatch panel area on the right of the interface in Figure 1 contains predefined color swatches. You can retrieve the color space or hex values of the individual swatches by clicking on them. If you want to save any of the colors that you have selected, you can add to the existing swatches by clicking on the currently selected color window and dragging the color to the color swatch panel.
The Color Slider
The color slider control in ColorPicker.NET, much like the color slider in the Photoshop color picker dialog, provides a means of adjusting the value of the currently selected color space component using the mouse. Users are able to select a value between 0 and 255 by dragging the arrows or clicking anywhere within the defined color region. Even though the control displays a color gradient, it does not perform any color-related calculations.
This section is broken down into three distinct components. First, I'll explain how easy it is to add the color slider control to a form, and prepare it for use. This will give you an idea of what is involved in making it work. Second, I'll examine the infrastructure of the control and explain how the control was built. Finally, I'll explain how I incorporated the color slider into the color picker application and discuss some of the problems that I encountered while doing so.
Using the Color Slider in Your Application
Figure 2. A form containing the Color Slider control
To add the color slider control (shown in Figure 2) to your form or another control, you need to define and initialize the ColorSlider object and set a few of its layout properties, shown in the following code block. The instance also subscribes to the ValueChanged event that the control publishes to allow it to listen for changes in the control's value.
public class ColorSliderForm : Form { ColorSlider colorSlider1; public ColorSliderForm() { this.colorSlider1 = new ColorSlider(); this.colorSlider1.Location = new System.Drawing.Point( 8, 16 ); this.colorSlider1.Size = new System.Drawing.Size( 64, 328 ); this.colorSlider1.ValueChanged += new ValueChangedHandler( this.colorSlider1_ValueChanged ); } }
The color slider exposes a read-only property named ColorBitmap that provides a reference to an 18- by 256-pixel bitmap object. You can use this to define the color that shows up inside the middle rectangle of the color slider (henceforth referred to as the color region), as seen in Figure 2. There are no restrictions placed on the colors that you can use, but it makes the most sense to designate colors that conform to the values that the color slider represents. Below, I create a linear gradient that spans from black to red at 270 degrees from the gradient's orientation line.
public class ColorSliderForm : Form { public ColorSliderForm() { ... using ( Graphics g = Graphics.FromImage( colorSlider1.ColorBitmap ) ) { Color start = Color.FromArgb( 0, 0, 0 ); Color end = Color.FromArgb( 255, 0, 0 ); Rectangle region = new Rectangle( 0, 0, 18, 300 ); using ( LinearGradientBrush lgb = new LinearGradientBrush( region, start, end, 270f ) ) { g.FillRectangle( lgb, region ); } } } }
In the example seen in Figure 2, the text box is updated with the new value of the color slider through the ValueChanged event handler. By grabbing and moving the arrows, or clicking anywhere on the color region, you can see this value change.
Color Slider Infrastructure
The color slider places a large burden on the accuracy of the painting operations in its infrastructure. Even though there is not much to the control, there is a lot of painting involved in response to user actions and a smooth, flicker-free experience is very important. In this section, I will be walking through the implementation of the control, focusing on techniques that will ensure that the transitions between the values in the slider are as fluid as possible.
Figure 3. Components of the color slider
Before taking a look at the code, I want to point out the drawn components of the color slider control that are manifested in Figure 3. The outer region is a solid line whose purpose is purely aesthetic. It is represented in the code through the m_outerRegion field. The color region, as discussed earlier, is used to display the color and is represented through the m_colorRegion field. The left and right arrow regions are represented by the m_leftArrowRegion and m_rightArrowRegion fields respectively. The vertical position of the arrows is stored in m_currentArrowYLocation. The said identifiers are seen throughout the various code blocks that exist throughout the remainder of this section.
When the color slider is initialized, everything described in the previous paragraph is defined. The region identifiers and the color bitmap are defined as read-only values. The vertical location of the arrows is updated to the location of the top portion of the color region in the constructor.
public class ColorSlider : UserControl { // private data member declarations private int m_currentArrowYLocation; private Rectangle m_leftArrowRegion; private Rectangle m_rightArrowRegion; // readonly data member declarations private readonly Rectangle m_colorRegion = new Rectangle( 13, 7, 18, 256 ); private readonly Rectangle m_outerRegion = new Rectangle( 10, 4, 26, 264 ); private readonly Bitmap m_colorBitmap = new Bitmap( 18, 256 ); public ColorSlider() : base() { m_currentArrowYLocation = m_colorRegion.Top; } }
The OnPaint method is overridden to draw the boundaries and the arrows. The arrows are drawn with the assistance of the CreateLeftTrianglePointer and CreateRightTrianglePointer helper methods, which are shown in the code block after this one.
public class ColorSlider : UserControl { protected override void OnPaint(PaintEventArgs e) { base.OnPaint (e); using ( Graphics g = e.Graphics ) { CreateLeftTrianglePointer( g, m_currentArrowYLocation ); CreateRightTrianglePointer( g, m_currentArrowYLocation ); if ( m_colorBitmap != null ) { g.DrawImage( m_colorBitmap, m_colorRegion ); } ControlPaint.DrawBorder3D( g, m_outerRegion ); g.DrawRectangle( Pens.Black, m_colorRegion ); } } } }
The following helper methods create an array of points that are used to determine where the arrows are to be drawn. The topmost portion of the triangle is calculated first, followed by the pointer and then the bottom. The triangle is then drawn by passing the points into the DrawPolygon method of the Graphics object.
public class ColorSlider : UserControl { private void CreateLeftTrianglePointer( Graphics g, int y ) { Point[] points = { new Point( m_outerRegion.Left - ARROW_WIDTH - 1, y - ( ARROW_HEIGHT / 2 ) ), // top new Point( m_outerRegion.Left - 2, y ), // pointer new Point( m_outerRegion.Left - ARROW_WIDTH - 1, y + ( ARROW_HEIGHT / 2 ) ) // bottom }; g.DrawPolygon( Pens.Black, points ); } private void CreateRightTrianglePointer( Graphics g, int y ) { Point[] points = { new Point( m_outerRegion.Right - 1 + ARROW_WIDTH, y - ( ARROW_HEIGHT / 2 ) ), // top new Point( m_outerRegion.Right, y ), // pointer new Point( m_outerRegion.Right - 1 + ARROW_WIDTH, y + ( ARROW_HEIGHT / 2 ) ) // bottom }; g.DrawPolygon( Pens.Black, points ); } }
The fun starts when the user presses the mouse button. Before raising the MouseDown event, the control checks to see if the left mouse button was pressed. If it was, the m_isLeftMouseButtonDown flag is set and the CheckCursorYRegion method is invoked with the y-coordinate value.
If the user moves the mouse cursor while the left mouse button is down, the m_isLeftMouseButtonDownAndMoving flag is set to true and the CheckCursorYRegion method is invoked.
There are two conditions that must be met in CheckCursorYRegion. First, if the user has pressed the left mouse button, the y-coordinate must lie in between the top and bottom of the color region. If this condition is not met, the method returns and nothing happens.
Figure 4. Issues with cursor positioning
When the user moves the mouse cursor from point A to point B, there is no guarantee that Windows will provide all of the coordinates in between. In fact, it rarely ever does. In some cases, you might have something like what is displayed in the first image in the figure above where you have explicitly instructed that the y-coordinate of the cursor is to be in between the top and bottom area of the color region in order for the arrow positions to be updated. The user has dragged the mouse cursor so quickly that the last coordinate that Windows has provided that falls within the restricted zone is where the arrows lie. The ideal behavior here would be the arrows being positioned at the top portion of the color region, as displayed in the second image. In order to make this happen, a conditional expression was added that checks to see if the mouse button is down and is being moved (m_isLeftMouseButtonDownAndMoving). If it is, and the y-coordinate is outside the color region, then the value is adjusted according to the cursor position. If the cursor is above the top of the color region, then the arrows are positioned at the top. If it's below the bottom of the color region, the arrows are positioned at the bottom.
public class ColorSliderForm : Form { private void CheckCursorYRegion( int y ) { int mValue = y; if ( m_isLeftMouseButtonDown && !m_isLeftMouseButtonDownAndMoving ) { if ( y < m_colorRegion.Top || y > m_colorRegion.Bottom ) { return; } } else if ( m_isLeftMouseButtonDownAndMoving ) { if ( y < m_colorRegion.Top ) { mValue = m_colorRegion.Top; } else if ( y >= m_colorRegion.Bottom ) { mValue = m_colorRegion.Bottom - 1; } } else { return; } ... } }
After all the required conditions have been met, the vertical location of the arrows (m_currentArrowYLocation) is updated with the modified y-coordinate value. The arrow regions are then invalidated through a call to the InvalidateArrowRegions method.
When the InvalidateArrowRegions method is invoked, the regions stored in m_leftArrowRegion and m_rightArrowRegion are invalidated. After that, the new regions are created through calls to the GetLeftTrianglePointerInvalidationRegion and GetRightTrianglePointerInvalidationRegion methods, which take in the new y-value and calculate the new regions. The new regions are then invalidated to let the system know that painting instructions await its attention.
public class ColorSliderForm : Form { private void InvalidateArrowRegions( int y ) { this.Invalidate( m_leftArrowRegion ); // left of marker a in figure 5 this.Invalidate( m_rightArrowRegion ); // right of marker a in figure 5 m_leftArrowRegion = this.GetLeftTrianglePointerInvalidationRegion( y ); m_rightArrowRegion = this.GetRightTrianglePointerInvalidationRegion( y ); this.Invalidate( m_leftArrowRegion ); // left of marker b in figure 5 this.Invalidate( m_rightArrowRegion ); // right of marker b in figure 5 } }
Figure 5. (1) Invalidated arrow regions; (2) after painting has taken place.
I've provided Figure 5 to give a visual representation of the invalidation process. Marker a in the first (left) image represents the arrows at their initial location. Imagine that the user has clicked on the color region in the area where marker b resides. The translucent red rectangles that are drawn on top of the arrows and across from marker b represent the areas that are added to the update region of the control. When the control receives its next paint message, it will trigger the necessary paint operations on the regions listed in the update region, giving us the view seen in the second image.
The last thing that needs to happen is the generation of the ValueChanged event to notify all listeners that the color slider has a new value. The event data, represented by ValueChangedEventArgs, has a parameterized constructor that requires this new value. Instead of the minimum value of the slider being on top and the maximum value being on the bottom, it's the other way around, so we need to do a quick calculation to determine the value before the event can be raised.
Recall that mouse coordinates are expressed in relation to the top left corner of the window. The more you move down, the higher the y-coordinate is. In the color slider, the more you move up, the higher the value. To work around this anomaly, we subtract the difference between the y-coordinate and the value of the topmost portion of the color region from 255. For instance, if the y-coordinate was 250 and the top of the color region was 150, the value would be 155 (255 – (250 – 150) = 155).
The Color Slider in ColorPicker.NET
The value returned by the color slider works well for the coordinates in the RGB color space, since their values can range from 0-255. However, some adjustments are required in order to make it work with the coordinates in the HSB color space. The hue coordinate is measured in degrees between 0 and 360 inclusive and the brightness and saturation coordinates are measured in percentages. When the color slider value is received through the ValueChanged event handler, calculations are performed to obtain the appropriate hue, saturation, and brightness values.
In the application, the color slider is tightly integrated into the color panel control, which is the main control in ColorPicker.NET at this time. This was done because there are so many different dependencies, and it was too difficult to try to get the color slider to work as an independent control. One of the problems that I ran into during the initial development stages was dealing with lag time. When you change the color slider value, there are, at a minimum, four different controls that need to be updated: the color field, the currently selected color window, the active coordinate, and the opposing color space (that is, if an RGB value is changed, the HSB color space needs to be updated). When I attempted to slide from point A to point B, even though in many cases the change was minimal, the color transition in both the color field and the picture box was very choppy. This produced a very unpleasant user experience and was something that I needed to correct.
I wrote a simple test application that tested the difference between coordinate values supplied by sequential WM_MOUSEMOVE messages. The largest discrepancy that I could achieve between two messages in a window of the same size as the main ColorPicker window was 308. Granted, this is outside the range of values provided by the color slider, but it does show that it is entirely possible for the user to go from 0-255 within one message cycle. Imagine the visual disruption of an RGB value going from RGB: 0, 0, 0 to RGB: 255, 0, 0 without any fluidity.
I was able to fix this problem with the enlistment of a System.Windows.Forms.Timer object and several different private data fields. The objective with the timer was to gradually update the color panels and spaces to smooth out the irregularities that were being seen. It progressively reduces the gap between the old and target values by updating the current value with each tick.
Before the timer is started, the three private data fields need to be initialized. The following bulleted list manifests the purpose of each field.
- m_targetYValue represents the coordinate value supplied by the most recent WM_MOUSEMOVE message.
- m_currentYValue is used to track the value as it is moved from the old value to the target value. This is set to the value that was conveyed through the previous WM_MOUSEMOVE message (which is stored in m_oldValue).
- m_oldValue is updated with the same value as m_targetYValue. This value is checked in a conditional statement to make sure that the timer does not start if the ValueChanged method is invoked with the same value as it was the previous time.
The timer is then started with a tick value of 1, which means that the Tick event gets fired once every millisecond.
With every tick, the difference between the current and target values is checked. It is then split in half to determine the incremental amount of the current value. This process is repeated until the current value is equal to the target value.
public class ColorPanel : UserControl { private void sliderTimer_Tick(object sender, System.EventArgs e) { int difference = m_currentYValue - m_targetYValue; int nextValue = ( int ) Math.Round( ( double ) difference / 2 ); if ( nextValue == 0 ) { m_currentYValue = m_targetYValue; sliderTimer.Stop(); } else { if ( m_currentYValue < m_targetYValue ) { m_currentYValue += nextValue; } else { m_currentYValue += -nextValue; } } ... } }
For example, if the current value is 120 and the target value is 220, the first time the tick method is invoked, the difference would be 100 and the incremental value would be 50. The second time, it would be 50 and 25. The third time, it would be 25 and 12, and so forth.
With this solution in place, instead of the color slider jumping from, say, 110 to 210, it will go from 110 to 160 to 185 to 197 to 203 to 207 to 209 and finally to 210. The color panels and spaces are updated at each tick, creating the smooth transitional effect that I wanted.
Before concluding the discussion on this control, I want to note that FXCop complains about the tick frequency, warning that higher frequency periodic activity will keep the CPU busy and interfere with the tasks that it might need to perform. Since the timer will run for no longer than 10 milliseconds at a time, there should be no cause for concern. You will see a temporary spike in CPU usage as you are changing the value, but that drops back down to normal levels fairly quickly.
Drag and Drop
The drag-and-drop functionality in ColorPicker.NET allows users to build up their own custom swatch palette by dragging colors from the currently selected color window to the color swatch panel. This experience is based on what the .NET Framework provides through the Win32 OLE drag-and-drop model, but is extended to provide a more aesthetic dragging experience for the user.
Figure 6. The drag-and-drop experience
This section is broken down into two parts. As with the color slider, I'll go through the implementation details of the drag-and-drop experience and then I will briefly detail how I implemented this functionality in ColorPicker.NET.
Drag-and-Drop Infrastructure
The OLE model does not provide anything that allows you to visually enhance the drag-and-drop experience, and unfortunately, nothing was added in this area when the .NET wrapper was written. This meant that if I were to add the transparent rectangle that I had so badly wanted to, I would be forced to do all the dirty work myself.
After researching my options, I decided that in lieu of implementing global system hooks to track the cursor position and perform the necessary nonclient painting, I would emulate the painting by using a transparent form. The forthcoming paragraphs will provide you with the details of the various functionalities that I pulled together to make this happen.
In order to make the whole thing work, the form needed to meet the following criteria: (1) it was not to show up in the task bar; (2) it needed to be the top-most window; (3) its icon could not show up in the ALT+TAB window if the user pressed ALT+TAB during a drag-and-drop operation; (4) and, most importantly, it was not to steal focus from the application when displayed.
The DragForm constructor defines the properties needed to meet the first three criteria. Note that the only way to prevent the icon of a form from showing up in the ALT+TAB window is to make it a tool window (either fixed or sized).
In order to meet the fourth criterion, a brief foray into unmanaged code was required. The ShowWindow function in the User32 library enables you to explicitly instruct Windows not to activate the window when it's shown. By using this function, it is guaranteed that the form that was active at the time that the DragForm instance is shown will remain active even though the instance is visible and resides higher in the z-order.
Since the Show method in the base class is nonvirtual, a new method named ShowForm is created. The call to ShowWindow is wrapped in this method. The only downside is that those who use this class will have to remember to invoke ShowForm instead of Show if they want to ensure that the underlying form remains active.
Now we've satisfied all four requirements in the criteria list. We're not done, though. I know we haven't discussed the drag-and-drop functionality yet, but I'm going to jump ahead a little bit. The following figure contains a screenshot of the source control after the mouse button has been pressed. The drag-and-drop operation has started, and the DragForm instance is shown.
Figure 7. Borders of the tool window are visible
There's one little problem: the tile bar and the borders of the tool window are visible. It would have been easy to just change the form border style to none, but recall that in order to prevent the form's icon from showing up in the ALT+TAB window (criterion #3), the border style of the form must be set to a tool window style. Instead, I decided to add a method that would expand the client area and modify the region of the form so that the title bar and borders were excluded.
The ChangeSize method displayed below has a Size parameter, which is expected to be a representation of the desired client area. The parameter value is stored in a private data field named m_clientRectangleSize for use in the OnPaint method that I will be discussing momentarily. The Size property of the form is updated with the sum of the Size parameter and another Size object that represents the total amount of horizontal and vertical space that is consumed by the title bar and borders.
This gives us the view in the first image in Figure 8. You might not be able to tell, but the client size of the form is now the same size as the source control, which is exactly what was desired. We still have the problem with the title bar and borders showing, and the positioning of the form needs to be fixed.
Figure 8. (1) View after the form has been resized; (2) view after the title bar and borders have been excluded
The Region property allows you to define the area of the window where the operating system permits drawing. This gives us the ability to dictate which parts of the window get drawn. Here, we're only interested in having Windows paint the client area of the form. This Size parameter (recall that this is expected to be a representation of the desired client area) is used in conjunction with a Point object containing the point where the title bar and left border end to create a Rectangle object representing the new region. This is then wrapped in a Region object, giving us the borderless view seen in the second image in Figure 8 above.
Next, the problem with the positioning needs to be fixed. Even though we have created a new region, and the title bar and borders are no longer visible, the coordinates of the form are still relative to the upper left corner of the window. Since only the client area of the form is painted, we need to make some modifications so that the location of the form is relative to the client area. In other words, instead of the view in the second image in Figure 8, we want something like what is seen in Figure 9.
Figure 9. View after the Location property has been adjusted
The UpdateLocation method was added to make the deductions necessary to position the form's client area exactly above the source control when it's clicked. It has a Point parameter, which is expected to be the desired location of the form relative to the upper left corner of the client area. The x and y coordinates of the parameter are deducted from the left border width and title bar height, respectively. The updated coordinates are wrapped up inside a new Point object and its reference is passed onto the form's Location property.
When the user clicks on the source control, the coordinate differences between the cursor location and the client area of the DragForm instance are recorded through the CursorXDifference and CursorYDifference properties.
Figure 10. Demonstrates how the cursor difference property values are determined
This allows us to maintain consistency in the location of the form relative to the cursor position as the drag-and-drop operation is taking place.
The OnPaint method is overridden to draw a thin black border around the outer region of the form. This is done through the DrawRectangle method of the Graphics object. Note that when painting on a form, the coordinates are always relative to the upper left corner of the client area, regardless of whether or not the region has been modified. The client rectangle size is retrieved through the m_clientRectangleSize field, which contains a copy of the Size parameter that is passed into the ChangeSize method.
Whenever you move the mouse cursor across the active window (remember that controls are considered child windows), or press or release one of the mouse buttons, Windows sends the WM_NCHITTEST message to query where the mouse cursor lies within the window. When the window's message queue processes this message, it responds with a hit test value (HT*) letting the system know what type of cursor to display and what will happen when the mouse is clicked or released. For instance, when the cursor is along the right edge of a form, the system receives the HTRIGHT value in response, which results in the cursor type being changed to Cursors.SizeWE.
When the drag-and-drop operation is taking place, the cursor will be consistently positioned above the dragged form, which means that the form's message queue will process all the WM_NCHITTEST messages. This also means that the necessary drag events in the target control will not get raised even if the cursor is above the control. Overriding the WndProc method and setting the message's Result property to HTTRANSPARENT tells the system to send the WM_NCHHITTEST message to the underlying control, ensuring that the necessary mouse events are raised. All the other messages are processed by the form.
That's all there is to DragForm. It didn't take much code, but it certainly shows that it helps to know a few tricks. Let's jump right into incorporating it into the drag-and-drop experience.
As with every drag-and-drop operation, there is a source and a target. In this example, the source and target are PictureBox objects, named pictureBox1 and pictureBox2 respectively. The whole drag-and-drop experience starts when the user presses the mouse button above the source picture box.
In the MouseDown event handler, the DragForm gets the attention first. Its background color is changed to match the background color of the picture box, and then all of the other properties and methods that were recently discussed are updated or invoked. The drag is initiated by invoking the DoDragDrop method on the source object. The Color object that the BackColor property of the source PictureBox refers to is conveyed as the IDataObject parameter in the method invocation. Since the objective is to copy the color object from the source to the target, the DragDropEffects parameter is set to DragDropEffects.Copy.
public class Panel : UserControl { private void pictureBox1_MouseDown( object sender, System.Windows.Forms.MouseEventArgs e ) { if ( e.Button == MouseButtons.Left ) { df.BackColor = pictureBox1.BackColor; df.UpdateLocation( this.PointToScreen( pictureBox1.Location ) ); df.CursorXDifference = Cursor.Position.X - df.Location.X; df.CursorYDifference = Cursor.Position.Y - df.Location.Y; df.ChangeSize( pictureBox1.Size ); df.ShowForm(); pictureBox1.DoDragDrop( pictureBox1.BackColor, DragDropEffects.Copy ); } } }
Because I want to display the hand cursor at all times during the drag-and-drop operation, I need to subscribe to the source control's GetFeedback event. The GiveFeedbackEventHandler delegate contains a reference to a GiveFeedbackEventArgs object that exposes a UseDefaultCursor property which, when set to false, allows you to override the default drag-and-drop cursors and define your own.
The QueryContinueDrag event is continually raised throughout the drag-and-drop operation. Handling this event enables me to check up on the status of the drag-and-drop operation. The QueryContinueDragEventHandler delegate provides a reference to an instance of QueryContinueDragEventArgs, which has an Action property that notifies you of the most recent drag action. There are three different types of actions in the DragAction enumeration: Cancel, Continue, and Drop. If the drag action is continue, the cursor position is checked and the location of the form is updated through its Location property. Otherwise, if the drag has been terminated either by a cancel or drop action, the form is hidden.
public class Panel : UserControl { private void pictureBox1_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) { if ( e.Action == DragAction.Cancel || e.Action == DragAction.Drop ) { df.Hide(); } else { df.Location = new Point( Cursor.Position.X - df.CursorXDifference, Cursor.Position.Y - df.CursorYDifference ); } } }
The DragOver event is raised when the user drags the mouse cursor over a target control during a drag-and-drop operation. Its role is to determine whether or not the DragDrop event should be raised. If the Effect property of the DragEventArgs object is DragDropEffects.None, which is the default value, then the control will not accept the drop and the DragDrop event is not raised.
In the following implementation, a check is performed to see if the data associated with the drag-and-drop operation is of type Color. If it is, the DragDrop event is raised and the BackColor property of the target control is set to the color object.
public class Panel : UserControl { private void pictureBox2_DragOver( object sender, System.Windows.Forms.DragEventArgs e ) { if ( e.Data.GetData( typeof( Color ) ) != null ) { e.Effect = DragDropEffects.Copy; } } private void pictureBox2_DragDrop(object sender, System.Windows.Forms.DragEventArgs e) { Color c = ( Color ) e.Data.GetData( typeof( Color ) ); pictureBox2.BackColor = c; } }
Drag and Drop in ColorPicker.NET
The drag-and-drop operation in ColorPicker.NET is very similar to this example. The currently selected color window is the source control and the color swatch panel is the target. Users can build up custom color swatches by dragging colors from the source to the target. The only real difference in the application is the first available color swatch is highlighted when the DragOver event is fired to let the user know that they can drop the color. This can be seen in Figure 11.
Figure 11. Demonstrates the first available color swatch highlighted with a yellow border
Conclusion
This article provides some insight into the ColorPicker.NET infrastructure. I also demonstrate the techniques that were used to implement the color slider and the drag-and-drop functionality that were used in the application. I will be discussing some of the other components in a future article, but until then, the source code for the application is available if you're interested in taking a look at them.
Please note that ColorPicker.NET is a continually evolving project. The source code available with this article is a snapshot of code that was deemed stable at the time this article was written. For a more recent snapshot and/or the latest binaries, please go to the official ColorPicker.NET Web site at.
About the AuthorAbout the Author
Chris Sano is a Software Design Engineer with MSDN. When he's not working like mad on his next article, he can be found wreaking havoc with his hockey stick at the local ice rink. He welcomes you to contact him at csano@microsoft.com with any questions or comments that you may have about this article, or things that you'd like to see in future pieces. | http://msdn.microsoft.com/en-us/library/ms996423.aspx | CC-MAIN-2014-15 | refinedweb | 5,826 | 53 |
Referential Transparency in JavaScript and TypeScript: Or why to prefer const over let
When I look back at my programming experience I understand that at the start of my career it was much harder to read someone’s code than to write it. And even though now I think that I am good at both tasks the style of the code I am reading makes a difference.
What is referential transparency?
An expression called referentially transparent if we can replace it with its corresponding value without changing program behavior. That two examples below will help you to understand the last sentence:
1. Not a referentially transparent expression:
let x = 10;// ... imagine 100 lines of code between that 2 linesconst z = x + 5; // what is the value of z?
There is no guarantee that x still has a value of 10 at the moment when we define z (since let allows reassignment). So now we need to make an effort to search through 100 lines of code to answer that question “what is the value of z?”.
2. Referentially transparent expression:
const x = 10;// ... imagine 100 lines of code between that 2 linesconst z = x + 5; // what is the value of z?
Here you only need to check the line with the assignment of x to understand the value of z because it is guaranteed by const keyword that the value of x in runtime will be 10 forever. So expression can be replaced with its corresponding value without changing the program’s behavior:
const z = 15;
Note: The topic of referential transparency is much broader and can touch concepts of immutable data structures and pure functions. I deliberately want to focus only on the const vs let part here.
What are the benefits of referentially transparent expressions?
I think you could guess from the previous example that the main benefit is better clarity of your code. People don’t need to suspect any changes in the value of the variable from the moment of assignment, as they usually do with let. That is especially helpful during a code review with partial git diff.
Also, const provides a potential for optimizations at the compiler level.
That is why until you don’t have an intention to mutate your variable use const. If you get used to writing code where you think about variables as not reassignable you will find out that your codebase has less than 1% of real cases for let variables. And don’t be afraid to enable “prefer-const” lint rule in your project.
Some typical cases when people misuse let keyword.
1. Conditional variable assignments
let x;if (isTrue) {
x = 10;
} else {
x = 100;
}
You can easily use a ternary operator here to declare x as const
const x = isTrue ? 10 : 100;
2. Pointless reassignment of a variable
let str = 'cats,love,fish';
str = str.split(',').join(' ');
Don’t be lazy, just create a new const variable with a better name :
const str = 'cats,love,fish';
const transformedStr = str.split(',').join(' ');
3. Poor knowledge of the built-in Array.prototype functions
const result = [];for (let i=0; i < arr.length; i++) {
if (arr[i] % 2) {
result.push(arr[i]);
}
}
No need to have an explicit loop counter here:
const result = arr.filter(element => element % 2);
4. Lack of abstract thinking [an advanced example]
There are however cases when you might need to use let, but you can hide it in an abstract utility function or have it in some library like lodash. Here is a simple example of that:
let isLikeSent = false;// that function likes an article only once
function sendUsersLike() {
if (!isLikeSent) {
isLikeSent = true;
likeAnArticle('anID');
}
}
Let’s rewrite it with lodash once function. It does what we need:
import once from 'lodash/once';// that function likes an article only once
const sendUsersLike = once(() => likeAnArticle('anID'));
Check the next code snippet if you are curious how to implement own function similar to one from lodash. Finally, a valid case for a let declaration:
const once = (func) => {
let isCalled = false;return (...args) => {
if (!isCalled) {
isCalled = true;
func(...args);
}
}
}
Bonus: A couple of words about TypeScript
When TypeScript compiler does type inference it tends to be more precise and efficient if your code has more referentially transparent expressions. Check the next example:
const x = 'a'; // here inferred type of x is a constant 'a' which is subtype of string;function foo(param: 'a' | 'b') {}
function bar(param: string) {}foo(x); // no errors 'a' is one of union type values
bar(x); // no errors, compiler will make type widening
Now let’s see what happens if we declare x as let
let x = 'a'; // here inferred type of x is a string;function foo(param: 'a' | 'b') {}
function bar(param: string) {}foo(x); // error! type string is wider than the union 'a' | 'b'
bar(x); // no errors, because type matches.
But it gets even worse if let is declared without assignment:
let x; // we forgot to declare type, so now x has any type!x = 10; // it doesn't matter what we assign it will remain any// so now your x starts spreading any type epidemy..
Conclusion
So avoiding let in your code ensures that you don’t have involuntary reassignments of variables. It helps people to reason about your code faster. It might give your app performance benefits in the future. TypeScript provides better type inferences. It helps you to write code that is closer to a functional programming style. The only one drawback here is that it requires some effort to change your mind model. But believe me, it’s worth it. | https://medium.com/javascript-in-plain-english/referential-transparency-in-javascript-and-typescript-or-why-to-prefer-const-over-let-9fe241b0a7f3?source=---------5------------------ | CC-MAIN-2020-16 | refinedweb | 935 | 61.87 |
Class BorderImage
- java.lang.Object
- javafx.scene.layout.BorderImage
public class BorderImage extends ObjectDefines properties describing how to render an image as the border of some Region. A BorderImage must have an Image specified (it cannot be null). The.
- Since:
- JavaFX 8.0
Constructor Detail
BorderImage
public BorderImage(Image image, BorderWidths widths, Insets insets, BorderWidths slices, boolean filled, BorderRepeat repeatX, BorderRepeat repeatY)Creates a new BorderImage. The image must be specified or a NullPointerException will be thrown.
- Parameters:
filled- A flag indicating whether the center patch should be drawn
repeatX- The repeat value for the border image in the x direction. If null, defaults to STRETCH.
repeatY- The repeat value for the border image in the y direction. If null, defaults to the same value as repeatX.
Method Detail
getImage
public final Image getImage()The image to be used. This will never be null. If this image fails to load, then the entire BorderImage will be skipped at rendering time and will not contribute to any bounds or other computations.
- Returns:
- the image to be used
getRepeatX
public final BorderRepeat getRepeatX()Indicates in what manner (if at all) the border image is to be repeated along the x-axis of the region. If not specified, the default value is STRETCH.
- Returns:
- the BorderRepeat that indicates if the border image is to be repeated along the x-axis of the region
getRepeatY
public final BorderRepeat getRepeatY()Indicates in what manner (if at all) the border image is to be repeated along the y-axis of the region. If not specified, the default value is STRETCH.
- Returns:
- the BorderRepeat that indicates if the border image is to be repeated along the y-axis of the region
getWidths
public final BorderWidths getWidths()The widths of the border on each side. These can be defined as either to be absolute widths or percentages of the size of the Region,
BorderWidthsfor more details. If null, this will default to being 1 pixel wide.
- Returns:
- the BorderWidths of the border on each side
getSlices
public final BorderWidths getSlices()Defines the slices of the image. JavaFX uses a 4-slice scheme where the slices each divide up an image into 9 patches. The top-left patch defines the top-left corner of the border. The top patch defines the top border and the image making up this patch is stretched horizontally (or whatever is defined for repeatX) to fill all the required space. The top-right patch goes in the top-right corner, and the right patch is stretched vertically (or whatever is defined for repeatY) to fill all the required space. And so on. The center patch is stretched (or whatever is defined for repeatX, repeatY) in each dimension. By default the center is omitted (ie: not drawn), although a BorderImageSlices value of
truefor the
filledproperty will cause the center to be drawn. A default value for this property will result in BorderImageSlices.DEFAULT, which is a border-image-slice of 100%
- Returns:
- the BorderWidths that defines the slices of the image
- See Also:
- border-image-slice
isFilled
public final boolean isFilled()Specifies whether or not the center patch (as defined by the left, right, top, and bottom slices) should be drawn.
- Returns:
- true if the center patch should be drawn
getInsets
public final Insets getInsets()The insets of the BorderImage define where the border should be positioned relative to the edge of the Region. This value will never be null.
- Returns:
- the insets of the BorderImage
equals
public boolean equals:
o-) | https://docs.huihoo.com/java/javase/9/docs/api/javafx/scene/layout/BorderImage.html | CC-MAIN-2021-10 | refinedweb | 586 | 54.32 |
To install the project, simply do:
sudo easy_install hash_ring
Example of usage when mapping keys to memcached servers:
memcache_servers = ['192.168.0.246:11212',
'192.168.0.247:11212',
'192.168.0.249:11212']
ring = HashRing(memcache_servers)
server = ring.get_node('my_key')
Consistent hashing is really neat and can be used anywhere where you have a list of servers and you need to map some keys (objects) to these servers. An example is memcached or a distributed system.
A problem when you use memcached clients is that you map keys to servers in following way:
server = serverlist[ hash(key) % len(serverlist) ]
The major problem with this approach is that you'll invalidate all your caches when you add or remove memcache servers to the list - and this invalidation can be very expensive if you rely on caching.
This problem was solved 10 years ago by David Karger et al and they have published following articles that explain the idea of consistent caching in greater details:
Another motivation is that I am currently looking into building a distributed hash map - and consistent hashing is essential in such a system. Here are a few widely used systems that use consistent hashing:
Consistent hashing is fairly simple (and genius way of distributing keys). It can be best explained by the idea that you have a ring that goes from 0 to some big number. Given a node A, you find a placement for A on the ring by running hash_function(A), the hash_function should generally mix the values well - good candidates for the hash function are MD5 or SHA1. Given a (key, value) pair you find the key's placement on the ring by running hash_function(key). A node holds all the keys that have a value lower than itself, but greater than the preceding node.
Tom White has written a great blog post about consistent hashing, take a look at it, it explains the idea in much greater detail.
I think my Python implementation is beatiful so I will share the full implementation. The code speaks for itself or something:
import md5
class HashRing(object):
def __init__(self, nodes=None, replicas=3):
"""Manages a hash ring.
`nodes` is a list of objects that have a proper __str__ representation.
`replicas` indicates how many virtual points should be used pr. node,
replicas are required to improve the distribution.
"""
self.replicas = replicas
self.ring = dict()
self._sorted_keys = []
if nodes:
for node in nodes:
self.add_node(node)
def add_node(self, node):
"""Adds a `node` to the hash ring (including a number of replicas).
"""
for i in xrange(0, self.replicas):
key = self.gen_key('%s:%s' % (node, i))
self.ring[key] = node
self._sorted_keys.append(key)
self._sorted_keys.sort()
def remove_node(self, node):
"""Removes `node` from the hash ring and its replicas.
"""
for i in xrange(0, self.replicas):
key = self.gen_key('%s:%s' % (node, i))
del self.ring[key]
self._sorted_keys.remove(key)
def get_node(self, string_key):
"""Given a string key a corresponding node in the hash ring is returned.
If the hash ring is empty, `None` is returned.
"""
return self.get_node_pos(string_key)[0]
def get_node_pos(self, string_key):
"""Given a string key a corresponding node in the hash ring is returned
along with it's position in the ring.
If the hash ring is empty, (`None`, `None`) is returned.
"""
if not self.ring:
return None, None
key = self.gen_key(string_key)
nodes = self._sorted_keys
for i in xrange(0, len(nodes)):
node = nodes[i]
if key <= node:
return self.ring[node], i
return self.ring[nodes[0]], 0
def get_nodes(self, string_key):
"""Given a string key it returns the nodes as a generator that can hold the key.
The generator is never ending and iterates through the ring
starting at the correct position.
"""
if not self.ring:
yield None, None
node, pos = self.get_node_pos(string_key)
for key in self._sorted_keys[pos:]:
yield self.ring[key]
while True:
for key in self._sorted_keys:
yield self.ring[key]
def gen_key(self, key):
"""Given a string key it returns a long value,
this long value represents a place on the hash ring.
md5 is currently used because it mixes well.
"""
m = md5.new()
m.update(key)
return long(m.hexdigest(), 16) | http://amix.dk/blog/viewEntry/19367 | CC-MAIN-2015-11 | refinedweb | 700 | 67.25 |
Scripting Java Libraries With JRuby
One of the most powerful features of JRuby (and one that's unique to JRuby) is the fact that you can call out to any Java library as it if were just another piece of Ruby code. In fact, other than a few small details, you might not even realize you're using Java libraries. Today I'll walk through a quick example of "scripting" the MIDI support built into the Java platform.
Accessing Java
Because JRuby always strives to be a solid Ruby implementation first, we don't normally expose nonstandard features like Java integration. That said, it's easy to pull it in... just require the 'java' library:
require 'java'
Alternatively, you can -rjava on the command line. And yes. That's all there is to it. You might want to consider taking a break at this point, so your manager doesn't realize just how simple it was to make this happen. Grab a snack, play some video games, and once you're done with all that hard work, we'll be ready to pull in some Java APIs!
Importing Java Classes
Once you've loaded Java support, all the Java classes that the JVM can see are available to you as though they were normal Ruby classes. You can access them directly:
java.lang.System.out.println "hello, world"
This "package" access works for any Java classes in packages starting with "java", "javax", "org", or "com." In order to avoid polluting the top-level namespace (we actually define Kernel methods for "java", "javax", "org", and "com" to provide this feature), other packages need to be scoped under the Java module:
reader = Java::jline.ConsoleReader.new obj = Java::SomeClassWithNoPackage.new
You can actually "import" these classes in a couple different ways. First, you can simply assign them to a constant:
System = java.lang.System
You can also import them with the "java_import" Kernel method (also available as "import", but that frequently conflicts with libraries like Rake):
# This is basically the same as "JButton = javax.swing.JButton" java_import javax.swing.JButton
Calling Methods
Once you have access to the Java classes, there's really nothing tricky about using them. Call the methods you want to call, and you'll get back the results you'd expect to get:
# display current system ns-granularity timer value puts System.nanos # Java constructors are just Class#new, as in Ruby frame = JFrame.new "My window!" # notice we allow setSize to work as set_size frame.set_size 300, 300 # set* and get* properties work like Ruby attributes frame.always_on_top = true frame.visible = true button = JButton.new "Press me!" frame.add button
A MIDI Keyboard
Ok, let's put it all together using a more entertaining library: Java's MIDI API. The MIDI API is located under the javax.sound.midi package, which contains all the classes you'd need to load, construct, and play MIDI sequences.
In this first MIDI example, we'll listen for a line of text at a time and convert that text into a playable MIDI sequence. First we'll load Java support and import the classes we need:
require 'java' midi = javax.sound.midi import midi.MidiSystem import midi.Sequence import midi.MidiEvent import midi.ShortMessage
Notice I assigned the javax.sound.midi package to the 'midi' local variable in order to shorten the import lines a bit. It's all just objects, after all...
Next up we'll want a simple gets loop with an exit clause:
while (line = gets) !~ /exit/
Ok, now we get to the meat of our app: building a sequence. For every line, we'll construct a new sequence. It's not the most efficient way, but it's nice and simple for now. Then for each character in the sequence we'll add a NOTE_ON event using the character code as the note. Finally we'll add a STOP event to stop playing the sequence.
# Construct a new sequence using 2 beats per quarter note seq = Sequence.new Sequence::PPQ, 2 track = seq.create_track # add each character into track as a note for i in 0...line.length do msg = ShortMessage.new # args here are (message, data1, and data2 according to MIDI spec) # NOTE_ON, character code, and a mid-range note velocity of 64 msg.set_message(ShortMessage::NOTE_ON, line \[i\], 64) track.add MidiEvent.new(msg, i) end # add a STOP to end the track msg = ShortMessage.new msg.message = ShortMessage::STOP track.add MidiEvent.new msg, i + 1
Finally we'll play the sequence and end the loop. There's also a hard JVM System.exit call here, to shut down the internal event threads that MIDI support starts.
# open the sequencer and play the sequence seqer = MidiSystem.sequencer seqer.open seqer.sequence = seq seqer.start end java.lang.System.exit(0)
Give it a try! Here's the full source to our first MIDI script.
Making it More Interactive
Given what we've learned, perhaps we can make our MIDI keyboard app a little more interactive. Ideally we'd like it to respond to keystrokes live,turning the note on when the key is pressed and turning it off when the key is released. For that, we'll launch a GUI window to receive keystroke events.
Our preamble this time only imports three classes, since we won't be constructing sequences this time.
# MIDI keyboard take two! require 'java' import javax.sound.midi.MidiSystem import javax.swing.JFrame import java.awt.event.KeyListener
In order to make this interactive, we're going to access the system synthesizer directly. Here we retrieve the default synthesizer, open it, and grab its channel number 0:
# Prepare the synth, get channel 0 synth = MidiSystem.synthesizer synth.open channel = synth.channels \[0\]
There are a few ways to receive keystroke events directly at the command line, but a lot of them are system-specific or require special libraries. For simplicity, we'll launch a GUI frame and just set it up to receive keystroke events.
# Prepare a frame to receive keystrokes frame = JFrame.new("Music Frame") frame.set_size 300, 300 frame.default_close_operation = JFrame::EXIT_ON_CLOSE
Here we're going to use another feature of JRuby: implementing an interface using a block of code. Every Java interface has a class method "impl" that receives a block and produces an object that implements that interface using the given block. The block itself is called for every interface method, receiving the name of the method and the original arguments as parameters.
In this case, we're going to handle the keyPressed and keyReleased methods on the KeyListener interface by turning notes on and off, again using the character code as the note:
# Listen for keystrokes, play notes frame.add_key_listener KeyListener.impl { |name, event| case name when :keyPressed channel.note_on event.key_char, 64 when :keyReleased channel.note_off event.key_char end }
And finally, we'll show the frame to get the whole thing started:
# Show the frame frame.visible = true
Here's the source for our MIDI keyboard.
Using JRuby, a whole new world of libraries are at your fingertips, and you never have to write a line of Java code. This is just one use case, but there really are an unlimited number of great ways JRuby allows you to leverage technologies that are otherwise out of the picture for Rubyists.
In the coming weeks and months we'll be working on a series of posts about how you can use JRuby, why we love it, and what you can look forward to in the future. If you've got a hankering for something specific, leave a comment—we aim to please :D
Share your thoughts with @engineyard on Twitter | https://blog.engineyard.com/2009/scripting-java-libraries-with-jruby | CC-MAIN-2015-14 | refinedweb | 1,285 | 66.74 |
Let's take React Tic-Tac-Toe example by someone named D Abramov. He must be somewhat important person, since this example was included in the React Tutorial. You can find my version of the game at bahmutov/react-tic-tac-toe-example.
The project uses
react-scripts to bundle and serve the application. The application itself only has 3 files in the
src folder
The application file
src/app.jsx has a few components: Square, Board, Game and a function
calculateWinner.
E2E vs component tests
Usually, I consider end-to-end tests the most effective way to confirm the application works. The Cypress test interacts with the loaded application like a real user, and any error in its logic, code, bundling, or deployment is likely to be caught.
The tests are nice, but what if we want to concentrate on the
Square component? Maybe we want to refactor it, maybe we want to see how it looks with different styles or props, there could be lots of reasons we want to really stress this component in isolation from the main application.
Component tests
By adding cypress-react-unit-test to the repo we can easily write component tests. Let's confirm the
Square component shows the value passed via a prop. For now we can simply export
Square from the
app.jsx and import it in the test file, and we can place the spec file alongside the component.
We import the component and mount it, and then use Cypress commands to interact with the live component. Let's confirm it calls the passed prop on click. Ordinarily one would write a new unit test to separate the value test from the click test. But Cypress has built-in time traveling debugger, records movies on CI, takes screenshots on failures - you don't need to make component tests tiny just to have a good debugging experience. So I will continue expanding the same test.
The test passes.
Styles
The square component looks like a regular button, not like a board cell in the real game. This is because we only mounted the markup and never applied any styles to it. There are multiple options for styling components during tests, but the simplest is just to import the application's CSS from the spec file.
We can
import './app.css' because the specs are bundled using the same Webpack config as the application; if you can import a resource from the application code, you should be able to import it from the component test file.
Mocking imports
We have passed cy.stub to the component. This stub comes from Sinon.js included with Cypress. It works great when stubbing individual functions or a method on an object. But what about mocking ES6 module exports and imports?
The game component determines the winner by calling
calculateWinner function. The exact details are unimportant, but the code around it looks like this:
From the component test, we cannot reach and overwrite a private function
calculateWinner. But we could move it into an external module and import it.
Now let's write a component test for the
Game component - and mock the ES6 module import.
The test passes - note how
Winner: X is immediately displayed, even before the first move is played 😀
Unit tests
We can write more end-to-end and component tests, using built-in code coverage as a guide. But what about the above function
calculateWinner? Do we only indirectly test it via component tests? No. We should also directly test it using unit tests.
We exercise different data inputs rather than code paths to make sure the function works correctly. The tests do not have a GUI, but the Command Log still shows useful information.
If there is an error, the code frame immediately shows the problem. For example if we change the last assertion to
)).to.equal(x) we get the precise source code location
More info
For more reasons behind component testing, read My Vision for Component Tests blog posts, and visit the cypress-react-unit-test repo. | https://glebbahmutov.com/blog/tic-tac-toe-component-tests/ | CC-MAIN-2020-29 | refinedweb | 680 | 65.01 |
« Return to documentation listing
MPI_Comm_spawn - Spawns a number of identical binaries.
#include <mpi.h>
int MPI_Comm_spawn_ERRORCODES(*),).
intercomm Intercommunicator between original group and the newly
spawned group (handle).
gram specified by command, establishing communication with them and
returning an intercommunicator. The spawned processes are referred to
as children. The children have their own MPI_COMM_WORLD, which is sepa-
rate par-
ents work-
ing directory of the spawning process.
The argv Argument
argv is an array of strings containing arguments that are passed to the
program. The first element of argv is the first argument passed to com-
mand,. Specifi-
cally, argv[0] of main contains the name of the program (given by com-
mand).
in C++ and INTEGER in Fortran. It is a container for a number of user-
speci ed (key,value) pairs. key and value are strings (null-terminated
char* in C, character*(*) in Fortran). Routines to create and manipu-
late the info argument are described in Section 4.10 of the MPI-2 stan-
dard.
For the SPAWN calls, info provides additional, implementation-dependent
instructions to MPI and the runtime system on how to start processes.
An application may pass MPI_INFO_NULL in C or Fortran. Portable pro-
grams not requiring detailed control over process locations should use
MPI_INFO_NULL.
The following values for info are recognized in Open MPI. (The reserved
values mentioned in Section 5.3.4 of the MPI-2 standard are not imple-
mented.)
Key value Type Description
---------- ---- -----------
host char * Host on which the process should be spawned.
wdir char * Directory where the executable is located..
Completion of MPI_Comm_spawn in the parent does not necessarily mean
that MPI_Init has been called in the children (although the returned
intercommunicator can be used immediately).pirun(1)
Open MPI 1.2 September 2006 MPI_Comm_spawn(3OpenMPI) | http://icl.cs.utk.edu/open-mpi/doc/v1.2/man3/MPI_Comm_spawn.3.php | CC-MAIN-2014-10 | refinedweb | 295 | 51.65 |
Submitted by virtualmin3123 on Wed, 07/16/2014 - 07:25
Dear support,
I just upgraded from 12.04 to 14.04. And... it fails. I used the advised manual from:
My mail users can now no longer receive their mail. I got the following error: Jul 16 13:54:43 SYSNAME dovecot: imap(user.domain.tld): Error: user user.domain.tld: Initialization failed: namespace configuration error: inbox=yes namespace missing Jul 16 13:54:43 SYSNAME dovecot: imap(user.domain.tld): Error: Invalid user settings. Refer to server log for more information.
Please help.
Thanks
Status:
Active
Submitted by virtualmin3123 on Wed, 07/16/2014 - 09:00 Comment #1
Submitted by virtualmin3123 on Wed, 07/16/2014 - 09:05 Comment #2
I now added the following manually to my dovecot.conf in the /etc/dovecot folder:
namespace inbox { inbox = yes }
Should I do this? It seems to work. I have had an original Virtualmin setup (4 month old!) and upgraded tot 14.04 and this happens. You should add this to the upgrade document as this actually causes a serious issue for the continuity of our clients.
Please respond AND please advise.
Submitted by andreychek on Wed, 07/16/2014 - 09:17 Comment #3
Howdy -- after adding
namespace inbox { inbox = yes }, did that correct the problem you were seeing? And you're able to receive email now?
Submitted by virtualmin3123 on Wed, 07/16/2014 - 09:41 Comment #4
Yes, this solved the problem but is not a charming solution.
Submitted by andreychek on Wed, 07/16/2014 - 10:03 Comment #5
Googling for the error you received, it looks like you're not the only one to get that error upon upgrading Dovecot, and your solution is the best one.
I'll do some research to see if that line you added needs to be put in there every upgrade, or only in some cases; once I figure that out we'll update the Ubuntu upgrade documentation.
Submitted by virtualmin3123 on Wed, 07/16/2014 - 14:37 Comment #6
Don't forget I'm running the default Virtualmin configuration. This should not happen at all.
Is there new a namespace inbox programming code (statement) which did not existed in the ubuntu 12.04 version of Dovecot? On all questions a for Keeping or replacing the configuration I answered to KEEP (default) it. Then you probably should advise UPDATERS to replace these "aged" configurations is it?
I'm now unsure if it was wise to keep the advise for KEEPING these configuations for Dovecot. please advise.
Submitted by andreychek on Wed, 07/16/2014 - 15:17 Comment #7
Overwriting the configs is usually bad, and will wipe out any changes that have been made by both the sysadmin, as well as by the Virtualmin installer. That's much harder to fix than adding the line that you added :-)
If we're able to reproduce the issue you saw in our testing, what we'll do is just update the upgrade documentation, and have sysadmins add that line.
Any time you see that issue, that's the best fix -- just add in the line it was asking for.
Submitted by virtualmin3123 on Wed, 08/06/2014 - 07:50 Comment #8
I noticed that after the upgrade from 12.04 tot 14.04 my PHP is not working. I tried to reinstall PHP using APT but this does not work. What should I do? Please help.
Submitted by andreychek on Wed, 08/06/2014 - 10:01 Comment #9
What happens when trying to execute a PHP script? Do you receive an error of some sort?
Also, what is the PHP execution mode set to for domains experiencing this problem?
Submitted by virtualmin3123 on Thu, 08/07/2014 - 03:54 Comment #10
If I run a PHP script the browser will display the sourcecode/script of the PHP page.
Submitted by andreychek on Thu, 08/07/2014 - 09:52 Comment #11
That problem can be caused by a "SetHandler" line in Apache's PHP config.
If you go into System Settings -> Re-Check Config, does it detect any problems? If it's a SetHandler issue it should be able to detect that.
Submitted by virtualmin3123 on Mon, 08/11/2014 - 16:35 Comment #12
Thanks but I do not get this warning (except the all time warning from a not running antivirus deamon).
It seems that PHP (roundcube) is working for all other domains except but one specific domain. I replaced the php.ini in the /home/domain.tld/etc/php/ with the one from a working domain but this does not make any difference. Any other suggestions?
Thanks in advance.
Submitted by andreychek on Mon, 08/11/2014 - 17:08 Comment #13
What is the PHP execution mode set to for domain(s) experiencing this problem?
Submitted by virtualmin3123 on Mon, 08/11/2014 - 17:24 Comment #14
Okay guys. I did it the long way.... I replaced my domain.tld.conf in /etc/apache2/sites-available/ with a backup of this config file from a year ago. As my IP changed and SuexecUserGroup setting I updated these with the old settings for the 80 and 443 virtualhost in the file. This seems to work. I think a inconsistent config file (with too many old and no longer operational) statements in the config file caused this issue. This is not an error of Virtualmin.
Would it not be possible/feasible to create a "regenerate config file" option in virtualmin to make it possible to restore a default config file for a selected domain? Looking forward to your answer.
[Solved]
Submitted by andreychek on Mon, 08/11/2014 - 17:32 Comment #15
One way to do that would be to go into Edit Virtual Server -> Enabled Features, and then disable the "Apache website enabled" option. Save that, then go back in and re-enable it.
After disabling, then re-enabling, that particular option, it would regenerate the Apache config for that domain.
Would that do what you're after?
Submitted by virtualmin3123 on Mon, 08/11/2014 - 18:08 Comment #16
Yep, but without you telling me this now, I could not easily know this. The only way is to do this is on trail en error and that is time consuming.....
Now you told me I know.
Reason for my answer is that by default the config file on ubuntu will not be deleted unless you explicitly tell ubuntu to do so......
Submitted by techforce on Fri, 08/15/2014 - 13:32 Comment #17
Im having the same kind of problems. The upgrade for Ubuntu prompted many times to overwrite or keep existing config files....and since the problems mostly seem config files, I guess in hindsight we were suppose to overwrite them....not keep them by default.
After I rebooted, somehow Webmin /Vmin defaulted to an older version. There were upgrade options, and options to detect the new Ubuntu version, which I did, but apparently this was unwise. | https://www.virtualmin.com/node/33722 | CC-MAIN-2020-40 | refinedweb | 1,167 | 65.62 |
Tax
Have a Tax Question? Ask a Tax Expert
Why was there no probate, was the property held as joint tenants? Could you explain more? Some types of IRD (like a 401(k)) might be subject to double taxation and reported on both the estate return (if possible) and the beneficiaries returns as income (estate gets the income and then deduction for taxes it pays, net cash then flows to beneficiary as taxable income, depending). However, other income (IRD) could flow directly to the beneficiary if the asset (rental property) was inherited or other agreements in place. This all gets a little complicated based on timing, types of assets, how assets were titled, etc.
...
However, there should have been a step up in basis of the rental property going into the estate; or to the other owner (joint tenant of so titled). Then if sold shortly thereafter, there should not be much of a gain (again depending on how titled and step up basis laws), if any at all, as the step up should have been to FMV (at time of death as reported on the 706); the exception being if substantial time has lapsed between the step up date and the sale.
First part, because the asset was held solely in his name, rental income after death (date of death as reported on the 706) should just be reported as income to the beneficiaries. Technically, this is not IRD; that term is used for income earned but received after death (deceased sold a a car but didn't receive the check until after death). The rental income earned in your case is after death and therefore income of those whom inherited the property. Second, the new basis should have been reported on the final return (706 Schedule A or F) and that is the inherited basis. I cannot imagine any significant change in value between death and the closing of the sale 6 months later. Accordingly, there should not be any capital gain.
I hope that answers your question, let me know if you need more information.. | https://www.justanswer.com/tax/aey71-tenn-ird-rental-income-non-probated-tn-does-pass.html | CC-MAIN-2017-39 | refinedweb | 348 | 64.95 |
using namespace std;it brings heaps of stuff into the global namespace, polluting it, potential causing conflicts with other namespaces. It is easier on the compiler if you only refer to the specific things you need. There are several options:
using namespace std;
using namespace std;and put std:: before each std thing throughout the code.
GenerateRandomNumber
GenRandNum
int Numbers[6] = {0};
int Numbers[6] = {0,0,0,0,0,0};
int loop_count = {0};
int LoopCount = 0;
while (sort_needed==true); // But only sort, if rquired
pointer = &Array[0];
pointer = Array;
All the code I have seen with the 1d solution seems to have long lists of if else's to cover all the number combinations. | http://www.cplusplus.com/forum/beginner/82323/ | CC-MAIN-2016-40 | refinedweb | 115 | 53.75 |
Announcements
SutayhMembers
Content count14
Joined
Last visited
Community Reputation173 Neutral
About Sutayh
- RankMember
Designing a "quest" system for top down 2d rpg
Sutayh replied to BaneTrapper's topic in For Beginners".
99 Bottles Of Beer Challenge With Least Amount Of Characters ?
Sutayh replied to RLS0812's topic in Coding HorrorsJust throwing my hat in the ring, though it's not the shortest: #include<iostream> #include<sstream> using namespace std; string m="o more",v=" bottle",t=" of beer",s=" on the wall"; string a(int n,int c=0) { stringstream b; b << n; return (n?b.str():(c?"N":"n")+m)+(n==1?v:v+"s"); } int main() { for(int l=99;l>-1;--l) { cout << a(l,1)+t+s+", "+a(l)+t+".\n"+(l?"Take one down and pass it around, ":"Go to the store and buy some more, ")+(a(l?l-1:99))+t+s+".\n\n"; } } 370 characters, 332 without "any" whitespace.
Mountain climbing game name ideas
Sutayh replied to weetabix's topic in Game Design and TheoryApex Reach
Hardest game as a child, still hard as an adult?
Sutayh replied to Mayple's topic in GDNet LoungeI started with all of the old NES games I couldn't beat or always wanted to play recently, too. I must be one of the few people who had no problems with the water level in TMNT. Aside from Battletoads, already mentioned, my NES gaming kryptonite was Ghosts and Goblins. Wow did that game suck. It was one of those where you'd finally get all the way to the end(still haven't done it without either save states or level select) and you'd get the "our princess is in another castle" deal. It was totally a game that was difficult for the sake of being difficult.
Short attention span + programming = not good
Sutayh replied to SeeForever's topic in For BeginnersThe #1 thing to do to stay focused is write a to-do list. At least when you're getting bored of doing something it makes it easier to go back into it later. It prevents phrases uttered like: "What the hell was I on a month ago?" #2 helps #1 out. ALWAYS DOCUMENT YOUR CODE! Sure it's tedious and you may never look at this lame swapxy function again. But...in case you need to make sure what you've done is working or is causing problems with your new function after you haven't looked at code in forever, there you go. It's tough to stay focused, especially when you have 8 billion behind-the-scenes engine things to do that don't really have a good way to show you the results of your labor until later. It wouldn't hurt to write a little debug insert that outputs things to a text file. Timestamps are great for optimizing. Really, just anything that says: "This function works...I'm awesome" will keep you interested longer. Remember, the more you document what you're trying to accomplish the easier it will be to keep interest.
C++ version control system for Visual Studio
Sutayh replied to Desperado's topic in General and Gameplay ProgrammingI'll second the VisualSVN. I use TortoiseSVN with it. Awesome combo and easy to set up.
OpenGL is dying? No! Windows is dying!!
Sutayh replied to superoptimo's topic in GDNet LoungeThe mojave experiment is lame. They probably use a $3,000 laptop to have them try Vista on. Sure, it'll run with 4gigs of ram for things most users do. Ever try to change permissions and crap? POS Our XP at work is flawless for what we do. Our Vista is slow and incompatible with half of our devices(at least without screwing stuff up).
combining an rpg with a tbs wargame
Sutayh replied to ncsu121978's topic in Game Design and TheoryYou should really check out the Advance Wars games for the GBA/DS/GameCube. They have an interesting take on handling this kind of stuff. | https://www.gamedev.net/profile/137928-sutayh/ | CC-MAIN-2017-34 | refinedweb | 671 | 72.87 |
So how exactly does Linux determine the following PID it'll use for any process? The objective of this would be to better comprehend the Linux kernel. You shouldn't be afraid to publish kernel source code. If PIDs are allotted sequentially so how exactly does Linux complete the gaps? What goes on if this hits the finish?
For instance basically operate a PHP script from Apache that does a
<?php print(getmypid())?> exactly the same PID is going to be printed out for any couple of minutes while hit refresh. This time period is really a purpose of the number of demands apache gets. Even when there's just one client the PID will ultimately change.
Once the PID changes, it will likely be a detailed number. however , how close? The amount doesn't seem to be entirely consecutive. Basically perform a
ps aux grep apache I recieve a reasonable quantity of processes:
So how exactly does Linux choose this next number? The prior couple of PID's continue to be running, along with the newest PID which was printed. So how exactly does apache decide to reuse these PIDs?
I'd rather assume the behaviour you watch comes from another source:
Good web servers will often have several process instances to balance the burden from the demands. These processes are handled inside a pool and designated to some certain request every time a request is available in. To optimize performance Apache most likely assigns exactly the same process to a lot of consecutive demands in the same client. After some demands that process is ended and a replacement is produced.
I do not believe which more than one processes in sequence are designated exactly the same PID by linux.
While you state that the brand new PID is gonna bond with the final one, I suppose Linux simply assigns each process the final PID + 1. But you will find processes appearing and being ended constantly in background by programs and system programs, thus you can't predict the precise quantity of the apache process being began next.
Aside from this, you need to not use any assumption about PID assignment like a base for something you implement. (See also sanmai's comment.)
The kernel allocates PIDs in the plethora of (RESERVED_PIDS, PID_MAX_DEFAULT). It will so sequentially in each namespace (tasks in various namespaces can have a similar IDs). Just in case the number is exhausted, pid assignment systems around.
Some relevant code:
Inside alloc_pid(...)
for (i = ns->level i >= i--)
alloc_pidmap()
static int alloc_pidmap(struct pid_namespace *pid_ns)
Do observe that PIDs poor the kernel are not only
int identifiers the appropriate structure are available in
/include/linux/pid.h. Aside from the id, it consists of a listing of tasks with this id, a reference counter along with a hashed list node for immediate access.
The reason behind PIDs not showing up consecutive in user space happens because kernel arranging might fork a procedure among your process'
fork() calls. It is extremely common, actually.
PIDs are consecutive. You can observe that by beginning several processes on your own on idle machine.
PIDs could be allotted at random. There's various ways to complete that. | http://codeblow.com/questions/so-how-exactly-does-linux-determine-the/ | CC-MAIN-2018-09 | refinedweb | 536 | 65.22 |
At the conference Directions EMEA 2009, I did a session on Dynamics NAV and SharePoint. In that session I showed a short demo on how you can show Dynamics NAV data in SharePoint, using the Business Data Catalog feature. You can see more about the conference at
Here I would like to walk through the steps to do the demo, so you can try this out as well. I think it is a quite simple way to enable SharePoint users to access the data that is in your Dynamics NAV system.
This first part of the walkthrough will show how you build the Web Service and Application Definition File for SharePoint. The second part will show how you can then use this in SharePoint.
Step 1: Creating the NAV 2009 Web Service
The first step is to create a NAV 2009 Web Service to expose the data that you want. In our example we will expose Customer Data.
Creating a Web Service in NAV 2009 is really simple. In the Classic Client, open the Web Service Form. It is found under “IT Administration->General Setup->Web Services”
In the Web Services Form, you add a line with Page 21, call the Service “Customer” and set a checkmark in the Published Column. This will create a Web Service, exposing all the Fields on Page 21 “Customer Card”. If you want to expose other fields, you can create a specific Page for that, but for my example I have just used the standard Customer Card Page
Before you can try the new Web Service, you need to make sure that the “Microsoft Dynamics NAV Business Web Services” service is started on the machine. In a default installation this service is not started automatically, so you might want to set the Startup Type to Automatic as well.
Now you can actually try out your new Web Service. The default URL for the Web Service is:
If you want to know more about NAV 2009 Web Services, then you can try out some of the Web Services Walkthroughs in the C/SIDE Reference Guide Online Documentation.
Step 2: Creating a new BDC compatible Web Service
The Web Service that you have just created does unfortunately not have the right format for the SharePoint Business Data Catalog, so you need to create a new Web Service that Business Data Catalog understands, and then from that call the NAV 2009 Web Service.
In Visual Studio (I used VS 2005), create a new ASP.NET Web Service Application, called NavBdcWebService
Rename the Service1.asmx file to NavBdcWebService.asmx, and call the Web Service class for NavBdcWebService. Also remember to update the reference in the .asmx file to the new name of the class. To edit that file, right click the NavBdcWebService.asmx file in the Solution Explorer and select “View Markup”
<%@ WebService Language="C#" CodeBehind="NavBdcWebService.asmx.cs" Class="NavBdcWebService.NavBdcWebService" %>
In order to access the NAV 2009 Web Service from your new Web Service, you need to add a Web Reference to the NAV 2009 Web Service.
In the menu, select “Project->Add Web Reference…” and specify the URL for the NAV 2009 Web Service called Customer:
Give the Web Reference the name “NavCustomer” to avoid conflicts with the Customer Class there, and click “Add Refernce”:
Now replace all the code in NavBdcWebService.asmx.cs file with the following:
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Collections.Generic;
using NavBdcWebService.NavCustomer;
namespace NavBdcWebService
{
/// <summary>
/// MOSS BDC Compatible Webservice for getting NAV Data
/// </summary>
[WebService(Namespace =)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class NavBdcWebService : System.Web.Services.WebService
{
/// <summary>
/// Finder method for finding Customers
/// </summary>
/// <param name="no">Filter parameter for the Customer No.</param>
/// <param name="name">Filter parameter for the Customer Name</param>
/// <param name="noOfRecordsToReturn">Number of Customers to return</param>
/// <returns>Array of Customer objects, with all the fields on a Customer</returns>
[WebMethod]
public Customer[] CustomerFinder(string no, string name, int noOfRecordsToReturn)
{
Customer_Service service = new Customer_Service();
service.UseDefaultCredentials = true;
service.Url =;
List<Customer_Filter> filters = new List<Customer_Filter>();
if (!string.IsNullOrEmpty(no))
{
Customer_Filter filter = new Customer_Filter();
filter.Field = Customer_Fields.No;
filter.Criteria = no;
filters.Add(filter);
}
if (!string.IsNullOrEmpty(name))
{
Customer_Filter filter = new Customer_Filter();
filter.Field = Customer_Fields.Name;
filter.Criteria = name;
filters.Add(filter);
}
return service.ReadMultiple(filters.ToArray(), null, noOfRecordsToReturn);
}
}
}
The code simply adds a Web Method called CustomerFinder. This is the Method that Business Data Catalog will use to get data.
The Method takes two Filter Parameters “no” and “name”. For this example I have chosen only to enable filtering on those two fields, but you can add other fields as well. Business Data Catalog supports up to a total of 30 parameters to the Finder Method.
The third parameter called “noOfRecordsToReturn” is used by Business Data Catalog to limit the number of records to look for within the filter. This protects your service from excessive unfiltered requests from the SharePoint users.
The Method simply adds the two filters to a Filter List, and calls the ReadMultiple Method on the NAV 2009 Web Service, passing the Filter List and the noOfRecordsToReturn parameter.
The Method returns an array of Customer Objects as defined by the NAV 2009 Web Service.
The new Web Service is now done, and you should try it. Simply run the web service from Visual Studio, and invoke the CustomerFinder Method with the parameters no=10000 and noOfRecordsToReturn=1
You should now get an XML document with the Customer data for the Customer 10000 – “The Cannon Group PLC”
You can now deploy the new web service, but for the walkthrough we will just stay with the Service running on the ASP.NET Development Server in Visual Studio. Just make sure that the Web Service is running in Visual Studio. The name of the new Web Service will then be (Your port number might be different):
Step 3: Creating the BDC Application Definition File
In order to tell BDC (Business Data Catalog) how the Customer Entity is structured, we need to create an Application Definition File. This is an XML file, but creating it manually is not trivial, so we will use the Business Data Catalog Definition Editor that come as part of the SharePoint Server 2007 SDK:
In the Business Data Catalog Definition Editor, Add a new LOB System. We want to connect to a Web Service, so specify the URL for the NavBdcWebService that you just created:
Click Connect, and drag the CustomerFinder Method into the Design Surface
Click OK, and name the System NavLobSystem.
The Business Data Catalog Definition editor has now imported the information from the Web Service, but unfortunately there are a number of manual steps that you need to do to set this up properly. When you have done this for this Entity (Customer) it is pretty easy to do the same for an additional Entity.
Set the Version of NavLobSystem to “1.0.0.0” and WildcardCharacter to “*”
Also rename the Entity to be called “Customer”.
Adding an Identifier for the Customer
In order to identify an Entity in the Business Data Catalog, you need to add an Identifier. Call the Identifier “No”, and leave the default datatype to System.String:
Defining Filters for the CustomerFinder Method
We have already imported most of the data for the CustomerFinder Method, but we need to define the Filters for the two filter parameters No and Name. Create both of them as WildcardFilter
In order to limit the number of records to search for, you should also create a Filter called Limit of type “Limit”:
Defining Parameters for the CustomerFinder Method
We also need to do a little extra work on the parameters of the CustomerFinder Method
For the parameter called “no”, set FilterDescriptor to the Filter we just created called “No” and Identifier to the identifier we just created: “No[Customer]”
For the parameter called “name”, set FilterDescriptor to “Name” and leave the Identifier blank
For the parameter called noOfRecordsToReturn, set the FilterDescription to “Limit” and leave the Identifier blank.
For the “No” field of the returned Item (CustomerFinder->Parameters->Return->Return->Item->No), also set the Identifier to “No[Customer]”
Defining the Method Instances
In order for the BDC to call the Finder Method, we need to define a number of different Method Instances.
An Enumerator
A Finder
A Specific Finder
The first one is of type idEnumerator. It can return all the Identifiers for the Customers. Call this Method Instance “GetCustomerIDs”
You can actually try this Method Instance in the Business Data Catalog Definition Editor. Simply click “Execute” and “Next” on the form that opens. You should now get a list of Customer IDs:
The second Method Instance is of type SpecificFinder, and it can find an Entity for a specific Identifier. Call this Method Instance “FindCustomer”
The last Method Instance is of type Finder, and it is used to return multiple Entities. Call this Method Instance “FindCustomers”
You can also test the two other Method Instances directly in the Business Data Catalog Definition Editor. Click Execute on each of them to validate that they work as expected.
FindCustomer should return a single Customer when specifying a Customer No
FindCustomers should return a list of Customers within the filter specified
Note: The result page has a lot of fields, so it is difficult to see exactly which Customers is returned. You can expand some of the columns to see more of the content.
Adding Display Names for the Parameters and returned Fields
By default the display name will be the same as the field name. For some of the fields, this is not nice, because it contains underscores instead of spaces. You can specify a different Display name for each of those, so it looks nicer for the user.
Export the Application Definition File to an XML file
Finally you export the Application Definition File to an XML file that can later be imported into SharePoint Business Data Catalog.
If you later make changes to the Definition File, then remember to increment the Version Number. This will allow BDC to update existing definitions.
To be continued…
This completes the first part of this walkthrough. The second part will show you how you can then use the Web Service and Application Definition File in SharePoint.
Thanks
/Bugsy
PingBack from
This is the second part of the walkthrough, showing how you can show your Dynamics NAV Data in SharePoint.
This article has been a great help, as there is so little information out there on this subject. At least none that I've been able to find!
I'm working with SharePoint 2010 and so only the first half of this article works for me, once I get to the point of building the Dubiness Data Connection Model it doesn't apply. Although I'm able to use the Application Definition Designer, the resulting output is not compatible with SP2010. I've tried finding articles on creating a BDC Model for a web service but haven't found anything I can really use.
Do you know if there is a similar tool for SP2010 available, as it no longer exists within the new SDK
Thanks
Andy | https://blogs.msdn.microsoft.com/pchriste/2009/04/14/showing-nav-data-in-sharepoint-using-business-data-catalog-part-1-of-2/ | CC-MAIN-2019-47 | refinedweb | 1,880 | 52.49 |
ReactVR/react-360 Is Great, but Maybe Not Quite There Yet
ReactVR/react-360 Is Great, but Maybe Not Quite There Yet
While it's not perfect yet, it's still pretty dang cool. Read on to learn how to get started making VR apps with this React library!
Join the DZone community and get the full member experience.Join For Free
My goal was to build a 3D scatterplot that you can explore. Stand inside your data and look around.
Wouldn't that be cool?
Instead, I got a squished Baymax healthcare companion...
ReactVR, recently renamed to react-360, doesn't have 3D modeling primitives like spheres and boxes. Instead, it asks you to import 3D models and build your scenes with that.
The base example is a 3D viewer of models from Google's Poly library.
And that works great:
You can import a model, display it with a React component, and look around using VR goggles and the Oculus browser. Just gotta make sure there's a URL that shows your VR app.
To Display a 3D Model...
To display a 3D model in VR space, you put it in a react-360
<View> component, add some light, and an
<Entity>.
class Baymax extends React.Component { render() { return ( <View> <AmbientLight intensity={1.0} <PointLight intensity={0.4} style={{ transform: [{ translate: [0, 4, -1] }] }} /> <Entity source={{ obj: baymax }} style={{ transform: [{ scaleX: 0.05 }, { scaleY: 0.05 }] }} /> </View> ); } }
Lighting doesn't do much in my
<Baymax> example. I'm not sure why. Maybe because the whole model is white?
Where it gets interesting is the scale transformation. In theory, you can scale your models on all 3 axes. In practice, the
scaleZ transform is currently not implemented and throws an error. Even though it's in the docs. Oops.
But I guess that's the problem with models you import from the web because you don't know how to make your own. Their scales are out of whack.
The Baymax model, for example, looks great when it's 200 meters away. Yes, units for all vectors in ReactVR and react-360 are in meters. Love it.
Baymax 200 meteres away head on
To Oosition a react-360 View
Positioning react-360 views happens through something they call roots. You can think of it as an anchor point for your components that you build on top of.
This goes in your
client.js and you can have as many roots as you need.
r360.renderToLocation( r360.createRoot("Baymax"), new Location([0, -30, -200]) );
Location is a 3D vector based off of the user's position. In this case, that's
0 meters to the left or right,
30 meters down, and
200 meters back. Go
200 meters in the other direction, and your user has to turn their head to see your scene.
And that's where react-360 starts to shine. 360 degrees on 3 axes is a lot of space to play around with. Seriously. A ton of space. You can't even imagine until you start to play around.
react-360 Shines at Placing 2D Views in 3D Space
What I believe react-360 is truly optimized for is putting 2D panels in 3D space and giving your users more room to use different controls.
It's kind of a shame that this is the case, but there's a lot you can do with 2D in 3D. Imagine a data dashboard for your infrastructure that uses full 3-axis 360 views to place charts all around you instead of trying to squish everything into a small browser window.
I don't know about you, but I always run out of space when making monitoring dashboards!
Code looks just like React Native by the way. You have
<View>s and
<Text>s and
<Image>s and
<VrButton> s. You put them together and voila, an interface.
This builds that panel on the left:
const TopPosts = props => { if (!props.posts) { return ( <View style={styles.wrapper}> <Text>Loading...</Text> </View> ); } return ( <View style={styles.wrapper}> <Text style={styles.postButtonName}> Posts: {props.posts.length} </Text> {props.posts.map((post, i) => ( <PostButton key={post.id} index={i} name={post.name} author={post.author} preview={post.preview} /> ))} </View> ); };
Take a list of posts from Google's Poly store, render a
<View>, put some
<Text> inside to know the count, then iterate through the data and render a
<PostButton> for each entry.
The
<PostButton> component is a
<VrButton> that gives us clickability and callbacks. It contains an image and two text labels. Pretty neat.
You place the panel in 3D space with a root, a surface, and a render to surface.
const leftPanel = new Surface(300, 1200, Surface.SurfaceShape.Flat); leftPanel.setAngle(-0.6, 0); r360.renderToSurface(r360.createRoot("TopPosts"), leftPanel);
The extreme 1,200 height doesn't look so great in a web browser, but works great in VR goggles because you can look up and down.
360 degree really is a lot of room for activities. Really. Wish I knew how to record what I can see inside my goggles.
Fin
There's a lot of potential here. In production mode, react-360 is fast enough to avoid nausea; in dev, not so much. The engineering UX is similar to React Native, and VR is growing like crazy.
You might not realize it, but there's a lot of VR users out there. 171,000,000 according to statista. Similar to the web in 1999.
Now's the time to start playing around.
Watch me build the squished Baymax and preorder React + D3 2018, likely the first React book/course to include VR stuff:
Published at DZone with permission of Swizec Teller , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/reactvrreact-360-is-great-but-maybe-not-quite-ther | CC-MAIN-2019-51 | refinedweb | 979 | 76.52 |
04 December 2007 18:06 [Source: ICIS news]
TORONTO (ICIS news)--The Bank of Canada on Tuesday lowered its target for the overnight rate by 0.25 percentage point, to 4.25%, because of the impacts of the US subprime mortgage crisis and the high Canadian dollar (C$) on the country's economy.
?xml:namespace>
Global financial market troubles, triggered by the ?xml:namespace>
Canadian exports were at risk as the outlook for the
It also noted the strong Canadian dollar vis-à-vis the US dollar.
The Canadian dollar spiked at well over parity last month but has since then fallen back to around parity with the US dollar.
Following the bank’s announcement, the Canadian dollar was down 1.24 US cents, to 98.78 cents on Tuesday morning.
The bank had come under intense pressure in past months to cut rates against a backdrop of plant closures and mounting job losses in the manufacturing sectors - including plastics and | http://www.icis.com/Articles/2007/12/04/9084141/canada-cuts-rates-due-to-us-crisis-c-strength.html | CC-MAIN-2014-35 | refinedweb | 161 | 64.81 |
I've recently acquired P3B+ and migrating existing code onto that platform and I'm encountering a pile of problems recompiling. I'm not sure if it's the toolchain, the compiler or the linux environment that is causing the issue.
I've installed libpthread-stubs0-dev on the pi.
I've using VIsual Studio to cross-compile with VisualGDB / Cygwin / arm-linux-gnueabihf toolchain and this code has worked for years on older PIs.
The new one however, doesn't seem to like PTHREADS and is failing to compile with a
errorerror__PTHREAD_SPINS was not declared in this scope
I've tried every compile switch I can think of, but getting the same error. Not many references to this error on google, so hoping someone can tell me if it's something to do with the processor architecture?
Very simple to reproduce : this won't compile
Many thanks in advance
Code: Select all
#include <iostream> #include <pthread.h> using namespace std; int main(int argc, char *argv[]) { pthread_mutex_t mp = PTHREAD_MUTEX_INITIALIZER; return 0; } | https://www.raspberrypi.org/forums/viewtopic.php?t=220266 | CC-MAIN-2019-04 | refinedweb | 172 | 51.78 |
Invite Freelancer to Project
You don't seem to have an active project at the moment. Why not post a project now? It's free!Post a project
Kamal Saleh
Recent Reviews
Convert vBulletin (3.8.4) Installation to Vanilla Forums $175.00 USD
“Very easy guy to work with. Knowledgeable, hard-working and did the job 100% to spec.”deagledan
2 months ago
Project for bridge2heyday $500.00 USD
“Kamal is the only forum expert on I totally recommend him for your forum tasks , because he knows what he is doing and won't disappoint you.”Busylancer
3 months ago
Transfer a Forum from SMF to vBulletin $666.00 CAD
“This was the best experience I had on Freelancer. He is an absolutely fantastic guy. He knows what he is doing and goes put of his way to help. I will definitely hire him again. A+ rating.”clafo
8 months ago
Convert custom vBulletin 3.8 mod to vBulletin 4 €111.00 EUR
“Very easy to work with. Glad I picked him for the project.”floid78
9 months ago
Migrate a forum based on vBulletin 4.2.3 to IPBoard 4.1 and keep url $200.00 USD
“Very high quality with this freelance, difficult to find better !”olijo
1 year ago
import guestbook data from database to a joomla component $100.00 USD
“Kamal delivers a high quality work, he perfectly know his limit and his knowledge in database management is great.”olijo
1 year ago
Experience
PHP Web DeveloperDec 2010
Junior Web DeveloperMar 2008 - Sep 2010 (2 years)
TraineeJun 2007 - Dec 2007 (6 months)
Education
Bsc of Elecrical Engineering2005 - 2010 (5 years)
Certifications
Zend PHP 5.3 Certification (2011)Zend
Verifications
- Facebook Connected
- Preferred Freelancer—
- Payment Verified
- Phone Verified
- Identity Verified—
My Top Skills
- vBulletin 34
- PHP 26
- MySQL 19
- Forum Software 10
- HTML 5
- SEO 3
- WordPress 3
- Database Administration 3
- Script Install 1
- Joomla 1
- SQL 1
- Translation 0
- Web Security 0
- Social Networking 0
- Computer Security 0
- Facebook Marketing 0
- Google Adsense 0
- jQuery / Prototype 0
- Blog Install 0
- Web Services 0 | https://www.freelancer.com/u/bridge2heyday.html | CC-MAIN-2017-04 | refinedweb | 348 | 66.74 |
There is a great article from Tenderlove - one of the core Ruby and Rails developers - called “I am a puts debuggerer”, that I enjoyed when I played with Ruby. The gist of it is to show you that, in many cases, you don’t need a full-fledged debugger. Don’t get me (or Tenderlove) wrong - the debugger that comes with a good IDE is one of the most powerful tools that a programmer can have! You can easily put breakpoints in your code, move around the stack trace or inspect and modify variables on the fly. It makes working with large codebase much easier and helps newcomers get up to speed on a new project.
Yet, people still use
print(a_varible) ... if foo: print(">>>>>>>>>>>>>>Inside 3rd IF") ... print(">>>>>>>>>>>>>>Inside 37th IF") print(">>>>>>>>>> #@!?#!!!")
Sounds familiar? There is nothing wrong with using
And not everyone is using an IDE with a good debugger. According to the Stack Overflow Developer Survey Results 2019, 30.5% of developers are using Notepad++, 25.4% Vim, and 23.4% Sublime Text. Those are text editors! And even though I have seen people being more productive in Vim than most of the PyCharm or VS Code users, text editors are not created with a powerful debugger in mind. You can always use the standard Python debugger
pdb, but a much better alternative is to use IPython as your debugger.
I’ve been using VS Code for almost two years, but I don’t remember when was the last time I used the built-in debugger. I do most of my debugging in IPython. Here is how I’m using it:
Embedding IPython session in the code
The most common case for me is to embed an IPython session in the code. All you need to do is to put the following lines in your code:
from IPython import embed embed()
I like to put those two statements in the same line:
from IPython import embed; embed()
so I can remove them with one keystroke. And, since putting multiple statements on the same line is a bad practice in Python, every code linter will complain about it. That way, I won’t forget to remove it when I’m done 😉.
When you run your code and the interpreter gets to the line with the
embed() function, it will open an IPython session. You can poke around and see what’s going on in the code. When you are done, you just close the session (
Ctrl+d) and the code execution will continue. One nice thing about this approach is that all the modifications done in IPython will persist when you close it. So you can modify some variables or functions (you can even decorate functions with some simple logging) and see how the rest of the code will behave.
Here is a short demo of
embed() in action. Let’s say we have the following file:
a = 10 b = 15 from IPython import embed; embed() print(f"a+b = {a+b}")
This is what happens when we run it:
As you can see, I changed the value of the
a variable and the new value persisted after I closed the IPython session.
Putting a breakpoint in your code
Embedding an IPython session in the code is fine if you want to see what’s going on at a given line. But you can’t execute the next lines of code, as a real debugger would do. So a better idea is to put a breakpoint in your code instead. Starting with version 3.7 of Python, there is a new built-in function called breakpoint() that you can use for that. If you are using an older version of Python, you can achieve the same effect by running the following code:
import pdb; pdb.set_trace()
The default debugger (
pdb) is pretty rudimentary. Just like in the standard Python REPL, you won’t get the syntax highlighting or automatic indentation. A much better alternative is the ipdb. It will use IPython as the debugger. To enable it, use the ipdb instead of pdb:
import ipdb; ipdb.set_trace()
There is also another interesting debugger called PDB++. It has a different set of features than ipdb, for example, a sticky mode that keeps showing you the current location in the code.
No matter which debugger you end up using, they have a pretty standard set of commands. You can execute the next line by calling the
next command (or just
n), step inside the function with
step (or
s), continue until the next breakpoint with
continue (or
c), display where you are in the code with
l or
ll, etc. If you are new to these CLI debuggers, the “Python Debugging With Pdb” tutorial is a good resource to learn how to use them.
%run -d filename.py
IPython has another way to start a debugger. You don’t need to modify the source code of any file as we did before. If you run the
%run -d filename.py magic command, IPython will execute the
filename.py file and put a breakpoint on the first line there. It’s just as if you would put the
import ipdb; ipdb.set_trace() manually inside the
filename.py file and run it with
python filename.py command.
If you want to put the breakpoint somewhere else than the first line, you can use the
-b parameter. The following code will put the breakpoint on line 42:
%run -d -b42 filename.py
Keep in mind that the line that you specify has to contain code that actually does something. It can’t be an empty line or a comment!
Finally, there might be a situation where you want to put a breakpoint in a different file than the one that you will run. For example, the bug might be hidden in one of the imported modules and you don’t want to type
next 100 times to get there. The
-b option can accept a file name followed by a colon and a line number to specify where exactly you want to put the breakpoint:
%run -d -b myotherfile.py:42 myscript.py
The above code will put a breakpoint on line 42 in a file called
myotherfile.py and then start executing file
myscript.py. Once the Python interpreter gets to
myotherfile.py, it will stop at the breakpoint.
Post-mortem debugging
IPython has 176 features1. Post mortem debugging is the best of them. At least for me. Imagine that you are running a script. A long-running script. And suddenly, after 15 minutes, it crashes. Great - you think - now I have to put some breakpoints, rerun it and wait for another 15 minutes to see what’s going on. Well, if you are using IPython, then you don’t have to wait. All you need to do now is to run the magic command
%debug. It will load the stack trace of the last exception and start the debugger (Python stores the last unhandled exception inside the
sys.last_traceback variable). It’s a great feature that has already saved me hours of rerunning some commands just to start the debugger.
If you are using the standard
pdb debugger, you can achieve the same behavior by running the
import pdb; pdb.pm() command.
Automatic debugger with %pdb
The only way to make debugging even more convenient is to automatically start a debugger if an exception is raised. And IPython has a magic command to enable this behavior -
%pdb.
If you run
%pdb 1 (or
%pdb on), a debugger will automatically start on each unhandled exception. You can turn this behavior off again with
%pdb 0 or
%pdb off. Running
%pdb without any argument will toggle the automatic debugger on and off.
Footnotes
Photo by Steinar Engeland on Unsplash | https://switowski.com/blog/ipython-debugging | CC-MAIN-2020-50 | refinedweb | 1,306 | 73.07 |
Introduction to Digit DP
Introduction
Suppose you have two integers, 'X' and 'Y,' and you are required to count the number of integers' Z' which satisfy the given constraints, and Z must lie in the range X to Y, both inclusive.
If X and Y are small(1 <= X, Y <= 10^6), you can iterate over all the numbers from X to Y and check which satisfies the given constraints and keeps their count. But if X and Y are large (1 <= X, Y <= 10^18), then this approach is inefficient and gives the verdict "Time Limit Exceeded." So for such cases, we use Digit DP. By the Term "Digit DP," it's clear that we will apply Dynamic Programming on digits.
Approach
Let Solve(L, R) give you the solution for the range L to R. For the time being, suppose L is zero. So, to solve for 0 to R, we have to count the total number of non-negative integers Z such that Z satisfies the given constraints and Z is less than or equal to R.
So, if we can find the solution for 0 to X - 1 and 0 to Y, then their difference will give the solution for range X to Y.
Solve(X, Y) = Solve(0, Y) - Solve(0, X - 1)
How to solve for range zero to R??
Let d be the number of digits in the decimal representation of integer R (without leading zeros). Any number less than equal to R can't have the numbers of digits greater than d in its decimal representation. If there is a number less than R having less than d number of digits, we will add leading zeros to it, so we can say that every number less than R has exactly d number of digits in its decimal representation.
Let's consider each number as a sequence of digits. Let's assume that sequence r1,r2,r3,........, rd represents integer R.
Let 'S' be another sequence. S is initially empty.
We will recursively add digits to the next position of S, but we can't add any random digit from 0 to 9 to the sequence. We have to make sure that number is always less than or equal to R.
The index 0 is the most significant digit, and the index d - 1 is the least significant digit. So, if we want to place a digit at index 'i' and index 0 to i - 1 is already filled, then -
- We can put any digit at position 'i' if there exists at least one index 'j' from 0 to 'i' such that S[j] < r[j] because the sequence is already smaller than R, so whatever we add won't create any difference.
- But if no such 'j' exists, we can't put a digit greater than r[i] because the number will become greater than R.
So, we have to pass the next 'index to fill' and the 'current sequence' as a parameter to the recursive call.
This recursive solution is inefficient because we must pass the whole sequence whenever we make the recursive call. But there is no need to pass the entire sequence. We can use a boolean variable 'f' to check whether the current sequence is less than R or not. If f = 1, then the sequence is already smaller than R, and we can add any digit to the next index, but if f = 0, we can't.
So, we can build the sequence, but we have forgotten that the number formed by the sequence must satisfy the given constraints. For that, Let's take an example problem.
Example Problem
Given two integers, X and Y., Your task is to find the count of integers Z such that digit t occurs exactly k times in Z.
Constraints : 1 <= X , Y <= 10^18,
0 <= t <= 9,
1 <= K <= 18
Solution
As discussed earlier, we have to find the solution for the range 0 to L - 1 and 0 to R to solve this problem.
Now, to keep the count of digit 't' in the sequence, we need another parameter, 'num.' Whenever we place digit t at any index in our sequence, we increment the num in the next recursive call.
States of DP
So, the final states of DP are current position (index at which we place the next digit), whether the number is already smaller than R or not (boolean variable f), and frequency of digit t till now (num).
Base Case
If the current index is equal to d, we have built the whole sequence, and then we need to check whether the num is equal to k or not. If num is equal to k, we return 1. Otherwise, we return 0.
Code
#include <bits/stdc++.h> #define int long long using namespace std; int X, Y, t, k; vector <int> r; //sequence r - represents R int dp[20][20][2]; //3D array to memorize the states /* index - current index num - frequency of digit t f - boolean variable to check the current sequence is less than R or not */ int rec(int index, int num, int f){ if(index == r.size()){ //Base case if(num == k) return 1; else return 0; } if(dp[index][num][f] != -1) //to avoid overlapping return dp[index][num][f]; int res = 0; if(f == 0){ /* digits we placed so far matches with the prefix of r so, we can't place digit > r[index] at the current index. */ for(int i = 0; i <= r[index]; ++i){ if(i == r[index]){ /* i == r[index] and f == 0, so the digits we placed still match with prefix of r, so f = 0 */ res += rec(index + 1, num + (i == t), 0); } else{ /* i < r[index] so, f = 1 */ res += rec(index + 1, num + (i == t), 1); } } } else{ /* f = 1, so the sequence is already smaller than r so we can place any digit at the current index. */ for(int i = 0; i <= 9; ++i){ res += rec(index + 1, num + (i == t), 1); } } return dp[index][num][f] = res; } int Solve(int R){ r.clear(); while(R > 0){ r.push_back(R%10); R /= 10; } //to store the digits of R in the decreasing order of significance we have to reverse the sequence r reverse(r.begin(), r.end()); memset(dp, -1, sizeof(dp)); return rec(0, 0, 0); } signed main(){ cin >> X >> Y >> t >> k; //range - [X, Y], digit - t, frequency - k cout << Solve(Y) - Solve(X - 1); //Solve(X, Y) = Solve(0, Y) - Solve(0, X - 1) return 0; }
Time Complexity
The overall complexity is O(index * frequency * f * 10). The factor of ten is included because, at each state, we will try to place all the ten digits from 0 to 9 at the current index.
X, Y can't be greater than 10^18, so the maximum number of digits in X and Y can be 19, K can't be greater than 20, and the boolean variable f can be 0 or 1. so the total number of iteration can be 10 * 20 * 19 * 2 ~ 10^5.
Space complexity
We have to use a 3D array to memorize each state. Each Dimension represents one parameter, so the total space complexity is O(index * f * frequency)..
Key Takeaways
This article covered the basics of digit DP and an example problem. Having a good hold on Dynamic Programming is very important for cracking coding interviews at MAANG.
Check out the coding ninjas master class on dynamic programming for getting a better hold on dynamic programming.
To learn more about such data structures and algorithms, Codestudio is a one-stop destination. This platform will help you to improve your coding techniques and give you an overview of interview experiences in various product-based companies by providing Online Mock Test Series and many more benefits.
Happy learning! | https://www.codingninjas.com/codestudio/library/introduction-to-digit-dp-1009 | CC-MAIN-2022-27 | refinedweb | 1,313 | 66.78 |
There are a large number of questions that deal with some aspect of distance. If you are interested in quick distance calculations, then download and read the attachment.
The tools are builtin to arcpy to get the data into this form to facilitate calculations.
You can determine distances using different metrics... euclidean distance is shown here.
If you need to find the nearest, a list of closest objects or to calculate the perimeter of a polygon or length of a line represented by a sequence of points, there are other options available to you.
Associated references:
Python Near Analysis (No Advanced Licence)
That's all for now...
I always forget. I read about something pythonic, then quasi-remember what it was I read. So this is what is coming to python. A look into the future. Preparing for the future.
The main link What’s New in Python ... this goes back in history
Pre-existing functionality What is in version 3 that existed in version 2.6
with statement, print as a function, io module
----- python 3.7 ---------------------------------------------------------------------------------------
What’s New In Python 3.7 ... main page
Highlights
----- python 3.6 ---------------------------------------------------------------------------------------
What’s New In Python 3.6 ... main page
Highlights
>>>>> f"He said his name is {name}."
'He said his name is Fred.'
datetime The
datetime.strftime() and
date.strftime() methods now support ISO 8601 date directives
%G,
%u and
%V
os
zipfile
---- python 3.5 -------------------------------------------------------------------------------------------
What’s New In Python 3.5 ...main page
an infix matrix multiplier a @ b ... pep 465
>>> *range(4), 4 (0, 1, 2, 3, 4)
>>> [*range(4), 4] [0, 1, 2, 3, 4]
>>> {*range(4), 4, *(5, 6, 7)} {0, 1, 2, 3, 4, 5, 6, 7}
>>> {'x': 1, **{'y': 2}} {'x': 1, 'y': 2}
collections.OrderedDict is now implemented in C which makes it 4 to 100 times faster.
---- python 3.4 -----------------------------------------------------------------------------------------
What's New in Python 3.4 ... main page
>>> import statistics
>>> dir(statistics)
[ .... snip ... 'mean', 'median', 'median_grouped', 'median_high', 'median_low', 'mode', 'pstdev', 'pvariance', 'stdev', 'variance']
---- python 3.3 and before -------------------------------------------------------------------------------
Previous stuff (aka pre-3.4)
way more ..... you will just have to read the original migration docs.
Significant changes to text handling and the migration to full unicode support.
Some of the changes have been implemented in python 2.7 and/or can be accessed via ... from future import ....
Anaconda, Spyder and ArcGIS PRO
Python and ArcGIS Pro 1.3 : Conda
Download Anaconda now! | Continuum
The reverse chronological list of changes to numpy Release Notes — NumPy v1.12 Manual
Too many to list, but the change logs are given here Release Notes — SciPy v0.17.0 Reference Guide
SciPy central
users guide User’s Guide — Matplotlib 1.5.1 documentation
chronologic change history What’s new in matplotlib — Matplotlib 1.5.1 documentation
Pandas 0.18.1 What’s New — pandas 0.18.1 documentation
The full list is here pandas main page and release notes
Have you every come across a situation like one of these:
Well, this lesson is for you. It is a culmination of a number of the previous lessons and a few
NumPy Snippets and Before I Forget posts. I have attached a script to this post below
There is also a GitHub repository that takes this one step further providing more output options... see Silly on GitHub
The following provides the basic requirements to operate a function should you choose not to
incorporate the whole thing. Obviously, the header section enclosed within triple quotes
isn't needed but the import section is.
# -*- coding: UTF-8 -*-
"""
:Script: random_data_demo.py
:Author: Dan.Patterson AT carleton.ca
:Modified: 2015-08-29
:Purpose:
: Generate an array containing random data. Optional fields include:
: ID, Shape, text, integer and float fields
:Notes:
: The numpy imports are required for all functions
"""
#-----------------------------------------------------------------------------
# Required imports
from functools import wraps
import numpy as np
import numpy.lib.recfunctions as rfn
np.set_printoptions(edgeitems=5, linewidth=75, precision=2,
suppress=True,threshold=5,
formatter={'bool': lambda x: repr(x.astype('int32')),
'float': '{: 0.2f}'.format})
#-----------------------------------------------------------------------------
# Required constants ... see string module for others
str_opt = ['0123456789',
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~',
'abcdefghijklmnopqrstuvwxyz',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
]
#-----------------------------------------------------------------------------
# decorator
def func_run(func):
"""Prints basic function information and the results of a run.
:Required: from functools import wraps
"""
@wraps(func)
def wrapper(*args,**kwargs):
print("\nFunction... {}".format(func.__name__))
print(" args.... {}\n kwargs.. {}".format(args, kwargs))
print(" docs.... \n{}".format(func.__doc__))
result = func(*args, **kwargs)
print("{!r:}\n".format(result)) # comment out if results not needed
return result # for optional use outside.
return wrapper
#-----------------------------------------------------------------------------
# functions
Before I go any further, lets have a look at the above code.
Now back to the main point. If you would like to generate data with some control on the output.
This will present some functions to do so and put it together into a standalone table or feature class.
An example follows:
Array generated....
array([(0, (7.0, 1.0), 'E0', '(0,0)', 'A', 'ARXYPJ', 'cat', 'Bb', 0, 9.380410289877375),
(1, (2.0, 9.0), 'D0', '(4,0)', 'B', 'RAMKH', 'cat', 'Aa', 9, 1.0263298179133362),
(2, (5.0, 8.0), 'C0', '(1,0)', 'B', 'EGWSC', 'cat', 'Aa', 3, 2.644448491753841),
(3, (9.0, 7.0), 'A0', '(1,0)', 'A', 'TMXZSGHAKJ', 'dog', 'Aa', 8, 6.814471938888746),
(4, (10.0, 3.0), 'E0', '(1,0)', 'B', 'FQZCTDEY', '-1', 'Aa', 10, 2.438467639965038)],
............. < snip >
dtype=[('ID', '<i4'), ('Shape', [('X', '<f8'), ('Y', '<f8')]),
('Colrow', '<U2'), ('Rowcol', '<U5'), ('txt_fld', '<U1'),
('str_fld', '<U10'), ('case1_fld', '<U3'), ('case2_fld', '<U2'),
('int_fld', '<i4'), ('float_fld', '<f8')])
Here are the code snippets...
The above functions can be used with the main portion of the script and your own function.
You will notice in the above example that the rand_case function was to determine
the number of pets based upon p-values of 0.6, 0.3 and 0.1, with cats being favored, as they should be, and
this is reflected in the data. The coordinates in this example were left as integers, reflecting a 1m resolution.
It is possible to add a random pertubation of floating point values in the +/- 0.99 to add centimeter values if you desire.
This is not shown here, but I can provide the example if needed.
The 'Number' field in this example simply reflects the number of pets per household.
Homework...
Using NumPyArrayToFeatureclass, create a shapefile using a NAD_1983_CSRS_MTM_9 projection
(Projected, National Grids, Canada, NAD83 CSRS_MTM_9)
Answer...
>>> import arcpy
>>> a = blog_post() # do the run if it isn't done
>>> # ..... snip ..... the output
>>> # ..... snip ..... now create the featureclass
>>> SR_name = 32189 # u'NAD_1983_CSRS_MTM_9'
>>> SR = arcpy.SpatialReference(SR_name)
>>>>> arcpy.da.NumPyArrayToFeatureClass(a, output_shp, 'Shape', SR)
Result
That's all... | https://geonet.esri.com/blogs/dan_patterson/2016/04 | CC-MAIN-2017-30 | refinedweb | 1,093 | 69.38 |
Have you ever run into a traceback that ends with something like this?
File "C:\Python27\lib\logging\handlers.py", line 141, in doRollover os.rename(self.baseFilename, dfn) WindowsError: [Error 32] The process cannot access the file because it is being used by another process
I certainly have, in a few places. The basic problem is that when python creates file objects on Windows (and I think on *nix as well), by default Python will mark the handle as being inheritable (I’m sure there’s a reason why… but, doesn’t make a whole lot of sense for this to be the default behavior to me). So if your script spawns a new process, that new process will inherit all the file handles from your script — and of course since it doesn’t realize that it even has those handles, it’ll never close them. A great example of this is launching a process, then exiting. When you launch your script again and try to open that handle… the other process still has it open, and depending on how the file was opened, you may not be able to open it due to a sharing violation.
It looks like they’re trying to provide ways to fix the problem in PEP 433 for Python 3.3, but that doesn’t help those of us still using Python 2.7. Here’s a snippet that you can put at the very beginning of your script to fix this problem on Windows:
import sys if sys.platform == 'win32': from ctypes import * import msvcrt __builtins__open = __builtins__.open def __open_inheritance_hack(*args, **kwargs): result = __builtins__open(*args, **kwargs) handle = msvcrt.get_osfhandle(result.fileno()) windll.kernel32.SetHandleInformation(handle, 1, 0) return result __builtins__.open = __open_inheritance_hack
Now, I admit, this is a bit of a hack… but it solves the problem for me. Hope you find this useful!
Thank you for sharing this. Although it did not solve my problem, it inspired me along the way!
btw, I think you should
import __builtin__
and call “__builtin__.open” rather than “__builtins__.open” | http://www.virtualroadside.com/blog/index.php/2013/02/06/problems-with-file-descriptors-being-inherited-by-default-in-python/ | CC-MAIN-2019-04 | refinedweb | 345 | 71.65 |
Your Vagrant Deployment Sandbox for Django
Deploying your Django project for the first time can seem like a huge task, and a blocking one in addition to that. You can’t move forward until the site is in production. The pressure is on.
However, there’s one trick to make deployment way less scary, and way less of a big deal.
Just deploy as early as possible. It doesn’t even need to be a publicly accessible location. Just an environment which is distinct from your development environment. Somewhere, where you can try your deployment procedures from scratch every now and then.
If this sounds painful and tedious, this article is for you. Deployment doesn’t need to be a frustrating and task which costs you days to get right.
A Safe Environment
There’s the perfect tool, to create safe environments without much effort - it’s Vagrant.
“Vagrant enables users to create and configure lightweight, reproducible, and portable development environments.”
Vagrant makes it possible to create a virtual machine with a single command, configure it with code, and completely clean up the environment (and recreate it from scratch) whenever you wish.
It makes for the perfect environment to prototype your deployment approaches. A completely safe sandbox to try to deploy your application and find out what’s missing and what can be done better.
Your Goal
The idea behind deploying early, and doing so in an environment which is meant to be destroyed eventually, is to work on your processes. You want to make deployment really easy, almost boring.
This is done by iterating and learning as you go. In the beginning, you’ll be working on making notes for your future-self. Jotting down notes and tweaking your webapp project to make it more deploy-friendly. Eventually, you’ll start adding automation to your written documentation, to make each time you recreate your deployment environment easier and less intimidating.
If anything goes wrong or if you don’t know how to fix an issue - no biggie. You can simply completely destroy the VM, restart from scratch and arrive at a working state again.
Vagrant for your Django App - Step by Step
Here’s how you can create your first, safe Django deployment environment - right on your development machine. You’ll be able to get your feet wet here without the perceived responsibility and steep learning curve of working with a publicly-accessible remote environment.
1. Install Vagrant.
To get started, you’ll need to install Vagrant on your local development machine. Go to Vagrant’s download page and install the most recent version from there.
“Why not use the package manager version” you may ask? You could, but for example the Ubuntu one is known to be notoriously outdated. This sometimes leads to bugs and unexpected behaviour. I find it easier to roll with the versions from the site for this reason.
Once you’ve installed it, you can jump into your command line and check the version:
$ vagrant --version
2. Install VirtualBox
Vagrant is a tool to create and manage environments which run in in VMs. VirtualBox is a great free virtualization product. The way how you’re supposed to install it depends on your OS. Make sure to set it up well.
3. Get a Vagrant Box
Vagrant boxes are basically VM images, which you use to create a new virtual machine. I like to use Ubuntu, as it is easy to handle, and offers mix of stable & reasonably recent packages. The current LTS (long time support) version is Ubuntu 18.04.2 LTS.
With Vagrant, you can get Ubuntu boxes from different providers.
The Vagrant docs recommend to stick to Ubuntu boxes from either bento or hashicorp themselves. (Read here for more details). The boxes from the canonical namespace are not recommended as they are known to cause issues.
“These are the only two officially-recommended box sets.”
While Hashicorp’s box is described as “minimal, highly optimized, small in size”, while the bento box is recommended “for other users”. From the box site, both seem to be around 500 MB large. I went with the bento version out of habit - they haven’t had any issues with them in the past.
You can add a box (downloading it to your machine) with the following command:
$ vagrant box add bento/ubuntu-18.04 # Note: choose option 1 for virtualbox
4. Start a Vagrantfile
Now you have everything ready to create a Vagrantfile.
Go into the folder where your Django app is located, and execute the following command:
$ vagrant init bento/ubuntu-18.04 # you could also specify a particular version: # --box-version 201906.18.0
This will create a well-documented Vagrantfile for you, which you can build on. You’ll probably only need to uncomment parts and slightly tweak some of them.
Here is my (slightly modified) file:
# -*- = "bento/ubuntu-18.04" #" config.vm.network "forwarded_port", guest: 8000, host: 8081, ".", "/home/vagrant/code" # Provider-specific configuration so you can fine-tune various # backing providers for Vagrant. These expose provider-specific options. # Example for VirtualBox: # config.vm.provider "virtualbox" do |vb| # Don't display the VirtualBox GUI when booting the machine vb.gui = false # "shell", inline: <<-SHELL # apt-get update # apt-get install -y apache2 # SHELL end
The Vagrantfile is modified to:
- Add a shared folder (the one where the Vagrantfile is in) to the VM under
/home/vagrant/code.
- Enable “headless mode” so no window pops up where the VM is running.
- Set a memory limit for the VM to 1 GB.
- Forward port 80 of the VM to 127.0.0.1:8080 and port 8000 to 127.0.0.1:8081 on the host.
Now we are ready to start a brand-new Ubuntu VM based on those configs.
5. Vagrant Up!
With all of the preparations in place, creating a new VM is as easy as typing:
$ vagrant up
Once it has started, and you make changes to your Vagrantfile, you’ll need to run
$ vagrant reload
for the changes to take effect.
Now you can SSH into your box.
6. SSH Into Your VM
Once your Vagrant VM is up, you can connect to it directly via the commandline:
$ vagrant ssh
Congratulations! You’re in your brand-new Vagrant environment.
Your project’s code (shared from the local machine) can be found in the directories
/home/vagrant/code or
/vagrant in the new VM. Check out the content:
$ cd code $ ls
As it’s a shared folder, you should be aware that any file you delete or change here, will be deleted or changed on your development machine as well. Take care, and make sure to have your code under version control, so you could recover from things going wrong.
The upside of a shared folder is: you can edit code as usually on your machine, and your VM will get the newest changes right away.
7. The First “Deployment”
Now that we have made our way into a brand-new environment, we can get a very first deployment version of your application up and running.
In the beginning, it’s best to aim for the easiest possible option - simply bring up a development server inside of the VM. Once that one works, you’ll be able to make it more complicated. Consider it a “Hello World!” of deployment.
Be sure to take notes of all steps which you are taking. Jotting down info on the packages you need to install or commands you type in this environment are useful clues to make it easier the next time around! Don’t forget, you’re working on your deployment processes, not building a “forever” deployment environment. Being conscious of those processes is the first step forward.
8. An Example
As I don’t want to leave you hanging 1:1 with this (possibly) new environment, I’d like to share a series of commands which will help you to get up a brand-new Django project inside of the VM for testing.
Attention! If you already have a Django project in your VM’s
code directory, you won’t
need to create a new one. Everything else should be pretty much the same.
First, we’ll need to install Python 3, and add some tooling while we’re at it:
$ sudo install python3 $ sudo install python3-pip $ pip3 install virtualenv $ pip3 install pipenv
Now, we should exit the SSH session, and start a new one with
vagrant ssh. This will make sure
that we can use pipenv.
Here, we’ll create a new Pipfile and install the latest version of Django. These steps are loosely based no this article. Then, we’ll use that Django version to start a new project and run it inside of the VM:
$ pipenv --three $ pipenv install django $ pipenv shell $ django-admin startproject testproject . $ python manage.py runserver 0.0.0.0:8000
Notice how we run the development server on
0.0.0.0:8000 inside the VM? Because of the
port forwarding settings in the Vagrantfile, we can access this running application from outside
of the VM. Just open up your browser, and navigate to.
All done! We have created a new Django VM, installed everything we need to run a Django project in it, and accessed the running application from the development machine. Shiny!
8. Total Destruction
Once you feel that you are ready to try a more automated, or more elaborate way to deploy your application, you can get rid of the complete Vagrant VM, and start from scratch. This is a good thing! You’ll have a fresh OS, which is in a blank state. This will help you to make sure that your processes are complete and reproducible.
Destroying the environment and starting from scratch is as easy as typing the following two commands:
$ vagrant destroy $ vagrant up
Now, Vagrant will create a fresh VM. I hope your notes from the last time around are good, and you’ll get your environment up even faster!
Cool. Now What?
This was only the first non-development (but still develop-ish) environment you’ve created. Congratulations! You are now ready to build on your hard work, and bring it closer to a production environment.
Don’t forget: your goal is to build reproducible processes, not to “get it working once and forget how”. These processes will help you to shape your application to be easy to deploy, but they’ll also get you in the habit of bringing your project into a deployed state.
Here is what you can try next:
- Install a reverse proxy like Nginx, and make it pass traffic to your app.
- Install a PostgreSQL database inside the VM, make your app use it.
- Use Gunicorn instead of the development server to run your code.
- Automate some setups steps of the Vagrant VM - using either Bash, Ansible or Fabric.
- Try Docker for some of your backing services.
I hope you’ll be able to learn about deployment way earlier than the dreaded “time to deploy”, and get comfortable with the task in a safe, fully controlled environment. If it seems like repeating yourself - don’t worry. Approaching deployment iteratively will make it less stressful and save you time down the line.
Wanna learn how to use Vagrant better, and develop your first deployment environment into a production-like environment for your Django app? Sign up below and get the first lesson directly in your inbox! | https://vsupalov.com/django-vagrant-deployment-sandbox/ | CC-MAIN-2019-43 | refinedweb | 1,916 | 64.2 |
Mellow is a Haskell library providing a layer over freenect, friday, and gloss. That is, Mellow acquires frames of 11-bit depth information from an X-Box Kinect (360), applies the user-provided image transformation, and renders the image to screen.
N.B. Mellow is likey not an ideal platform for high-performance uses but is intended to be simple enough for fun toys and motivating educational demonstrations.
The main routine is
mellow state0 update render eventHandler where
state0 is
the initial state, update will update the state with a new frame,
render will
rasterize a given state for display to screen, and
eventHandler is useful for
key presses and other inputs.
In under 20 lines we can get a pretty little OpenGL colored rendering of the depth map. The basic steps are:
{-# LANGUAGE MultiWayIf #-} import Mellow -- The main 'Mellow' module import Vision.Image as I -- The Friday library for image manipulation main :: IO () main = mellow blackRGBA -- Black image to start (\d _ -> return (depthToRGBA d)) -- RGBA from 11-bit depth return -- Noop renders (defaultEventHandler return) -- The default event handler allows us to quit using 'esc' -- as well as save screen captures with 's'. depthToRGBA :: Depth -> RGBA depthToRGBA = I.map -- Friday image manipulation map operation (\val -> RGBAPixel (oper val 0 950) (oper val 800 1200) (oper val 1000 2100) 255) where oper v n x = let v' | v > x = 0 | v < n = 0 | otherwise = fromIntegral (v - n) in floor $ 255 * (v' / 700 :: Double) blackRGBA :: RGBA blackRGBA = I.fromFunction (Z :. 480 :. 640) (const (RGBAPixel 0 0 0 0))
Depth test image of my boring living room. See my cat everyone? SEE MY CAT EVERYONE!
Psychedelic Outlines (done for a birthday): | https://recordnotfound.com/mellow-TomMD-281 | CC-MAIN-2018-47 | refinedweb | 279 | 58.82 |
how to use throws exception in java?
The throws keyword is used to indicate that the method raises particular type of exception while being processed.
public class StringTest { public static void divide() throws ArithmeticException { int x = 10, y = 0; int z = x / y; } public static void main(String[] args) { divide(); } }
Output:-
Exception in thread "main" java.lang.ArithmeticException: / by zero
Description:- Here is an example of throws clause. We have created a class named ThrowsExample. In the main method, we have declared two variables of integer type and divide the first value by another which is 0. The throws keyword performs exception handling and display the exception. | http://www.roseindia.net/answers/viewqa/Java-Beginners/26775-throws-example-program-java.html | CC-MAIN-2015-35 | refinedweb | 107 | 56.35 |
Speed up creation of unit tests
Unit tests are indispensable, but they are also very verbose – every test fixture requires a properly decorated class, every test case – its own method. Also, you may find yourself typing
Assert.Equals far too many times.
Let’s see if we can shorten the time necessary to create unit tests by using ReSharper's code templates. We are going to start by creating a file template, which is a way for ReSharper to create a whole file at once. First, let’s open up the menu item. We are presented with the following:
Pressing the New Template
button, we can define a whole template for a test fixture. You can use concrete types and implementations, but we are going to follow general NUnit conventions below:
Now if we want to use this template to create a unit test fixture, we can right-click on a project and select . We are presented with the following dialog:
We can select our ‘Test Fixture’ here and additionally tick the 'Add to quicklist' so that the template is added quick access list for all C# projects and we have it the menu without selecting .
Clicking OK in the dialog creates the following file:
namespace MyProject { [TestFixture] public class MyFixture { [Test] public void MyTest() { } } }
The attributes can, of course, be customized to your preferred unit testing framework.
Now, let’s take a look at test methods. Typically, these are void methods with no parameters (parameterized tests being a ‘special case’) with the
Test attribute appended.
For this, we switch to the Live Templates tab of the Templates Explorer window. Once again, we simply define a stub for a method, with
$NAME$ being a variable for the method name and
$END$ indicating where the caret is once the template expands.
Now, typing
test inside our test fixture and pressing Tab yields us a new test method.
Another thing we can do is create a live template for
Assert.IsEqual(). This is also easy: we simply define a live template with two parameters:
Both of these use the Constant Value macro. This isn’t necessary, but it prettifies the code and makes the template more understandable when there comes a time to actually use it.
So there you have it – with the Test Fixture file template and the test and ae templates, you can quickly and easily generate test code stubs. Feel free to use the same approach for other test-related elements, such as generating test fixtures with setup/tear-down methods, using the file generation as a live template instead of a file template (remember, you can always move the class to a separate file), creating live templates for other types of asserts, etc. Good luck! | https://www.jetbrains.com/help/resharper/2017.1/Speed_up_Creation_of_Unit_Tests.html | CC-MAIN-2019-22 | refinedweb | 457 | 65.76 |
# Faster ENUM
#### tl;dr
[github.com/QratorLabs/fastenum](https://github.com/QratorLabs/fastenum)
```
pip install fast-enum
```
### What are enums
(If you think you know that — scroll down to the “Enums in Standard Library” section).
Imagine that you need to describe a set of all possible states for the entities in your database model. You'll probably use a bunch of constants defined as module-level attributes:
```
# /path/to/package/static.py:
INITIAL = 0
PROCESSING = 1
PROCESSED = 2
DECLINED = 3
RETURNED = 4
...
```
...or as class-level attributes defined in their own class:
```
class MyModelStates:
INITIAL = 0
PROCESSING = 1
PROCESSED = 2
DECLINED = 3
RETURNED = 4
```
That helps you refer to those states by their mnemonic names, while they persist in your storage as simple integers. By this, you get rid of magic numbers scattered through your code and make it more readable and self-descriptive.
But, both the module-level constant and the class with the static attributes suffer from the inherent nature of python objects: they are all mutable. You may accidentally assign a value to your constant at runtime, and that is a mess to debug and rollback your broken entities. So, you might want to make your set of constants immutable, which means both the number of constants declared and the values they are mapped to must not be modified at runtime.
For this purpose you could try to organize them into named tuples with `namedtuple()`, as an example:
```
MyModelStates = namedtuple('MyModelStates', ('INITIAL', 'PROCESSING', 'PROCESSED', 'DECLINED', 'RETURNED'))
EntityStates = MyModelStates(0, 1, 2, 3, 4)
```
However, this still doesn't look too understandable: in addition to that, `namedtuple` objects aren't really extensible. Let's say you have a UI which displays all these states. You can then use your module-based constants, your class with the attributes, or named tuples to render them (the latter two are easier to render, while we're at it). But your code doesn't provide any opportunities to give the user an adequate description for each state you've defined. Furthermore, if you plan to implement multi-language support and i18n in your UI, you'll find that filling in all the translations for these descriptions becomes an unbelievably tedious task. The matching state values might not necessarily have matching descriptions which means that you cannot just map all of your `INITIAL` states onto the same description in `gettext`. Instead, your constant becomes this:
```
INITIAL = (0, 'My_MODEL_INITIAL_STATE')
```
Your class then becomes this:
```
class MyModelStates:
INITIAL = (0, 'MY_MODEL_INITIAL_STATE')
```
And finally, your `namedtuple` becomes this:
```
EntityStates = MyModelStates((0, 'MY_MODEL_INITIAL_STATE'), ...)
```
Well, good enough, it now makes sure both the state value and the translation stub are mapped to the languages supported by your UI. But now you may notice that the code which uses those mappings has turned into a mess. Whenever you try to assign a value to your entity, you also need not forget to extract value at index 0 from the mapping you use:
```
my_entity.state = INITIAL[0]
```
or
```
my_entity.state = MyModelStates.INITIAL[0]
```
or
```
my_entity.state = EntityStates.INITIAL[0]
```
And so on. Keep in mind that the first two approaches using constants and class attributes, respectively, still suffer from mutability.
#### And then Enums come at the stage
```
class MyEntityStates(Enum):
def __init__(self, val, description):
self.val = val
self.description = description
INITIAL = (0, 'MY_MODEL_INITIAL_STATE')
PROCESSING = (1, 'MY_MODEL_BEING_PROCESSED_STATE')
PROCESSED = (2, 'MY_MODEL_PROCESSED_STATE')
DECLINED = (3, 'MY_MODEL_DECLINED_STATE')
RETURNED = (4, 'MY_MODEL_RETURNED_STATE')
```
That’s it. Now you could easily iterate the enum in your renderer (Jinja2 syntax):
```
{% for state in MyEntityState %}
{{ \_(state.description) }}
{% endfor %}
```
Enum is immutable for both member set (you can’t define a new member at runtime, nor can you delete a member already defined) and those member values they keep (you can’t reassign any attribute values or delete an attribute).
In your code you just assign values to your entities like this:
```
my_entity.state = MyEntityStates.INITIAL.val
```
Well, clear enough. Self-descriptive. Fairly extensible. That’s what we use Enums for.
### Why is it faster?
But the default ENUM is rather slow so we asked ourselves — could we make it faster?
As it turns out, we can. Namely, it is possible to make it:
* 3 times faster on member access
* ~8.5 times faster on attribute (`name`, `value`) access
* 3 times faster on enum access by value (call on enum's class `MyEnum(value)`)
* 1.5 times faster on enum access by name (dict-like `MyEnum[name]`)
Types and objects are dynamic in Python. But Python has the tools to limit the dynamic nature of the objects. With their help one can gain significant performance boost using `__slots__` as well as avoid using Data Descriptors where possible without significant complexity growth or if you can get benefit in speed.
#### Slots
For example, one could use a class declaration with `__slots__` — in this case, class instances would have only a restricted set of attributes: attributes declared in `__slots__` and all `__slots__` of parent classes.
#### Descriptors
By default the Python interpreter returns an attribute value of an object directly:
```
value = my_obj.attribute # this is a direct access to the attribute value by the pointer that the object holds for that attribute
```
According to the Python data model, if the attribute value of an object is itself an object that implements the Data Descriptor Protocol, it means that when you try to get that value you first get the attribute as an object and then a special method `__get__` is called on that attribute-object passing the keeper object itself as an argument:
```
obj_attribute = my_obj.attribute
obj_attribute_value = obj_attribute.__get__(my_obj)
```
#### Enums in Standard Library
At least `name` and `value` attributes of standard Enum implementation are declared as `types.DynamicClassAttribute`. That means that when you try to get a member’s `name` (or `value`) the flow is following:
```
one_value = StdEnum.ONE.value # that is what you write in your code
one_value_attribute = StdEnum.ONE.value
one_value = one_value_attribute.__get__(StdEnum.ONE)
```
```
# and this is what really __get__ does (python 3.7 implementation):
def __get__(self, instance, ownerclass=None):
if instance is None:
if self.__isabstractmethod__:
return self
raise AttributeError()
elif self.fget is None:
raise AttributeError("unreadable attribute")
return self.fget(instance)
```
```
# since DynamicClassAttribute is a decorator on Enum methods `name` and `value` the final row of __get__() ends up with:
@DynamicClassAttribute
def name(self):
"""The name of the Enum member."""
return self._name_
@DynamicClassAttribute
def value(self):
"""The value of the Enum member."""
return self._value_
```
So, the complete flow could be represented as the following pseudo-code:
```
def get_func(enum_member, attrname):
# this is also a __dict__ lookup so hash + hashtable scan also occur
return getattr(enum_member, f'_{attrnme}_')
def get_name_value(enum_member):
name_descriptor = get_descriptor(enum_member, 'name')
if enum_member is None:
if name_descriptor.__isabstractmethod__:
return name_descriptor
raise AttributeError()
elif name_descriptor.fget is None:
raise AttributeError("unreadable attribute")
return get_func(enum_member, 'name')
```
We’ve made a simple script that demonstrates the above conclusion:
```
from enum import Enum
class StdEnum(Enum):
def __init__(self, value, description):
self.v = value
self.description = description
A = 1, 'One'
B = 2, 'Two'
def get_name():
return StdEnum.A.name
from pycallgraph import PyCallGraph
from pycallgraph.output import GraphvizOutput
graphviz = GraphvizOutput(output_file='stdenum.png')
with PyCallGraph(output=graphviz):
v = get_name()
```
And after we’ve run the script it created this picture for us:

This proves that each time you access stdlib enum’s attributes `name` and `value` it calls a descriptor. That descriptor in turn ends up with a call to stdlib enum’s `def name(self)` property decorated with the descriptor.
Well, you can compare this to our FastEnum:
```
from fast_enum import FastEnum
class MyNewEnum(metaclass=FastEnum):
A = 1
B = 2
def get_name():
return MyNewEnum.A.name
from pycallgraph import PyCallGraph
from pycallgraph.output import GraphvizOutput
graphviz = GraphvizOutput(output_file='fastenum.png')
with PyCallGraph(output=graphviz):
v = get_name()
```
Which outputs this picture:

That is what is really done inside standard Enum implementation each time you access `name` and `value` attributes of your Enum members. And that’s why our implementation is faster.
**Python Standard Library’s implementation of Enum class uses tons of descriptor protocol calls.** When we tried to use standard enum in our projects we’ve noticed how many descriptor protocol calls for `name` and `value` attributes of the `Enum` members were invoked. And because enumerations were used excessively throughout the code, the resulting performance was poor.
Furthermore, the standard enum class contains a couple of helper “protected” attributes:
* `_member_names_` — a list that holds all the names of enum members;
* `_member_map_` — an OrderedDict that maps a name of an enum member to the member itself;
* `_value2member_map_` — a reverse dictionary that maps enum member values to corresponding enum members.
Dictionary lookups are slow since each one leads to a hash calculation and a hash table lookup, making those dictionaries non-optimal base structures for the enum class. Even the member retrieval itself (as in `StdEnum.MEMBER`) is a dictionary lookup.
#### Our way
While developing our Enum implementation, we kept in mind those pretty C-language enumerations and the beautiful extensible Java Enums. The main features we wanted in our implementation:
* an Enum must be as static as possible; by “static” we mean: If something could be calculated once and at declaration time, it should;
* an Enum can not be subclassed (must be a “final” class) if a subclass defines new enum members — this is true for standard library implementation, with the exception that subclassing is prohibited even if no new members defined;
* an Enum should have vast possibilities for extensions (additional attributes, methods and so on).
The only time we use dictionary lookups is in a reverse mapping `value` to Enum member. All other calculations are done just once during the class declaration (where metaclasses hooks used to customize type creation).
In contrast to the standard library implementation, we treat the first value after the `=` sign in the class declaration as the member value:
`A = 1, 'One'` in standard library enum the whole tuple `1, "One"` is treated as `value`
`A: 'MyEnum' = 1, 'One'` in our implementation only `1` is treated as `value`
Further speed-up is gained by using `__slots__` whenever possible. In the Python data model classes declared with `__slots__` do not have `__dict__` attribute that holds instance attributes (so you can’t assign any attribute that is not mentioned in `__slots__`). Additionally, attributes defined in `__slots__` accessed at constant offsets to the C-level object pointer. That is high-speed attribute access since it avoids hash calculations and hashtable scans.
### What are the additional perks?
FastEnum is not compatible with any version of Python prior to 3.6, since it excessively uses `typing` module that was introduced in Python 3.6; One could assume that installing a backported `typing` module from PyPI would help. The answer is: no. The implementation uses PEP-484 for some functions and methods arguments and return value type hinting, so any version prior to Python 3.5 is not supported due to syntax incompatibility. But then again, the very first line of code in `__new__` of the metaclass uses PEP-526 syntax for variable type hinting. So Python 3.5 won’t do either. It’s possible to port the implementation to older versions, though we in Qrator Labs tend to use type hinting whenever possible since it helps developing complex projects greatly. And, hey! You don't want to stick to any python prior to 3.6 since there's no backwards incompatibilities with your existing code (assuming you are not using Python 2) though a lot of work was done in asyncio compared to 3.5.
That, in turn, makes special imports like `auto` unnecessary, unlike in standard library. You type-hint all your Enum members with your Enum class name, providing no value at all — and the value would be generated for you automatically. Though python 3.6 is sufficient to work with FastEnum, be warned that the standard dictionary order of declaration guarantee was introduced only in python 3.7. We don’t know any useful appliances where auto-generated value order is important (since we assume the value generated itself is not the value a programmer does care about). Nevertheless, consider yourself warned if you still stick with python 3.6;
Those who need their enum start from 0 (zero) instead of default 1 can do this with a special enum declaration attribute `_ZERO_VALUED`, that attribute is «erased» from the resulting Enum class;
There are some limitations though: all enum member names must be CAPITALIZED or they won’t be picked up by the metaclass and won’t be treated as enum members;
However, you could declare a base class for your enums (keep in mind that base class can use enum metaclass itself, so you don't need to provide metaclass to all subclasses): you may define common logic (attributes and methods) in this class, but may not define enum members (so that class won't be «finalized»). You could then subclass that class in as many enum declarations as you want and that would provide you with all the common logic;
Aliases. We’ll explain them in a separate topic (implemented in 1.2.5)
### Aliases and how they could help
Suppose you have code that uses:
```
package_a.some_lib_enum.MyEnum
```
And that MyEnum is declared like this:
```
class MyEnum(metaclass=FastEnum):
ONE: 'MyEnum'
TWO: 'MyEnum'
```
Now, you decided to make some refactoring and want to move your enum into another package. You create something like this:
```
package_b.some_lib_enum.MyMovedEnum
```
Where MyMovedEnum is declared like this:
```
class MyMovedEnum(MyEnum):
pass
```
Now. You are ready to begin the «deprecation» stage for all the code that uses your enums. You divert direct usages of `MyEnum` to use `MyMovedEnum` (the latter has all its members be proxied into `MyEnum`). You state within your project docs that `MyEnum` is deprecated and will be removed from the code at some point in the future. For example, in the next release. Consider your code saves your objects with enum attributes using pickle. At this point, you use `MyMovedEnum` in your code, but internally all your enum members are still the `MyEnum` instances. Your next step would be to swap declarations of `MyEnum` and `MyMovedEnum` so that `MyMovedEnum` will now not be a subclass of `MyEnum` and declare all its members itself; `MyEnum`, on the other hand, would not declare any members but become just an alias (subclass) of `MyMovedEnum`.
And that concludes it. On the restart of your runtimes on unpickle stage all your enum values will be re-routed into `MyMovedEnum` and become re-bound to that new class. The moment you are sure all your pickled objects have been un(re)pickled with this class organization structure, you are free to make a new release, where previously marked as deprecated your `MyEnum` can be declared obsolete and obliterated from your codebase.
We encourage you to try it! [github.com/QratorLabs/fastenum](https://github.com/QratorLabs/fastenum), [pypi.org/project/fast-enum](https://pypi.org/project/fast-enum/). All credits go to the FastEnum author [santjagocorkez](https://habr.com/en/users/santjagocorkez/). | https://habr.com/ru/post/480600/ | null | null | 2,531 | 52.39 |
Next.js 10 + MikroOrm
Recently I’ve been experimenting with NextJS. Something that I found very compelling was the built in
api page routing. In theory, you can build a fully featured JAMStack app using just Next.js and deploy it to serverless.
While I know many people in practice use the
api routes to proxy requests to external apis, it seems to me that if you wanted to quickly bootstrap an application, you should be able to use an ORM and Database (for me it’s MySQL) of your choice to get up and running. Coming from a Laravel background, I was looking for a solution which reminded me of their Eloquent ORM, or Doctrine, which I use at work. Basic features should be schema generation, migration generation and running, and filtering / query builder.
My first attempts at getting this concept up and running used the popular TypeORM. At first glance, this seems to be the best option. However, in practice, I found the documentation to be sub-par and the support for serverless environments to be poor. I ran into lots of issues with hot module reloading, and reusing the connection to MySQL. If you Google “TypeORM and Next.js”, you will find countless Github issues with no clear resolution.
Around this time, I stumbled across MikroOrm, which seemed to have the same feature set as TypeORM that I was looking for, and a clean API syntax. You can read the authors motivations and comparisons here.
Step 1 — Creating a new project and install MikroORM
Your first step is to create a new next.js project with MikroOrm.
npx create-react-app my-new-project
...npm i @mikro-orm/core @mikro-orm/mysql @mikro-orm/cli reflect-metadata
Step 2 — Configuring Babel and TypeScript
Our next step is to get TypeScript working in the project. On the command line run
touch tsconfig.json
Following this, you should start your dev server by running
npm run dev
It will error out telling you to install some TS type packages. Install those and then restart the server. It should succeed.
While Next.js does have TS support, you need to do a little extra work to get the
@Decorator syntax working. In the root of your project create a file called
.babelrc . Copy the following in there:
{ "presets": ["next/babel"], "plugins": [ "babel-plugin-transform-typescript-metadata", ["@babel/plugin-proposal-decorators", { "legacy": true }], ["@babel/plugin-proposal-class-properties", { "loose": true }] ]}
We now need to also install those packages:
npm i -D babel-plugin-transform-typescript-metadata @babel/plugin-proposal-decorators
Note: @babel/plugin-proposal-class-properties comes installed already so we don’t need to install again. If you have issues with it, just
npm i @babel/plugin-proposal-class-properties
We need an extra tsconfig file, specifically for the ORM. This is because the JS target version for the CLI is requires syntax that the ES5 default target for Next.js does not support. Do this by creating a file called
tsconfig.orm.json . Inside, place the following:
{ "extends": "./tsconfig.json", "compilerOptions": { "module": "commonjs", "target": "es6" }}
Step 3 — Create an entity
Create a folder called
entities in your root directory. In this example, we are going to create a simple
User entity. Inside, create a file called
User.ts . Place the following inside:
import {PrimaryKey,Entity,Property,Unique,} from "@mikro-orm/core";@Entity()export class User { @PrimaryKey() id!: number;
@Property() name!: string; @Property() @Unique() email: string; @Property({ nullable: true }) age?: number; @Property({ nullable: true }) born?: Date; constructor(name: string, email: string) { this.name = name; this.email = email; }}
Step 4— Configure MikroOrm
In your root directory, create a file called
mikro-orm.config.ts
Place the following inside:
import dotenv from "dotenv";dotenv.config();import config from "./config/mikro-orm";export default config;
You see a reference to
./config/mikro-orm . We need to create that file as well now. In the root directory, create a folder called
config and place a file called
mikro-orm.ts inside. The contents of the file are your MikroOrm config, and should be roughly as follows:
import { User } from "../entities/User";import { Options } from "@mikro-orm/core";const config: Options = { dbName: "database-name", type: "mysql", host: process.env.MYSQL_HOST, port: Number(process.env.MYSQL_PORT), user: process.env.MYSQL_USERNAME, password: process.env.MYSQL_PASSWORD, entities: [User], discovery: { disableDynamicFileAccess: false }, debug: process.env.NODE_ENV === "development",};export default config;
Place anything referenced by
process.env.MYSQL_inside a file called .env. In the example repository I have create one that can be filled out.
Our last step is to configure our
package.json to use the new
tsconfig.orm.json that we made. The top of mine looks something like this:
{ "name": "mikro-orm-nextjs", "version": "0.1.0", "private": true, "mikro-orm": { "useTsNode": true, "tsConfigPath": "./tsconfig.orm.json", "configPaths": [ "./config/mikro-orm.ts" ] }
...
}
To check if everything you’ve done at this point is working, i’d recommend running
npx mikro-orm debug in the terminal. Your output should contain all the configuration thus far, and not contain any errors.
Step 5 — Using MikroOrm: A contrived example
Once you have your entity set up and the CLI tool working, you need to start working with your database. To do this, we need to create our initial migration. This is done by using the CLI tool to create our first migration:
npx mikro-orm migration:create --initial
A folder named migrations should appear in your root directory, with a file containing the migration logic. Example output:
Now that we have successfully create our migration, we need to run it to create changes to the database. This accomplished by running
npx mikro-orm migration:up
Once that successfully completes, your database should contain an empty table named users, with the columns
id, name, email, age, born .
To use our new database table and create queries, we head back into Next.js. Create a folder in pages called
api and create a new file called
users.js with the following inside:
import 'reflect-metadata';
import { MikroORM } from "@mikro-orm/core";
import config from "../../config/mikro-orm";
import { User } from "../../entities/User";
export default async (req, res) => { const orm = await MikroORM.init(config); const users = await orm.em.find(User); res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify({ user: users }));};
Returned should be an empty. If you wanted to create another API route which contains a user, the syntax would be something like:
const user = new User("Example User", "example@example.com")
await orm.em.persistAndFlush([user]);
At this point, however, you should be up and running with MikroOrm, whatever you do with it at this point is up to you. If you read the fantastic MikroOrm Docs you should have no problem creating your own API and frontend!
If you want to use my repo as a starting place, feel free to clone it and modify or fork. If you see anything wrong in this repo, feel free to reach out on Github or comment on here. | https://jonahallibonetech.medium.com/next-js-9-mikroorm-eb6f6e08e1a1 | CC-MAIN-2021-17 | refinedweb | 1,171 | 58.79 |
#include "dmx.h"
#include "dmxprop.h"
#include "dmxlog.h"
We could analyze the names used for the DMX "backend displays" (e.g., the names passed to the -display command-line parameter), but there are many possible names for a single X display, and failing to detect sameness leads to very unexpected results. Therefore, whenever the DMX server opens a window on a backend X server, a property value is queried and set on that backend to detect when another window is already open on that server.
Further, it is possible that two different DMX server instantiations both have windows on the same physical backend X server. This case is also detected so that pointer input is not taken from that particular backend X server.
The routines in this file handle the property management. | http://dmx.sourceforge.net/html/dmxprop_8c.html | CC-MAIN-2017-17 | refinedweb | 133 | 55.24 |
import "gopkg.in/square/go-jose.v1/json"
Package
Compact appends to dst the JSON-encoded src with insignificant space characters elided..
Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON object.
Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless
- the field's tag is "-", or - the field is empty and its tag specifies the "omitempty" option.
The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options. Examples:
// Field is ignored by this package. Field int `json:"-"` //, dollar signs, percent signs, hyphens, underscores and slashes. be string; the map keys are used as JSON object keys, subject to the UTF-8 coercion described for string values above.
Pointer values encode as the value pointed to. A nil pointer encodes as the null JSON object.
Interface values encode as the value contained in the interface. A nil interface value encodes as the null JSON object..
MarshalIndent is like Marshal but applies Indent to format the output. string-key.
A Decoder reads and decodes JSON objects from an input stream..
More reports whether there is another element in the current array or object being parsed..
UseNumber causes the Decoder to unmarshal a number into an interface{} as a Number instead of as a float64.
A Delim is a JSON array or object delimiter, one of [ ] { or }.
An Encoder writes JSON objects to an output stream.
NewEncoder returns a new encoder that writes to w.
Encode writes the JSON encoding of v to the stream, followed by a newline character.
See the documentation for Marshal for details about the conversion of Go values to JSON.. objects that can marshal themselves into valid JSON.
func (e *MarshalerError) Error() string
A Number represents a JSON number literal.
Float64 returns the number as a float64.
Int64 returns the number as an int64.
String returns the literal text of the number.
RawMessage is a raw encoded JSON object. It implements Marshaler and Unmarshaler and can be used to delay JSON decoding or precompute a JSON encoding. (e *UnmarshalTypeError) Error() string
Unmarshaler is the interface implemented by objects that can unmarshal a JSON description of themselves. The input can be assumed to be a valid encoding of a JSON value. UnmarshalJSON must copy the JSON data if it wishes to retain the data after returning.
An UnsupportedTypeError is returned by Marshal when attempting to encode an unsupported value type.
func (e *UnsupportedTypeError) Error() string
func (e *UnsupportedValueError) Error() string
Package json imports 16 packages (graph) and is imported by 5 packages. Updated 2018-03-23. Refresh now. Tools for package owners. | https://godoc.org/gopkg.in/square/go-jose.v1/json | CC-MAIN-2018-26 | refinedweb | 504 | 57.67 |
CodePlexProject Hosting for Open Source Software
Hi,
I am new to blogengine (after struggling with WP) and am using this tool already.
It made immediate sense to me as I do not see the usefulness of having a backend database for the content of my pages. The Search Engines don't care about DB's, just relevant content on the page.
One thing amazed me when visiting the BlogEngine site.
Whenever searching, through the google toolbar, for something like "BlogEngine Themes" and from the SERP clicking on the blogengine link I see the first line: You Searched for "BlogEngine Themes"
Is there some sort of script for this? I could use it extremely well in a different context.
Hoping for an answer soon.
Theres a Search On Search Control in BlogEngine already.
<blog:SearchOnSearch ID="SearchOnSearch1"
2: runat="server" MaxResults="5"
3: Headline="You searched for"
4: Text="Here are some results for the
5: search term on this website" />
<blog:SearchOnSearch ID="SearchOnSearch1"
2: runat="server" MaxResults="5"
3: Headline="You searched for"
4: Text="Here are some results for the
5: search term on this website" />
Put that in your master page. Should be in the default theme already.
using System;
using System.Collections.Generic;
using System.Web;
static public class ReferrerList
{
/// <summary>
/// List of referrer strings.
/// </summary>
static public List<string> Referrers { get; set; }
/// <summary>
/// Add a referrer string from current request.
/// </summary>
static public void AddReferrer()
{
Uri referrer = HttpContext.Current.Request.UrlReferrer;
if (referrer != null)
{
string original = referrer.OriginalString.ToLower();
Referrers.Insert(0, original);
}
}
static ReferrerList()
{
Referrers = new List<string>();
}
}
Java Blog
Are you sure you want to delete this post? You will not be able to recover it later.
Are you sure you want to delete this thread? You will not be able to recover it later. | http://blogengine.codeplex.com/discussions/253829 | CC-MAIN-2017-09 | refinedweb | 302 | 66.64 |
The current cloud inventory for one of the SaaS applications at our firm is as follows:
- Web server: Centos 6.4 + NGINX + MySql + PHP + Drupal
- Mail server: Centos 6.4 + Postfix + Dovecot + Squirrelmail
A quick test on Pingdom showed a load time of 3.92 seconds for a page size of 2.9MB with 105 requests.
Tests using Apache Bench ab -c1 -n500 yielded almost the same figuresa mean response time of 2.52 seconds.
We wanted to improve the page load times by caching the content upstream, scaling the site to handle much greater http workloads, and implementing a failsafe mechanism.
The first step was to handle all incoming http requests from anonymous users that were loading our Web server. Since anonymous users are served content that seldom changes, we wanted to prevent these requests from reaching the Web server so that its resources would be available to handle the requests from authenticated users. Varnish was our first choice to handle this.
Our next concern was to find a mechanism to handle the SSL requests mainly on the sign-up pages, where we had interfaces to Paypal. Our aim was to include a second Web server that handled a portion of the load, and we wanted to configure Varnish to distribute http traffic using a round-robin mechanism between these two servers. Subsequently, we planned on configuring Varnish in such a way that even if the Web servers were down, the system would continue to serve pages. During the course of this exercise we documented our experiences and thats what youre reading about here.
A word about Varnish
Varnish is a Web application accelerator or reverse proxy. Its installed in front of the Web server to handle HTTP requests. This way, it speeds up the site and improves the performance significantly. In some cases, it can improve the performance of a site by 300 to 1000 times.
It does this by caching the Web pages and when visitors come to the site, Varnish serves the cached pages rather than requesting the Web server for it. Thus the load on the Web server reduces. This method improves the sites performance and scalability. It can also act as a failsafe method if the Web server goes down because Varnish will continue to serve the cached pages in the absence of the Web server.
With that said, lets begin by installing Varnish on a VPS, and then connect it to a single NGINX Web server. Then lets add another NGINX Web server so that we can implement a failsafe mechanism. This will accomplish the performance goals that we stated. So lets get started. For the rest of the article, lets assume that you are using the Centos 6.4 OS. However, we have provided information for Ubuntu users wherever we felt it was necessary.
Enable the required repositories
First enable the appropriate repositories. For Centos, Varnish is available from the EPEL repository. Add this repository to your repos list, but before you do so, youll need to import the GPG keys. So open a terminal and enter the following commands:
[[email protected] sridhar]#wget [[email protected] sridhar]#mv 0608B895.txt /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 [[email protected] sridhar]#rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 [[email protected] sridhar]#rpm -qa gpg* gpg-pubkey-c105b9de-4e0fd3a3
After importing the GPG keys you can enable the repository.
To verify if the new repositories have been added to the repo list, run the following command and check the output to see if the repository has been added:
If you happen to use an Ubuntu VPS, then you should use the following commands to enable the repositories:
[[email protected] sridhar]# wget [[email protected] sridhar]# apt-key add GPG-key.txt [[email protected] sridhar]# echo deb precise varnish-3.0 | sudo tee -a /etc/apt/sources.list [[email protected] sridhar]# sudo apt-get update
Installing Varnish
Once the repositories are enabled, we can install Varnish:
On Ubuntu, you should run the following command:
After a few seconds, Varnish will be installed. Lets verify the installation before we go further. In the terminal, enter the following command the output should contain the lines that follow the input command (we have reproduced only a few lines for the sake of clarity).
[[email protected] sridhar]## yum info varnish Installed Packages Name : varnish Arch : i686 Version : 3.0.5 Release : 1.el6 Size : 1.1 M Repo : installed
That looks good; so we can be sure that Varnish is installed. Now, lets configure Varnish to start up on boot. In case you have to restart your VPS, Varnish will be started automatically.
Having done that, lets now start Varnish:
We have now installed Varnish and its up and running. Lets configure it to cache the pages from our NGINX server.
Basic Varnish configuration
The Varnish configuration file is located in /etc/sysconfig/varnish for Centos and /etc/default/varnish for Ubuntu.
Open the file in your terminal using the nano or vim text editors. Varnish provides us three ways of configuring it. We prefer Option 3. So for our 2GB server, the configuration steps are as shown below (the lines with comments have been stripped off for the sake of clarity):
NFILES=131072 MEMLOCK=82000 RELOAD_VCL=1 VARNISH_VCL_CONF=/etc/varnish/default.vcl VARNISH_LISTEN_PORT=80 , :443 VARNISH_ADMIN_LISTEN_ADDRESS=127.0.0.1 VARNISH_ADMIN_LISTEN_PORT=6082 VARNISH_SECRET_FILE=/etc/varnish/secret VARNISH_MIN_THREADS=50 VARNISH_MAX_THREADS=1000 VARNISH_STORAGE_FILE=/var/lib/varnish/varnish_storage.bin VARNISH_STORAGE_SIZE=1 \ -p thread_pool_add_delay=2 \ -p thread_pools=2 \ -p thread_pool_min=400 \ -p thread_pool_max=4000 \ -p session_linger=50 \ -p sess_workspace=262144 \ -S ${VARNISH_SECRET_FILE} \ -s ${VARNISH_STORAGE}
The first line when substituted with the variables will read -a :80,:443 and instruct Varnish to serve all requests made on Ports 80 and 443. We want Varnish to serve all http and https requests.
To set the thread pools, first determine the number of CPU cores that your VPS uses and then update the directives.
[[email protected] sridhar]# grep processor /proc/cpuinfo processor : 0 processor : 1
This means you have two cores.
The formula to use is:
-p thread_pools=<Number of CPU cores> \ -p thread_pool_min=<800 / Number of CPU cores> \
The -s ${VARNISH_STORAGE} translates to -s malloc,1G after variable substitution and is the most important directive. This allocates 1GB of RAM for exclusive use by Varnish. You could also specify -s file,/var/lib/varnish/varnish_storage.bin,10G which tells Varnish to use the file caching mechanism on the disk and that 10GB has been allocated to it. Our suggestion is that you should use the RAM.
Configure the default.vcl file
The default.vcl file is where you will have to make most of the configuration changes in order to tell Varnish about your Web servers, assets that shouldnt be cached, etc. Open the default.vcl file in your favourite editor:
Since we expect to have two NGINX servers running our application, we want Varnish to distribute the http requests between these two servers. If, for any reason, one of the servers fails, then all requests should be routed to the healthy server. To do this, add the following to your default.vcl file:
backend bw1 { .host = 146.185.129.131; .probe = { .url = /google0ccdbf1e9571f6ef.html; .interval = 5s; .timeout = 1s; .window = 5; .threshold = 3; }} backend bw2 { .host = 37.139.24.12; .probe = { .url = /google0ccdbf1e9571f6ef.html; .interval = 5s; .timeout = 1s; .window = 5; .threshold = 3; }} backend bw1ssl { .host = 146.185.129.131; .port = 443; .probe = { .url = /google0ccdbf1e9571f6ef.html; .interval = 5s; .timeout = 1s; .window = 5; .threshold = 3; }} backend bw2ssl { .host = 37.139.24.12; .port = 443; .probe = { .url = /google0ccdbf1e9571f6ef.html; .interval = 5s; .timeout = 1s; .window = 5; .threshold = 3; }} director default_director round-robin { { .backend = bw1; } { .backend = bw2; } } director ssl_director round-robin { { .backend = bw1ssl; } { .backend = bw2ssl; } } sub vcl_recv { if (server.port == 443) { set req.backend = ssl_director; } else { set req.backend = default_director; } }
You might have noticed that we have used public IP addresses since we had not enabled private networking within our servers. You should define the backends one each for the type of traffic you want to handle. Hence, we have one set to handle http requests and another to handle the https requests.
Its a good practice to perform a health check to see if the NGINX Web servers are up. In our case, we kept it simple by checking if the Google webmaster file was present in the document root. If it isnt present, then Varnish will not include the Web server in the round robin league and wont redirect traffic to it.
.probe = { .url = /google0ccdbf1e9571f6ef.html;
The above command checks the existence of this file at each backend. You can use this to take an NGINX server out intentionally either to update the version of the application or to run scheduled maintenance checks. All you have to do is to rename this file so that the check fails!
In spite of our best efforts to keep our servers sterile, there are a number of reasons that can cause a server to go down. Two weeks back, we had one of our servers go down, taking more than a dozen sites with it because the master boot record of Centos was corrupted. In such cases, Varnish can handle the incoming requests even if your Web server is down. The NGINX Web server sets an expires header (HTTP 1.0) and the max-age (HTTP 1.1) for each page that it serves. If set, the max-age takes precedence over the expires header. Varnish is designed to request the backend Web servers for new content every time the content in its cache goes stale. However, in a scenario like the one we faced, its impossible for Varnish to obtain fresh content. In this case, setting the Grace in the configuration file allows Varnish to serve content (stale) even if the Web server is down. To have Varnish serve the (stale) content, add the following lines to your default.vcl:
sub vcl_recv { set req.grace = 6h; } sub vcl_fetch { set beresp.grace = 6h; } if (!req.backend.healthy) { unset req.http.Cookie; }
The last segment tells Varnish to strip all cookies for an authenticated user and serve an anonymous version of the page if all the NGINX backends are down.
Most browsers support encoding but report it differently. NGINX sets the encoding as Vary: Cookie, Accept-Encoding. If you dont handle this, Varnish will cache the same page once each, for each type of encoding, thus wasting server resources. In our case, it would gobble up memory. So add the following commands to the vcl_recv to have Varnish cache the content only once:
if (req.http.Accept-Encoding) { if (req.http.Accept-Encoding ~ gzip) { # If the browser supports it, well use gzip. set req.http.Accept-Encoding = gzip; } else if (req.http.Accept-Encoding ~ deflate) { # Next, try deflate if it is supported. set req.http.Accept-Encoding = deflate; } else { # Unknown algorithm. Remove it and send unencoded. unset req.http.Accept-Encoding; } }
Now, restart Varnish.
Additional configuration for content management systems, especially Drupal
A CMS like Drupal throws up additional challenges when configuring the VCL file. Well need to include additional directives to handle the various quirks. You can modify the directives below to suit the CMS that you are using. When using CMSs like Drupal if there are files that you dont want cached for some reason, add the following commands to your default.vcl file in the vcl_recv section:
if (req.url ~ ^/status\.php$ || req.url ~ ^/update\.php$ || req.url ~ ^/ooyala/ping$ || req.url ~ ^/admin/build/features || req.url ~ ^/info/.*$ || req.url ~ ^/flag/.*$ || req.url ~ ^.*/ajax/.*$ || req.url ~ ^.*/ahah/.*$) { return (pass); }
Varnish sends the length of the content (see the Varnish log output above) so that browsers can display the progress bar. However, in some cases when Varnish is unable to tell the browser the specified content-length (like streaming audio) you will have to pass the request directly to the Web server. To do this, add the following command to your default.vcl:
if (req.url ~ ^/content/music/$) { return (pipe); }
Drupal has certain files that shouldnt be accessible to the outside world, e.g., Cron.php or Install.php. However, you should be able to access these files from a set of IPs that your development team uses. At the top of default.vcl include the following by replacing the IP address block with that of your own:
acl internal { 192.168.1.38/46; }
Now to prevent the outside world from accessing these pages well throw an error. So inside of the vcl_recv function include the following:
if (req.url ~ ^/(cron|install)\.php$ && !client.ip ~ internal) { error 404 Page not found.; }
If you prefer to redirect to an error page, then use this instead:
if (req.url ~ ^/(cron|install)\.php$ && !client.ip ~ internal) { set req.url = /404; }
Our approach is to cache all assets like images, JavaScript and CSS for both anonymous and authenticated users. So include this snippet inside vcl_recv to unset the cookie set by Drupal for these assets:
if (req.url ~ (?i)\.(png|gif|jpeg|jpg|ico|swf|css|js|html|htm)(\?[a-z0-9]+)?$) { unset req.http.Cookie; }
Drupal throws up a challenge especially when you have enabled several contributed modules. These modules set cookies, thus preventing Varnish from caching assets. Google analytics, a very popular module, sets a cookie. To remove this, include the following in your default.vcl:
set req.http.Cookie = regsuball(req.http.Cookie, (^|;\s*)(__[a-z]+|has_js)=[^;]*
If there are other modules that set JavaScript cookies, then Varnish will cease to cache those pages; in which case, you should track down the cookie and update the regex above to strip it.
Once you have done that, head to /admin/config/development/performance, enable the Page Cache setting and set a non-zero time for Expiration of cached pages.
Then update the settings.php with the following snippet by replacing the IP address with that of your machine running Varnish.
$conf[reverse_proxy] = TRUE; $conf[reverse_proxy_addresses] = array(37.139.8.42); $conf[page_cache_invoke_hooks] = FALSE; $conf[cache] = 1; $conf[cache_lifetime] = 0; $conf[page_cache_maximum_age] = 21600;
You can install the Drupal varnish module (), which provides better integration with Varnish and include the following lines in your settings.php:
$conf[cache_backends] = array(sites/all/modules/varnish/varnish.cache.inc); $conf[cache_class_cache_page] = VarnishCache;
Checking if Varnish is running and
serving requests
Instead of logging to a normal log file, Varnish logs to a shared memory segment. Run varnishlog from the command line, access your IP address/ URL from the browser and view the Varnish messages. It is not uncommon to see a 503 service unavailable message. This means that Varnish is unable to connect to NGINX. In which case, you will see an error line in the log (only the relevant portion of the log is reproduced for clarity).
[[email protected] sridhar]# Varnishlog 12 StatSess c 122.164.232.107 34869 0 1 0 0 0 0 0 0 12 SessionOpen c 122.164.232.107 34870 :80 12 ReqStart c 122.164.232.107 34870 1343640981 12 RxRequest c GET 12 RxURL c / 12 RxProtocol c HTTP/1.1 12 RxHeader c Host: 37.139.8.42 12 RxHeader c User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:27.0) Gecko/20100101 Firefox/27.0 12 RxHeader c Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 12 RxHeader c Accept-Language: en-US,en;q=0.5 12 RxHeader c Accept-Encoding: gzip, deflate 12 RxHeader c Referer: 12 RxHeader c Cookie: __zlcmid=OAdeVVXMB32GuW 12 RxHeader c Connection: keep-alive 12 FetchError c no backend connection 12 VCL_call c error 12 TxProtocol c HTTP/1.1 12 TxStatus c 503 12 TxResponse c Service Unavailable 12 TxHeader c Server: Varnish 12 TxHeader c Retry-After: 0 12 TxHeader c Content-Type: text/html; charset=utf-8 12 TxHeader c Content-Length: 686 12 TxHeader c Date: Thu, 03 Apr 2014 09:08:16 GMT 12 TxHeader c X-Varnish: 1343640981 12 TxHeader c Age: 0 12 TxHeader c Via: 1.1 varnish 12 TxHeader c Connection: close 12 Length c 686
Resolve the error and you should have Varnish running. But that isnt enoughwe should check if its caching the pages. Fortunately, the folks at the following URL have made it simple for us.
Check if Varnish is serving pagesVisit, provide your URL/IP address and you should see your Gold Star! (See Figure 3.) If you dont, but instead see other messages, it means that Varnish is running but not caching.
Then you should look at your code and ensure that it sends the appropriate headers. If you are using a content management system, particularly Drupal, you can check the additional parameters in the VCL file and set them correctly. You have to enable caching in the performance page.
Running the tests
Running Pingdom tests showed improved response times of 2.14 seconds. If you noticed, there was an improvement in the response time in spite of having the payload of the page increasing from 2.9MB to 4.1MB. If you are wondering why it increased, remember, we switched the site to a new theme.
Apache Bench reports better figures at 744.722 ms.
Configuring client IP forwarding
Check the IP address for each request in the access logs of your Web servers. For NGINX, the access logs are available at /var/log/nginx and for Apache, they are available at /var/log/httpd or /var/log/apache2, depending on whether you are running Centos or Ubuntu.
Its not surprising to see the same IP address (of the Varnish machine) for each request. Such a configuration will throw all Web analytics out of gear. However, there is a way out. If you run NGINX, try out the following procedure. Determine the NGINX configuration that you currently run by executing the command below in your command line:
Look for the with-http_realip_module. If this is available, add the following to your NGINX configuration file in the http section. Remember to replace the IP address with that of your Varnish machine. If Varnish and NGINX run on the same machine, do not make any changes.
set_real_ip_from 127.0.0.1; real_ip_header X-Forwarded-For;
Restart NGINX and check the logs once again. You will see the client IP addresses.
If you are using Drupal then include the following line in settings.php:
$conf[reverse_proxy_header] = HTTP_X_FORWARDED_FOR;
Other Varnish tools
Varnish includes several tools to help you as an administrator.
varnishstat -1 -f n_lru_nuked: This shows the number of objects nuked from the cache.
Varnishtop: This reads the logs and displays the most frequently accessed URLs. With a number of optional flags, it can display a lot more information.
Varnishhist: Reads the shared memory logs, and displays a histogram showing the distribution of the last N requests on the basis of their processing.
Varnishadm: A command line utility for Varnish.
Varnishstat: Displays the statistics.
Dealing with SSL: SSL-offloader, SSL-accelerator and SSL-terminator
SSL termination is probably the most misunderstood term in the whole mix. The mechanism of SSL termination is employed in situations where the Web traffic is heavy. Administrators usually have a proxy to handle SSL requests before they hit Varnish. The SSL requests are decrypted and the unencrypted requests are passed to the Web servers. This is employed to reduce the load on the Web servers by moving the decryption and other cryptographic processing upstream.
Since Varnish by itself does not process or understand SSL, administrators employ additional mechanisms to terminate SSL requests before they reach Varnish. Pound () and Stud () are reverse proxies that handle SSL termination. Stunnel () is a program that acts as a wrapper that can be deployed in front of Varnish. Alternatively, you could also use another NGINX in front of Varnish to terminate SSL.
However, in our case, since only the sign-in pages required SSL connections, we let Varnish pass all SSL requests to our backend Web server.
Additional repositories
There are other repositories from where you can get the latest release of Varnish:
wget repo.varnish-cache.org/redhat/varnish-3.0/el6/noarch/varnish-release/varnish-release-3.0-1.el6.noarch.rpm rpm nosignature -i varnish-release-3.0-1.el6.noarch.rpm
If you have the Remi repo enabled and the Varnish cache repo enabled, install them by specifying the defined repository.
Yum install varnish enablerepo=epel Yum install varnish enablerepo=varnish-3.0
Our experience has been that Varnish reduces the number of requests sent to the NGINX server by caching assets, thus improving page response times. It also acts as a failover mechanism if the Web server fails.
We had over 55 JavaScript files (two as part of the theme and the others as part of the modules) in Drupal and we aggregated JavaScript by setting the flag in the Performance page. We found a 50 per cent drop in the number of requests; however, we found that some of the JavaScript files were not loaded on a few pages and had to disable the aggregation. This is something we are investigating. Our recommendation is not to choose the aggregate JavaScript files in your Drupal CMS. Instead, use the Varnish module ().
The module allows you to set long object lifetimes (Drupal doesnt set it beyond 24 hours), and use Drupals existing cache expiration logic to dynamically purge Varnish when things change.
You can scale this architecture to handle higher loads either vertically or horizontally. For vertical scaling, resize your VPS to include additional memory and make that available to Varnish using the -s directive.
To scale horizontally, i.e., to distribute the requests between several machines, you could add additional Web servers and update the round robin directives in the VCL file.
You can take it a bit further by including HAProxy right upstream and have HAProxy route requests to Varnish, which then serves the content or passes it downstream to NGINX.
To remove a Web server from the round robin league, you can improve upon the example that we have mentioned by writing a small PHP snippet to automatically shut down or exit() if some checks fail.
References
[1]
[2]
[3] | https://opensourceforu.com/2014/10/boost-the-performance-of-cloudstack-with-varnish/ | CC-MAIN-2018-22 | refinedweb | 3,704 | 56.66 |
Generating seed data for PHPUnit testsApr 16, 2009 Python Tweet
I'm working on a pretty massive test harness for a custom framework extension - I won't bore anyone with the details, but I'm using PHPUnit, and for our particular implementation I needed to generate large numbers of XML files to seed a test database with about 80 tables.
Two things I already had were 1) a list of all the tables:
And 2) list of the columns in each table:
tables = ['product_links', 'product_type', 'reviews']
(I had these on hand from a previous project, but by all means, if you know of an alternative to SHOW COLUMNS or DESCRIBE that returns only the column names, please let me know.)
cols_product_type = ['id', 'title', 'description', 'active', 'approved', 'deprecated']
db = Database.connect("myhost", "username", "passwd", "dbname")
cursor = db.cursor()
def report(table):
a = open(table + "_seed.xml", "w")
cols = eval('cols_'+table)
a.write('<?xml version="1.0" encoding="UTF-8"?>\n\r<dataset>\n\r')
sql = """SELECT * FROM %s""" %(table)
cursor.execute(sql)
rows = cursor.fetchall()
for row in rows:
a.write('<' + table + ' ')
loopcount = len(cols)
for n in range(0, loopcount):
a.write(cols[n] + '="' + str(row[n]) + '" ')
a.write(' />\n\r')
a.write('')
for table in tables:
report(table)
cursor.close()
db.close() | http://www.mechanicalgirl.com/post/generating-seed-data-phpunit-tests/ | CC-MAIN-2020-50 | refinedweb | 214 | 57.77 |
Fred L. Drake wrote: > > I. The DTD wasn't attached :-) Nevertheless, I feel that the metadata element has very little purpose. Given the presence of XML Namespaces (), I don't think that the metadata tag adds any value. Rather than use <metadata owner="">, we can use <app:mytag xmlns:. Of course, there are other ways to specify the use of a namespace, but the point is that a "metadata-like" facility has already been defined in a standardized fashion (with the caveat of minor perturbations to the working draft prior to IETF acceptance). <info> still adds some value, in that the spec can say "app-specific extensions should go into the <info> element; any application should retain all child elements of the <info> element when manipulating items in the XBEL document." %common.attrs% is not very useful as an extension. It is located to broadly for somebody to extend the DTD. If you try to add something into %common.attr% it shows up EVERYWHERE. eek. Personally, I'm of the mind that somebody can issue a second version of the DTD, rather than attempt to extend it. At the present time, I'm not aware of apps that actually make use of extending a DTD. Why should we make an attempt which might not even be in the right direction? I'd say: let some precedent exist before biting this off. Further, given the presence of XML namespaces, an XBEL document can simply be incorporated *within* another XML document. i.e. extension via containment, rather than extension via derivation. The simplest designs always seem to be the most used designs, in my book. :-) (and I'm a big fan of KISS) Cheers, -g -- Greg Stein (gstein@lyra.org) | https://mail.python.org/pipermail/xml-sig/1998-October/000422.html | CC-MAIN-2017-22 | refinedweb | 288 | 64.51 |
hi
how can i convert all the keys for the user how enter for example his passwort
to char ********
hi
how can i convert all the keys for the user how enter for example his passwort
to char ********
It depends on your OS and compiler.
Do a board search, this is a common question.
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
Here's a Windows API version. Remember to include windows.h...
Code:char *getPass(char *szBuffer, size_t len) { size_t i; HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE); HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); DWORD dwOld, dwNumRead, dwNumWritten; if((hIn) && (hOut)) { if(GetConsoleMode(hIn,&dwOld)) { if(SetConsoleMode(hIn,ENABLE_PROCESSED_INPUT)) { for(i=0;i<len;i++) { if(ReadConsole(hIn,&szBuffer[i],1,&dwNumRead,NULL)) { if(szBuffer[i] == '\r') { WriteConsole(hOut,"\n",1,&dwNumWritten,NULL); szBuffer[i] = '\0'; break; } else WriteConsole(hOut,"*",1,&dwNumWritten,NULL); } else break; } SetConsoleMode(hIn,dwOld); return szBuffer; } } } return NULL; }
If using the WIN32 API, the edit control has a 'password' style ES_PASSWORD which will automatically replace text with asteri
but what is the size_t ......................
size_t is a data type in the standard C library, inside stdio.h. If size_t is not defined in windows.h, which I believe it is, you can include it in your C++ program by including cstdio.
GIYF.
Last edited by MacGyver; 05-22-2007 at 08:26 AM.
I think size_t is associated with <cstddef>.
Edit: Actually the same site indicates that it's also in <cstdio>. I'm confused. Why is it guaranteed to be defined in more than one standard header file?
Edit: This is important to me since my code uses std::size_t a lot (and I always qualify it with std:: since I don't think it's guaranteed to be in the global namespace).
Last edited by robatino; 05-22-2007 at 09:51 AM.
This site names 4 header files where size_t is define:
- stdio.h
- stddef.h
- stdlib.h
- string.h
The date type is important for strings, as well as malloc() and other functions, so I guess they chose the route of defining it quite a few times as opposed to just keeping it in one header file that all the others would be dependent upon. | https://cboard.cprogramming.com/cplusplus-programming/90081-convert-all-keys-*****.html | CC-MAIN-2017-04 | refinedweb | 395 | 52.49 |
The:
See the topics in this section for more specific limitations of the xml data type.
XML Data Type Variables and Columns
Describes how to create, modify, and use xml data type variables and columns.
Typed XML Compared to Untyped XML
Defines typed and untyped XML. Describes XML schemas and explains how to register an XML schema collection.
Generating XML Instances
Describes different methods for generating XML instances.
xml Data Type Methods
Describes the xml data type methods.
Setting Options (XML Data Type)
Describes the options that you must set when you query xml data type columns or variables.
Adding Namespaces Using WITH XMLNAMESPACES
Describes how to add namespaces by using a WITH XMLNAMESPACES clause.
XML Data Modification Language (XML DML)
Describes the XML Data Modification Language and its three keywords.
Indexes on XML Data Type Columns
Describes how to create, modify, and use primary and secondary XML indexes.
Serialization of XML Data
Explains how XML data is serialized and describes entitization of XML characters.
Working with the XML Data Type in Applications
Describes the options that are available to you for working with the xml data type in applications.
xml Data Type Representation in the AdventureWorks Database
Describes the xml type columns in the AdventureWorks database.
Refer to my blog for
Jeff Fischer | http://msdn.microsoft.com/en-us/library/ms189887.aspx | crawl-002 | refinedweb | 214 | 55.95 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.