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 |
|---|---|---|---|---|---|
Print the specified inputs.
Aliases:
tf.compat.v1.print
tf.compat.v2.print
tf.print( *inputs, **kwargs )
Used in the guide:
Used in the tutorials:
A TensorFlow operator that prints the specified inputs to a desired output stream or logging level. The inputs may be dense or sparse Tensors, primitive python objects, data structures that contain tensors, and printable Python objects. Printed tensors will recursively show the first and last elements of each dimension to summarize.
Example:
Single-input usage:
tensor = tf.range(10) tf.print(tensor, output_stream=sys.stderr)
(This prints "[0 1 2 ... 7 8 9]" to sys.stderr)
Multi-input usage:
tensor = tf.range(10) tf.print("tensors:", tensor, {2: tensor * 2}, output_stream=sys.stdout)
(This prints "tensors: [0 1 2 ... 7 8 9] {2: [0 2 4 ... 14 16 18]}" to sys.stdout)
Changing the input separator:
tensor_a = tf.range(2) tensor_b = tensor_a * 2 tf.print(tensor_a, tensor_b, output_stream=sys.stderr, sep=',')
(This prints "[0 1],[0 2]" to sys.stderr)
Usage in a
tf.function:
@tf.function def f(): tensor = tf.range(10) tf.print(tensor, output_stream=sys.stderr) return tensor range_tensor = f()
(This prints "[0 1 2 ... 7 8 9]" to sys.stderr)
@compatibility(TF 1.x Graphs and Sessions)
In graphs manually created outside of
tf.function, this method returns
the created TF operator that prints the data. To make sure the
operator runs, users need to pass the produced op to
tf.compat.v1.Session's run method, or to use the op as a control
dependency for executed ops by specifying
with tf.compat.v1.control_dependencies([print_op]).
@end_compatibility
Compatibility usage in TF 1.x graphs:
sess = tf.compat.v1.Session() with sess.as_default(): tensor = tf.range(10) print_op = tf.print("tensors:", tensor, {2: tensor * 2}, output_stream=sys.stdout) with tf.control_dependencies([print_op]): tripled_tensor = tensor * 3 sess.run(tripled_tensor)
(This prints "tensors: [0 1 2 ... 7 8 9] {2: [0 2 4 ... 14 16 18]}" to sys.stdout)
Args:
*inputs: Positional arguments that are the inputs to print. Inputs in the printed output will be separated by spaces. Inputs may be python primitives, tensors, data structures such as dicts and lists that may contain tensors (with the data structures possibly nested in arbitrary ways), and printable python objects.
output_stream: The output stream, logging level, or file to print to. Defaults to sys.stderr, but sys.stdout, tf.compat.v1.logging.info, tf.compat.v1.logging.warning, tf.compat.v1.logging.error, absl.logging.info, absl.logging.warning and absl.loogging,error are also supported. To print to a file, pass a string started with "file://" followed by the file path, e.g., "".
summarize: The first and last
summarizeelements within each dimension are recursively printed per Tensor. If None, then the first 3 and last 3 elements of each dimension are printed for each tensor. If set to -1, it will print all elements of every tensor.
sep: The string to use to separate the inputs. Defaults to " ".
end: End character that is appended at the end the printed string. Defaults to the newline character.
name: A name for the operation (optional).
Returns:
None when executing eagerly. During graph tracing this returns
a TF operator that prints the specified inputs in the specified output
stream or logging level. This operator will be automatically executed
except inside of
tf.compat.v1 graphs and sessions.
Raises:
ValueError: If an unsupported output stream is specified.
Python2 Compatibility
In python 2.7, make sure to import the following:
from __future__ import print_function | https://www.tensorflow.org/api_docs/python/tf/print?hl=cs | CC-MAIN-2019-43 | refinedweb | 585 | 54.49 |
In this tutorial, you are going to learn how to set up Next.js with TypeScript and TailwindCSS. Firstly, we are going to add TypeScript, and afterwards TailwindCSS. The purpose of the tutorial is to help you set up a project with these three technologies.
Once you complete the tutorial, you have a functional Next.js application with TypeScript and TailwindCSS. You can build on it and create a useful application!
Whenever you feel confused about where to add files or what the project's structure should be, check the end of the article; there is an image with the final project.
Pre-requisites:
- Terminal knowledge.
- Knowing how to use a code editor.
- Basic npm/npx/yarn knowledge.
Create Next.js application
The first step is to create a simple Next.js application. We can do that by running the command below:
npx create-next-app nextjs-typescript-tailwind
The command
create-next-app is maintained by Next.js creators, and it builds an application within seconds — the folder named
nextjs-typescript-tailwind stores your newly created application.
Now you can go into the application folder and run it. You can do so by following the commands below:
cd nextjs-typescript yarn dev
The
cd command takes you into the specified folder, and
yarn dev runs the application. You can go to
localhost:3000 and see your new app. That is all you have to do to create a simple Next.js app.
Add TypeScript
The next step is to add TypeScript to our application. The first step you have to do is create the file
tsconfig.json in the root directory. You can create the file by running the following command in the terminal:
touch tsconfig.json
The
touch command allows you to create empty files in the Unix-based systems, such as Linux and macOS - read more about the touch command. Since our
tsconfig file is empty, if you try to run the app, you get the following error:
It looks like you're trying to use TypeScript but do not have the required package(s) installed.
Please install typescript, @types/react, and @types/node by running:
yarn add --dev typescript @types/react @types/node
Since we are using npm in this tutorial, use the following command to install TypeScript in the project:
npm install --save-dev typescript @types/react @types/node
However, what does the above command do? It creates a file called
next-env.d.ts, and it populates
tsconfig.json. The purpose of
tsconfig.json is to indicate that the directory present is the root of a TypeScript project. Also, it specifies the compiler information that is required to compile the project. Additionally, the
next-env.d.ts file tells the TypeScript compiler to pick up the Next.js types.
Next.js types - that brings us to the next question; what are Next.js types? There are the
GetStaticProps,
GetStaticPaths, and
GetServerSideProps types, which you can use for the methods
getStaticProps,
getStaticPaths, and
getServerSideProps. For more types and information, check the Next.js documentation.
You are almost done now. The only step left is to change the
.js extensions to
.tsx. The
.tsx extension is the extension of TypeScript JSX. After changing the extensions, your files should look like in figure 1:
Now your Next.js app fully supports TypeScript. From now on, you can write TypeScript code!
Add TailwindCSS
The next and last step is to add TailwindCSS to the application. To add Tailwind, you need to run the command below, which installs it in the app:
npm install tailwindcss postcss-preset-env --save-dev
However, looking at the above line, you can see that we are not installing only Tailwind. We also have
postcss-present-env. So what is that? According to their website, PostCSS "lets you convert modern CSS into something most browsers can understand, determining the polyfills you need based on your targeted browsers or runtime environments".
But why do we need it for Tailwind? The reason is that TailwindCSS is a PostCSS plugin. As a result, we need a tool to translate the modern CSS into something the browsers can understand.
Let's move further, and generate the
tailwind.config.js file. The purpose of this file is to allow you to customize your TailwindCSS installation. It is a configuration file where you can add additional information such as plugins, themes, margins, padding, and everything you require and Tailwind does not have.
npx tailwindcss init
By running the above command, it automatically creates the
tailwind.config.js file. If you want to add customizations, I recommend checking the TailwindCSS Configuration page.
The next step is to create a CSS file, where we can add the TailwindCSS data. Create a new file in the styles directory as follows:
touch styles/styles.css
You can add the CSS file wherever you want, and makes sense for your project. Also, you can name the CSS file "Tailwind.css" or however you want.
However, moving further, add the following lines to the
styles.css file.
@tailwind base; @tailwind components; @tailwind utilities;
What these lines do is to hold all the CSS you can use in your app. At build time, it swaps these with the generated CSS. For instance,
@tailwind base is the equivalent of
Normalize.css.
PostCSS
We are almost done adding TailwindCSS to our project too. What is left is to set up the
postcss.config.js file, which stores the configuration for PostCSS. As usual, we can create the file as follows:
touch postcss.config.js
After you create the configuration file for PostCSS, add the following code the it:
module.exports = { plugins: ["tailwindcss", "postcss-preset-env"], };
The last thing you have to do is add
import '../styles/styles.css' at the beginning of the
_app.tsx file. After doing so, you can use TailwindCSS everywhere in your application.
Conclusion
Well done! You added TypeScript and TailwindCSS to your Next.js application. At this point, your project should look similar to the one in figure 2 below.
You can find the project on my Github - click me.
daily.dev delivers the best programming news every new tab. We will rank hundreds of qualified sources for you so that you can hack the future.
Discussion (0) | https://practicaldev-herokuapp-com.global.ssl.fastly.net/dailydotdev/a-comprehensive-guide-on-setting-up-next-js-with-typescript-and-tailwindcss-160m | CC-MAIN-2021-10 | refinedweb | 1,044 | 67.25 |
I have a CSV file that has errors. The most common one is a too early linebreak.
But now I don’t know how to remove it ideally. If I read the line by line
with open("test.csv", "r") as reader: test = reader.read().splitlines()
the wrong structure is already in my variable. Is this still the right approach and do I use a for loop over test and create a copy or can I manipulate directly in the test variable while iterating over it?
I can identify the corrupt lines by the semikolon, some rows end with a ; others start with it. So maybe counting would be an alternative way to solve it?
EDIT: I replaced reader.read().splitlines() with reader.readlines() so I could handle the rows which end with a ;
for line in lines: if("Foobar" in line): line = line.replace("Foobar", "") if(";n" in line): line = line.replace(";n", ";")
The only thing that remains are rows that beginn with a ; Since I need to go back one entry in the list
Example:
Col_a;Col_b;Col_c;Col_d 2021;Foobar;Bla ;Blub
Blub belongs in the row above.
Answer
Here’s a simple Python script to merge lines until you have the desired number of fields.
import sys sep = ';' fields = 4 collected = [] for line in sys.stdin: new = line.rstrip('n').split(sep) if collected: collected[-1] += new[0] collected.extend(new[1:]) else: collected = new if len(collected) < fields: continue print(';'.join(collected)) collected = []
This simply reads from standard input and prints to standard output. If the last line is incomplete, it will be lost. The separator and the number of fields can be edited into the variables at the top; exposing these as command-line parameters left as an exercise.
If you wanted to keep the newlines, it would not be too hard to only strip a newline from the last fields, and use
csv.writer to write the fields back out as properly quoted CSV. | https://www.tutorialguruji.com/python/remove-linebreak-in-csv/ | CC-MAIN-2021-39 | refinedweb | 331 | 75.91 |
diskmap—
#include <sys/dkio.h>
diskmapdriver provides userland applications with a means to map a disklabel UID to an actual device and open that device in one atomic operation. This is achieved via the DIOCMAP ioctl(2) command. The ability to use a disklabel UID is helpful in situations where a disk may appear to the operating system under different device names. For example, plugging USB keys into differently configured systems (think sd0 or sd1), or swapping between IDE and AHCI on a disk controller (wd0 or sd0). Although the device names may change, the operating system is still able to identify the disk by its UID.
diskmapdriver first appeared in OpenBSD 4.8.
diskmapdriver was written by Joel Sing. | https://man.openbsd.org/diskmap.4 | CC-MAIN-2018-34 | refinedweb | 120 | 56.76 |
when you call setPixel32 of bitmapdata
setPixel32(x,y,argb);
the real data stored is a a/255*r a/255*g a/255*b
so you can set rgb data by this setPixel32(x,y,0xff_r_g_b),
and setPixel(x,y,rgb)==setPixel32(x,y,0xff_r_g_b)
but if i want this setPixel32(x,y,0x000f0f0f) , and use it as a texture ;
the shader will get the value 0 not 0x000f0f0f
Is there a way to store any uint value into BitmapData?
Can you post the ActionScript code that you're using to set up the image as well as the Pixelbender code that you're trying to use to read it. The alpha channel should be passed through correctly, although you need to take into account that the uint values in Flash will be converted to float values in PixelBender.
Bob
=========for bitmapdata it self================
The alpha channel can used to store no zero value. setPixel32 then getPixel32 will match
If the alpha channel is 0 , it will set all the rgb balue to 0. getPixel32()==0
=========when it upload to gpu over stage3d=========================
it will send the value after mutiply
bd.setPixel32(0, 0, 0xARGB);
the real value fetch by shader is this: A A/255*R A/255*G A/255*B
for example : i want a value argb value such as (0.5,1,1,1) in the shader
then i do this bd.setPixel32(0, 0, 0x7fffffff);
the real value fetch by shader is this: (0.5 0.5 0.5 0.5)
========================================================
There are there kinds value
val1=the parameter of setPixel32
val2=the return value of getPixel32
val3=the texture value read by shader
if(alpha!=0) val1==val2
if(alpha==0) val1!=val2 and val2==0
val3=(val1.a , val1.a/255*val1.r, val1.a/255*val1.r, val1.a/255*val1.r)/255
Am i clear?
=============================================================
package
{
import flash.display.BitmapData;
import flash.display.Sprite;
public class BitmapDataTest extends Sprite
{
public function BitmapDataTest()
{
var bd:BitmapData = new BitmapData(128, 128);
bd.setPixel32(0, 0, 0xffffffff);
var storeValue:uint = bd.getPixel32(0, 0);
trace(storeValue);//ok and also ok for shader
bd.setPixel32(0, 0, 0x1ffffff);
storeValue = bd.getPixel32(0, 0);
trace(storeValue);//ok for bitmapdata but not ok for shader
bd.setPixel32(0, 0, 0x0ffffff);
storeValue = bd.getPixel32(0, 0);
trace(storeValue);// not 0xffffff but 0
}
}
}
I think I understand what's happening, and I don't think there's a way of fixing it. As you've noticed, the alpha value affects the rgb values so it's not possible to set four entirely independent values and have them passed through. That's a legacy of Pixel Bender's roots in image processing. I'm sorry, but Ithink you're going to have to find a different way of encoding the data to pass to PB.
Bob | http://forums.adobe.com/message/4002931 | CC-MAIN-2014-10 | refinedweb | 477 | 64.71 |
Agree totally
-----Original Message-----
From: Tink [mailto:flex@tink.ws]
Sent: 31 July 2012 14:49
To: flex-dev@incubator.apache.org
Subject: Re: What namespace should new components go in?
We surely don't need a new namespace for new components that are spark based. That would
mean that each time we release with some additional components we would end up adding a new
namespace (i.e we'd have got a new namespace for a spark DataGrid) Namespaces are not them
go show the date a component was introduced, but to group a codebase by the strategy it was
developed under. | http://mail-archives.apache.org/mod_mbox/incubator-flex-dev/201207.mbox/%3C00d101cd6f57$e1221ec0$a3665c40$@tinylion.co.uk%3E | CC-MAIN-2014-23 | refinedweb | 103 | 72.87 |
If?:
cast
.
import static com.example.mypackage.Util.cast
The magic here is that the compiler can use
type inference to figure out what T should be in the method call. In the example, since we're assigning the result of cast to a List<String>, the compiler can infer that T must be List<String>.
T.
<E>cast(x).)
I'm not sure it's a great idea to have such a general carpet sweeping method. Keeping duplicated cast methods as close to its usage as possible would be a good start.
There are some cases where unchecked casts are inevitable, but you can make the cast method smarter. For instance reading a generic object through serialisation (without defaultReadObject) will always be a problem. However you can move the readObject (or readUnshared) call into the case method.
@SuppressWarnings("unchecked")
static <T> T readObject(
java.io.ObjectInputStream in
) throws java.io.IOException, java.lang.ClassNotFoundException {
return (T)in.readObject();
}
There's a usenet thread here.
Posted by: tackline on March 30, 2007 at 03:56 AM
Tom, agreed that caution and restraint are appropriate (as I mentioned in my last paragraph). Also it is a good idea as you suggest to move the inference magic to a higher level to group several similar calls to cast.
I'm not sure I see what is to be gained by "keeping duplicated cast methods as close to its usage as possible"; I interpret this as meaning having a private cast method in every class that needs one. The disadvantages I see are: you have to delete the cast method explicitly when it is no longer used in its class (maybe your IDE can help, but still); you can't use your IDEs "find usages" method to find everywhere in your code that you are using this unsafe trick; and if you need to pass a type parameter then you have to write MyRandomClassName.<T>cast(x).
Posted by: emcmanus on March 30, 2007 at 04:06 AM
For your singleton example it's not necessary to create own utility method, functionality of Class class is enough:
<E> Set<E> result(Object x, Class<E> clazz) {
E e = clazz.cast(x);
return Collections.singleton(e);
}
...
Set<String> keys = result(myKey, String.class);
VS
Posted by: vsilaev on March 30, 2007 at 05:39 AM
Valery,
Passing an explicit Class parameter is certainly one good way of restructuring the code to eliminate warnings. But it does require callers to change. I don't think the particular example I gave is very good (how can we be sure that x really is of type E? if we know it is, couldn't we declare it as an E?).
As a data point, the JMX sources in JDK 7 contain 29 uses of Util.cast. That's quite a lot, but at least partly reflects the dynamically-typed nature of the JMX API. Of the 29, 8 have an explicit type parameter. In three cases, that parameter is a type variable, and in the other five it is Class<Object> or Class<T>.
The example of
com.sun.jmx.remote.util.CacheMap is perhaps more realistic. Here's the get(Object) method, specified by Map<K, V>:
public V get(Object key) {
cache(Util.<K>cast(key));
return super.get(key);
}
We're relying on the caller of this internal class not to pass us anything other than a K, though in fact the use of K and V throughout is just for readability. We don't want to have to specify the real class of K via a Class parameter on the constructor, and we don't want to use Object everywhere either. Hence Util.cast.
Posted by: emcmanus on March 30, 2007 at 06:40 AM
In the serialisation case, it's trivial to put the generic reference inside a non-generic class, and serialise and deserialise that. Then there's no casting issue.
Posted by: ricky_clarkson on March 30, 2007 at 07:42 AM
The @SuppressWarnings annotation also applies to local variables. (It's one of the Target values for the annotation.) So you can simply do
@SuppressWarnings("unchecked")
List list = (List) x;
within your method. This makes it perfectly clear what cast it applies to.
Disclaimer: I haven't tested this with javac, but it works fine in Eclipse.
Posted by: basdebakker on March 30, 2007 at 08:14 AM
Sorry, I forgot to quote the HTML characters, that should have been
@SuppressWarnings("unchecked")
List<String> list = (List<String>) x;
Posted by: basdebakker on March 30, 2007 at 08:17 AM
Bas,
Well, blow me down! I didn't know you could do that. It does make the cast method logically unnecessary, though still considerably more concise.
Your suggestion does work with javac, by the way.
Posted by: emcmanus on March 30, 2007 at 08:49 AM
Thanks for that: straight in my GenUtils toolbox!
Rgds
Damon
Posted by: damonhd on March 30, 2007 at 09:40 AM
Peronally, I think its pretty clear that unchecked warnings in Java can't keep things straight. They should disable them by default (not even ask you to run with -Xlint:unchecked). I'm not kidding. They can keep errors for "List<String> blah = getListOfIntegers();", but I just turn off the unchecked warnings in Eclipse. I don't find them helpful at all.
Posted by: tompalmer on March 30, 2007 at 09:48 AM
ricky_clarkson: Do you mean using a reference of the erased type? Say copying a List<String> to a List? You still end up having to get back from List to List<String>, which should give you an unchecked.
Eamonn: I think it's more obvious (and easier to find in the general case) to see @SuppressWarnings than happen to notice the significance of 'cast'. Heed your compiler's warnings, and if you don't, make it obvious that you are not. At least use an ugly name - REIFICATION_CAST or something. If I was scanning through the code, I wouldn't notice the problem. I would have to be looking at it quite intently to see.
So I had a search for cast() in com.sun.jmx, JDK7 b07 (really don't like the static import, btw).
Introspector - two uses of <Class<Object>>cast(). There can only be one Class<Object>. You could use Object.class. Or perhaps the compiler was right to warn.
CacheMap - bad cast. There is no reason to assume that key is of type K.
Service - I believe this should read service.cast(...) (i.e. use Class.cast).
SnmpOidDatabaseSupport - okay(ish). This is 'necessary' because the interface used is not generified. Actually, it returns Vector<?> (generally a bad practice) so it isn't actually necessary.
Posted by: tackline on March 30, 2007 at 12:48 PM
Tom,
Thanks for the free code review! :-)
I agree that the Introspector lie is ugly. The problem is that at this point we have determined that c is a Class representing an interface that the object mbean implements. So it meets the constraint expressed by the StandardMBeanSupport constructor:
public <T> StandardMBeanSupport(T resource, Class<T> mbeanInterface)
However there's no clean way to convince the compiler of that fact. But Util.<Class>cast() would be less unclean than Util.<Class<Object>>cast().
Concerning CacheMap, I judged that the readability advantage of being able to use K in the definition of the LinkedList<SoftReference<K>> field outweighed the potential for incorrect usage of this non-public class, especially since such usage would not in fact break anything. Alas, non-reified generics imply a lot of compromises of this sort.
Concerning Service, you are right; it is always better to use Class.cast if there is an appropriate Class to hand. In fact I noticed this when looking for an example of a cast to a type variable in my reply to Valery.
Concerning SnmpOidDatabaseSupport, these ancient SNMP packages were by far my biggest headache when de-linting the JMX sources. I had to use Vector<?> because the inheritance hierarchy includes methods that return Vector<SnmpOidRecord> that are overridden by methods that return Vector<SnmpOidTable>. Ugh. This is legacy code that we're not motivated to modify more than is strictly necessary for fear of breaking it, so a bigger rewrite was not on the cards.
Posted by: emcmanus on April 02, 2007 at 02:43 AM
Hmmm, following up to myself here about the Introspector code.
In fact using <Class> instead of Class<Object> does not work - I was fooled by a stray @SuppressWarnings on the method in question. However, I did find another solution which is better than Class<Object>. In outline it is:
public static <T> DynamicMBean makeDynamicMBean(T mbean)
throws NotCompliantMBeanException {
final Class<?> mbeanClass = mbean.getClass();
Class<? super T> c = Util.cast(getStandardMBeanInterface(mbeanClass));
if (c != null)
return new StandardMBeanSupport(mbean, c);
...
We are no longer lying to the compiler - getStandardMBeanInterface really does return a Class that is "super T".
Adding a type parameter to the method just so we can make things work inside it is a bit bizarre, and if this method were part of the public API I would forward to a private method with the type parameter.
Posted by: emcmanus on April 03, 2007 at 02:04 AM
Tackline (Tom Hawtin),
No, I mean an instance of a generic type referred to by an instance of a non-generic type. E.g.:
class StuffImGoingToSerialise implements Serializable
{
List<String> stringList;
}
You can serialise and deserialise instances of that without the warnings.
Posted by: ricky_clarkson on April 04, 2007 at 10:13 AM
I explained all kind of casting operations on my blog.. If you want to know anything else feel free to contact me by mail.
Posted by: angelas on May 25, 2007 at 01:45 PM
Your picture is quite lovely...I like it...
Posted by: bookworm02 on September 18, 2007 at 01:46 AM | http://weblogs.java.net/blog/emcmanus/archive/2007/03/getting_rid_of.html | crawl-002 | refinedweb | 1,659 | 64.51 |
Asked by:
Can Wave{In|Out} be run in exclusive mode? & is it safe to play with WASAPI buffers without eventcallback
Hi, i'm new to the core audio (SPECS: 64b intel, 32b vista OS with integrated realtek, 2Gram; Via IsApiSupported, realtek seems to run only 16bit-depth, though the Hz can go up to 192kHz and also in my control panel settings it goes up to 24bit).
I have 4 questions , 2 pertaining to exclusive mode (as i require lowlatency with audio hardware to feed back and forth with a neuralnet)
[1] Rather than using WASAPI, can the waveIn/Out functions be set in exclusive mode, or are they already? It was a hassle to go through the WASAPI to get things setup, though i haven't actually tried getting the buffer itself.
[2] Using WASAPI with everything setup properly, is it safe to just memcpy (to/from) the buffers grabbed from GetBuffer for both IAudioCaptureClient &IAudioRenderClient without using one of the flags for "Initialize"? The exclusive mode example uses EVENTCALLBACK and i'm not sure whether my application requires it?
My application is devised for this post into 3 threads: (a) AudioIn, (b) audioOut, and (c) the main thread for passing a buffer between the two.
AudioIn captures to buffer, that is manipulated by the main thread. And AudioOut renders from buffer used in main thread.
[3] Is the data from GetBuffer in PCM format just amplitude values of the waveform that i can feed into a FFT/iFFT if needed before feeding into NNET.
[4] I tried getting the wavformat from the properties methods in the examples (i setup the wavfmt manually as per someone previous post) using PKEY_AudioEngine_DeviceFormat but i get a duplicate _PKEY_ definitions error and am not sure what #define/undef I need to set so that initguid.h gets defined only once. I have the std WASAPI headers included in an .h file, and from someone's previous post it says u have to ensure that linking happens in only one .cpp.
Thanks in advanced.
Jack
Question
All replies
(2) You can access the capture buffer only between calls to IAudioCaptureClient::GetBuffer and IAudioCaptureClient::ReleaseBuffer, and the render buffer only between calls to IAudioRenderClient::GetBuffer and IAudioRenderClient::ReleaseBuffer. You should not access either buffer outside of these calls.
What are you using to control your loop? You can wait on an event that you passed to IAudioClient::SetEventHandle (event callback mode) or you can create your own waitable timer (or even use Sleep().)
Matthew van Eerde
(4) I usually create an initguid.cpp file which looks like this:
#include <initguid.h>
#include <windows.h>
#include <header-that-includes-guids-1.h>
#include <header-that-includes-guids-2.h>
...
#include <header-that-includes-guids-n.h>
I then make sure NOT to include initguid.h in any other .cpp file in the project.
Matthew van Eerde
thank you for the replies
for (1) is there away to get PCM format in exclusive mode for the waveXXX functions? I just need basic mic capture/speaker render functionality.
for (2) both capture/render threads will be in a "while(fOn) { }" loop till some error, device disconnection or the main thread sets the boolean fOn=false. The mic thread should be capturing CONSTANTLY while the speaker thread depends on when the neuralnet wants to make a sound.
for (4) I think I read in the docs that "initguid.h" must precede "mmdeviceapi.h", is this correct? I use a class defn with the following (that requires the latter header)
#include "mmdeviceapi.h"
#include <audioclient.h>
#include <audiopolicy.h>
class CAudioHdwrDev {
...
IMMDeviceCollection *devSet;
IMMDevice *dev;
IAudioClient *client; //adaptor?
WAVEFORMATEXTENSIBLE wavFmt;
EDataFlow type;
... //utilized ERole some where.
}
Does that mean that "mmdeviceapi.h" cannot be included in a header if i require "initguid.h"?
(1) is there away to get PCM format in exclusive mode for the waveXXX functions
No, but shared mode should work. Why do you need exclusive mode?
(2) the mic thread should be capturing CONSTANTLY
Sure, but once you're done processing a packet, how do you wait for the next one? There are a couple of WASAPI samples in the Windows SDK:
There are, in general, two answers: (a) pass an event to the IAudioClient and have it wake me up when it's time to process the next packet, or (b) use Sleep() or my own waitable timer
(4) DEFINE_GUID(X) either translates into "guid X exists and is defined in some other .obj file" or "guid X is {...}", based on whether INITGUID is defined. If all DEFINE_GUID(X)s are of the first form for a particular X, you'll get a compile error to the effect of "I can't find a definition for GUID X.". If you have two DEFINE_GUID(X)s of the second form for a particular X, you'll get a different compile error to the effect of "foo.obj defines X but it's already defined in bar.obj."
There are various ways to make sure that every X is defined in exactly one place. One way is to put all your code in one .cpp file (I can't recommend this.) Another way is the way I suggested - to make an initguid.cpp file which exists for the sole purpose of getting all the GUID definitions out of the way.
Matthew van Eerde
thx again
for (1): i wasn't sure whether there were latency issues with using waveXXX/PCM format/shared mode ... sorry i may have been miscomprehending the msdn docs
for (4): ah i see it now...u ensure initguid.cpp gets built before other mmdevice-dependent files . That was the part i couldn't wrap my brain around within the MSVC IDE. Thx for this suggestion...it was really bugging me.
for (2): with my OpenAL code(i'm working on openal/winaudio concurrently), i have the following
if (nDataCap>nGrabSamp)
{ alcCaptureSamples(devIn,buf,nGrabSamp); ...//other stuff
}
so i thought i would do the same with winaudio, but i'm running to issues in openal with race conditions...
so i'll take a look at the event method. Is there an msdn doc comparing the advantages of (a) event-driven vs (b) timer-driven. Is there a preference for low latency with the mic? or is that app-dependent?
regards, Jack
It is possible to get lower latency with exclusive mode than with shared mode. But you can't get exclusive-mode PCM through the winMM APIs (waveIn, waveOut), only exclusive-mode compressed audio.
Going through exclusive mode means no other apps will be able to play sound via that device. It also means your app will be limited to a single stream, so you'll need to do your own mixing if you want to play multiple sounds (and this mixing will add latency.) This is less of an issue for capture than for render.
If you still want to use exclusive mode you can use WASAPI directly.
Event-driven mode is perhaps slighly better than timer-driven mode from a latency perspective because you get notified at just the right time.
In addition to the SDK samples, there's an exclusive-mode playback app on my blog:
Capture would look similar.
Matthew van Ee
- Edited by Maurits [MSFT]Microsoft employee, Moderator Monday, April 04, 2011 6:55 PM fixed typo
that was very informative, thank you.
I should have mentioned it in the first post, that the application will be the only active app (a robotic app): In{Mic,Cam}/Out{Spkr} <--> Neuralnet , each with its own thread
... a side question: when an app is using exclusive mode, should I be closing other audio apps first (Winamp just crashed for me.)? or should (a) Window be reviving the other apps automatically after the exclusive app has terminated (b) is it up to the other software to handle another app using exclusive mode; or (c) my app should be signalling to other audio apps that it is using exclusive mode?
It's fine for your app to use exclusive mode.
If WinAmp is streaming, and then your app takes over the device, then WinAmp's calls to the audio APIs will start failing with "device in use" errors. WinAmp is expected to handle this gracefully and not crash; it sounds like they have a bug.
Generally well-behaved apps will respond to something like this by popping up a "there was an error" dialog; they will usually not attempt to resume playback "later".
Matthew van Eerde
This might be a very basic question.
What is the difference between #frames retrieved from
(a)IAudioClient::GetBufferSize(&nFrame) and
(b)IAudioCaptureClient::GetBuffer(&buf,&nFrame,...)
The docs say (a) is the maximum #frames the device can capture.
But i'm getting a value from (b) [#=576] double the size of (a) [#=288] ,
is this because its double buffering? Shouldn't (b) still only return max value?
- wavFmt is default PCM for my realtek onboard (24/32, 96000 , 2chhres=client->GetDevicePeriod (NULL,& dura);hres = client->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE,0 ,dura ,dura ,(WAVEFORMATEX*)wavFmt ,NULL);hres = client->GetService(__uuidof(IAudioCaptureClient), (void**)&clientCapture);UINT32 bufLn=0; hres=client->GetBufferSize(&bufLn); WIN_EXITERR(hres ,"Thread:Capture - bufln")hres = client->Start(); WIN_EXITERR(hres ,"Thread:Capture -client start")i fixed it though, imoved the buffersize call too after the start.Its weird though that before start its set to a different value
I ran some tests and I'm seeing it the other way around: GetBufferSize() is 896 frames but the most frames I ever actually get handed in a GetBuffer() call is 448.
You're doing timer-driven capture; the control flow for that should look something like:
for (...) {
while (pAudioCaptureClient->GetNextPacketSize() > 0) {
pAudioCaptureClient->GetBuffer();
// process the buffer
pAudioCaptureClient->ReleaseBuffer();
// note the lack of any sleep or wait here
}
Sleep or wait on a periodic waitable timer
}
Matthew van Eerde
i tried event driven but i kept getting some error....i need to look at this more deeply. But i had this as my init code
hres=client->GetDevicePeriod (NULL,& dura);
hres = client->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE
,AUDCLNT_STREAMFLAGS_EVENTCALLBACK ,dura ,dura ,(WAVEFORMATEX*)wavFmt ,NULL);
WIN_EXITERR(hres,"Thread:Capture - client init")
hres = client->SetEventHandle(hEvtAudioCap);
Though the erro might have been caused by this packet size error i posted previously.
Does the GetNextPacketSize work in exclusive mode? the docs say it doesn't.
I'm currently using this instead of nextpacket
hres=clientCapture->GetBuffer(&dataBuf,&nframeIn,&flags,NULL,NULL);
if(nframeIn>0) memcpy(audioDataIn, dataBuf, nframeIn*frameSz);
when i have the iaudioclient::initialize in EventCallback mode...., the GetBufferSize(&n) is n=288 [where i get the error i posted above]. But when i set the mode to 0 (timermode?) GetBufferSize(&n) is n= 512. Should this happen?
Also in several of the examples and in your blog on aligning this value pops up
10000.0 * // (hns / ms);
Is this an arbitrary value?...and does the hns abbrev refer to 100ns(nano) as per the doc on GetDevicePeriod?
And i think the last 2 questions I'll have for a while (I finally have thigns working for timer-driven and event-driven, the latter i had to set both threads to event-driven).
(1) When your WAVEFORMATEXTENSIBLE has non-equal precision bitd pairing 24/32 ... is the 24bit precsion the first 24b or the last 24b of the 32bit depth.
(2) after awhile of running flawlessly, the app flatlines to a constant buzz. Since i played with the Process/Thread Priority, would this account for the buzz. It usually happens when I doing some other UI task in another app.
Thanks again for all the help in understnading winAudio. Very much appreciated it.
regards, Jack
hns stands for "hundred nanoseconds." 1 hns is 1/10 of a microsecond, or 1/10,000 of a millisecond.
The 24 "valid bits" are the most significant bits of the 32. You could treat it as a 32 bit (signed) int and ignore the bottom eight bits, or divide it by 256 to see only the valid bits.
Re process and thread priority: registering with the Multimedia Class Scheduler Service (MMCSS) will ensure that your thread receives "bursts" of very high priority with intervals of low priority in between.
Matthew van Eerde
back again =[
The capturing works fine sometimes in "exclusive+event mode" ...then it ends up with AUDCLNT_E_BUFFER_OPERATION_PENDING and either the discontinuity flag or timestamp. Is there any way to restart teh device so that it captures again?
I tried "client->stop(); client->reset(); client->start();" to no avail.
===================
For the initialize i have set (should the buffersize/periodicity be greater than the DevicePeriod?)
client->GetDevicePeriod (NULL,&duraHNS);
hres = client->Initialize(AUDCLNT_SHAREMODE_EXCLUSIVE,AUDCLNT_STREAMFLAGS_EVENTCALLBACK ,duraHNS, duraHNS ,(WAVEFORMATEX*)&wavFmt ,NULL);
WIN_EXITERR(hres,"ClientInit - client init")
hres = client->SetEventHandle(hEvt);
WIN_EXITERR(hres,"ClientInit - set eventhandle")
===================
Then in the loop i have
client->Start();
while(On)
{ WaitForSingleObject(hEvt,INFINITE);
hres=cap->GetBuffer(&dataBuf,&nframeIn,&flags,NULL,NULL);
if(hres==S_OK&&dataBuf&&0<nframeIn)
{ devMgr->nframeSoundIn=nframeIn;
memcpy(devMgr->soundBufIn, dataBuf , nframeIn*frameSz);
hres=cap->ReleaseBuffer(nframeIn);
}
... some handlers for the various errors
}
- Hmmm... Are you getting failing HRESULTs, NULL buffers, or buffers of size 0 back from GetBuffer()? That is, if you change your error handling from "wait and call buffer again" to "report failure and exit", what failure do you see?
Matthew van Eerde
the 2errors i seem to be getting repeatedly are
[1] hresult=0x8890001(EMPTY BUFFER) with either valid or null ptr and flag=4 (TIMESTAMP error)
[2] hresult=0(or S_OK) with a NULL buffer with and flag = 4 (TIMESTAMP error)
#1 occurs quite frequently and usually at the first call to getbuffer, and i use a "continue" on this error to get the device capturing for some duration of time. This sometimes doesn't occur when i'm talking as the app is launched.
#2 usually occurs after #1 which seems logical...but it has also occured by itself.
----------------------------
it also returns back for #frames the full double buffer size of the multiple of the deviceperiod i set for buffer/periodicity in the INITIALIZE function.
ie. my realtek devperiod is 3ms (which corresponds to 288 frames), and i've been trying different factors of it (2x,4x,10x) so for the 4x its returns 2304 = (288*4*2) frames.
The larger the factor(currently at 20x) of devperiod I use for the INIT: buffer/periodicity, the longer before the secoond error appears.
--------------------------
So i guess the first thing i need to solve is how to not to get the
AUDCLNT_S_BUFFER_EMPTY off the start.
Oh yah i'm using SDK6.1 on vista
Event-driven capture is not supported prior to Windows 7.
> The initial release of Windows Vista supports event-driven buffering (that is, the use of the AUDCLNT_STREAMFLAGS_EVENTCALLBACK flag) for rendering streams only.
Matthew van Eerde
In the paragraph following the one u cited:
"In the Windows Vista Service Pack 1 release, this flag is functional in shared-mode and exclusive mode; an application can set this flag to enable event-buffering for capture streams. For more information about capturing an audio stream, see Capturing a Stream."
i have sp2 for vista....though i'll try to use shared-mode....should the loop be teh same AND just the initialization code is different?
Its nice though that it works for a couple of seconds and doesn't have the noise that timer-driven has. | https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/f4ec50d0-01cc-4217-8647-a2d7ec693c6d/can-waveinout-be-run-in-exclusive-mode-is-it-safe-to-play-with-wasapi-buffers-without?forum=windowspro-audiodevelopment | CC-MAIN-2015-48 | refinedweb | 2,566 | 63.8 |
Richard Jones' Log: withgui finally made public!
Thu, 21 Jan 2010
On the heels of the release of the cool withhacks library, I've finally (thanks Robert Collins for helping) released withgui on Launchpad. withgui is my experiment in simple GUI creation as mentioned previously (see also.)
I'll be looking at incorporating withhacks to replace my less-elegant (and fragile) namespace hackery. Feel free to take the code, branch and run. Contact me if you're interested in contributing (no comments on this blog but you'll figure out how to.)
Thanks also to Brianna Laugher who tried to help me release to Launchpad a couple of months ago - the failure then was in my available time. | http://www.mechanicalcat.net/richard/log/Python/withgui_finally_made_public | CC-MAIN-2017-39 | refinedweb | 118 | 63.59 |
This tutorial explains how to paste an image in Pillow
The
paste() function in the Python Pillow Library allows us to paste one image over the other. You can use it as a way to combine two images together into one.
Pasting an Image in Pillow
We’ll be aiming to paste the crown on top of the Kitten’s head. There will be a total of 3 sections, where we work on pasting it as well as we can.
We’ll be using the two above images in this tutorial today.
Simple Paste
Let’s first try a simple image paste, without any extra parameters or options. If pillow detects different color modes, it will automatically convert the image being pasted to the mode of the image being pasted upon. (It’s basically an automatic use of the
convert() function)
from PIL import Image img1 = Image.open("kitten.jpg") img2 = Image.open("crown.png") img1.paste(img2) img1.show()
It’s important to note that
img1 has been directly modified. If you wish to preserve the original image, you should make a copy using the
copy() function.
Output:
As we didn’t specify a coordinate, the image will automatically be pasted at the top-left corner, or the ( 0, 0 ) coordinate.
Pasting at specific Co-ordinates
In this section we’ll explain how to paste an image at a specific location.
from PIL import Image, ImageFilter img1 = Image.open("kitten.jpg") img2 = Image.open("crown.png") img1.paste(img2, (250, 20)) img1.show()
Passing an extra parameter with the coordinate tuple will begin drawing the image from that coordinate.
Output:
The above image has the crown on the right place, but it doesn’t look good due to the white background. This image is actually a transparent one, but Pillow is automatically converting into another format. We’ll discuss how to fix this in the next section.
Pasting Transparent Images in Pillow
Our crown image is being display with a white background due to Pillow’s default nature. We can get around this by using the concept of “masks”. A quick and easy way to implement it is shown below.
from PIL import Image, ImageFilter img1 = Image.open("kitten.jpg") img2 = Image.open("crown_trans.png") img2 = img2.convert("RGBA") # Including the "A" in RGB img1.paste(img2, (270, 10), img2) img1.show()
We just have to pass in the image with the transparent background into the third parameter, and Pillow will paste and display it correctly. We didn’t just convert it to RGB, just to be clear. The “A” has been included which represents the Alpha channel, which controls the transparency.
Output:
Note: This is not meant to remove backgrounds (though you could repurpose it to do so). The reason why the background disappeared in the above image is because that’s how our image originally looked. All we did was change Pillow’s default behavior when it’s dealing with images with transparent backgrounds.
Want to learn more about Pillow and Image Processing in Python? Check out our Pillow Tutorial Series!
This marks the end of the Pillow Image Paste Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below. | https://coderslegacy.com/python/pillow-image-paste/ | CC-MAIN-2022-40 | refinedweb | 547 | 58.48 |
#include <qgscrscache.h>
Definition at line 24 of file qgscrscache.h.
Definition at line 35 of file qgscrscache.cpp.
Definition at line 31 of file qgscrscache.cpp.
Referenced by instance().
Returns the CRS for authid, e.g.
'EPSG:4326' (or an invalid CRS in case of error)
Definition at line 40 of file qgscrscache.cpp.
References QgsCoordinateReferenceSystem::createFromOgcWmsCrs(), mCRS, and mInvalidCRS.
Referenced by crsByEpsgId().
Definition at line 58 of file qgscrscache.cpp.
References crsByAuthId().
Definition at line 22 of file qgscrscache.cpp.
References mInstance, and QgsCRSCache().
Referenced by QgsCoordinateReferenceSystem::readXML().
Definition at line 38 of file qgscrscache.h.
Referenced by crsByAuthId().
Definition at line 37 of file qgscrscache.h.
Referenced by instance(), and ~QgsCRSCache().
CRS that is not initialised (returned in case of error)
Definition at line 40 of file qgscrscache.h.
Referenced by crsByAuthId(). | http://qgis.org/api/1.8/classQgsCRSCache.html | CC-MAIN-2015-06 | refinedweb | 135 | 56.21 |
Hey, everyone! I've got small problem in this code! I cannot find a mistake in this code. I was playing many times by changing functions and values, but something wrong. I'm beginer in C++, but I would like to be professional. I never ask for codes, only help for explaining. Thank you!!!
Compiler shows error:(59)error C2181: illegal else without matching if //-???
(65) error C1075: end of file found before than left brace... //-???
//Specification: Count the letter is a Text file #include <iostream> #include <fstream> #include <string> using namespace std; const char FileName[] = "c:\\TestCount.txt"; int main() { string lineBuffer; ifstream inMyStream (FileName); //open my file stream if (inMyStream.is_open()){ //create an array to hold the letter counts int upperCaseCount[26] = {0}; int lowerCaseCount[26] = {0}; //read the text file while (!inMyStream.eof()){ //get a line of text getline (inMyStream, lineBuffer); / upperCaseCount[int(oneLetter)- 97]++; //make the index match the count array } }//end while inMyStream.close(); //close the file stream //display the counts for (int i = 0; i < 26; i++) cout << char(i + 65) << "\t\t" << upperCaseCount[i] << endl; for (int i = 0; i < 26; i++) cout << char(i + 97) << "\t\t" << lowerCaseCount[i] << endl; } else cout << "File Error: Open Failed"; return 0; } | https://www.daniweb.com/programming/software-development/threads/213144/error-of-letter-frequencies-in-a-text-file | CC-MAIN-2017-43 | refinedweb | 206 | 64.1 |
A Python client for the Imgur API
Project description
imgur-python
A Python client for the Imgur API.
The original imgurpython project is no longer supported, so, I decided to create my own python client for the Imgur API.
Disclaimer: This is a work in progress. In this first version, I'm not gonna implement all the API calls, only the necessary ones to interact with imgur and be able to create albums, upload images and share them on the site.
For more information, check the project wiki
Requirements
Links
Install
$ python setup.py install
with pip
$ pip install imgur-python
How to publish something and share it with the community?
- upload a bunch of images
- add them to an album
- share it
from os import path from imgur_python import Imgur imgur_client = Imgur({'client_id': 'cf8c57ca8......'}) image = imgur_client.image_upload(path.realpath('./image.png'), 'Untitled', 'My first image upload') image_id = image['response']['data']['id'] album = imgur_client.album_create([image_id], 'My first album', 'Something funny', 'public') album_id = album['response']['data']['id'] response = imgur_client.gallery_album(album_id, 'This is going down on the sub', 0, 'funny,midly_interesting') print(response)
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
imgur_python-0.2.2.tar.gz (20.0 kB view hashes) | https://pypi.org/project/imgur-python/0.2.2/ | CC-MAIN-2022-33 | refinedweb | 219 | 56.66 |
Hi,
Im new at python but Im looking for a way to retrieve a list of usernames in a text file and then insert them into my script wherever $User would be located.
I know in powershell it was
$Users = Get-Content -Path 'C:\temp\NewUser.txt'
foreach ($user in $users)
{ }
and this would apply to the entire script is there a way I can do this with python?
This is what I have for my current python script and it works correctly when trying to only do one username but I would like to be able to have a large list of usernames in a text file and then just play the python script and have it retrieve the usernames
#! /usr/bin/env python
import ldap
import ldap.modlist as modlist
import getpass
# ldap url for prod vault
uri = "ldap://myldap.aaa.aaa.com/"
l = ldap.initialize(uri)
print "Connecting to " + uri
# credentials for LDAP
user = raw_input("Enter your username: \n")
username = "cn=" + user + ",ou=Users,o=aaa"
password = getpass.getpass()
try:
# open the connection
l.bind(username, password)
print "Connection successful."
# the dn of our existing entry/object
uid = input("Enter the userid: \n")
dn = "cn=" + uid + ",ou=Users,o=aaa"
# placeholders for old and new values
old = {'loginDisabled': 'TRUE' }
new = {'loginDisabled': 'FALSE' }
# convert place-holders for modify operation using modlist module
ldif = modlist.modifyModlist(old,new)
# do the modification
l.modify(dn,ldif)
print "Enabling account: " + dn
print "Done."
# disconnect
l.unbind()
print "Connection closed."
except ldap.INVALID_CREDENTIALS:
print "Your username or password is incorrect."
except ldap.NO_SUCH_OBJECT:
print dn
print "Object does not exist."
except ldap.OPERATIONS_ERROR:
print "Transaction failed, invalid operation."
except ldap.OTHER:
print "Transaction failed, an uknown error occured."
Thank you for all your help I appreciate it sooooo much!!! | http://forums.devshed.com/python-programming-11/retrieve-txt-file-input-942550.html | CC-MAIN-2016-36 | refinedweb | 297 | 57.57 |
Java Garbage Collection
I was trying to find the best information on java garbage collection and why java does not support destructors. Almost read 100 of blogs and articles on java garbage collector and destructors method in java. I have found to the point answer but I was looking for the process and was looking for the exact method by which the JVM performs this task.
so today In this article I am going to share my knowledge to make understand others easily so that they can make sense on java garbage collection. This blog will help you to understand what is going in background when java garbage collection is being processed.
So before going to the process I think you might know some several things I am going to describe below. But if you are well known to these things then you might skip these.
One of the major difference between c++ and java :
Both are high level and object oriented programming language but the major difference is Java does not have destructor element as c++ have. Instead of destructor java uses Garbage collector to clear off unused memory automatically.
We may have a lot of unused objects. But we human are always in search of better memory management technique . To save up our memory we were using free() function in c language and delete() function in c++ .
The main advantage of Java is here, In Java this task is done automatically by the java which is known as Java Garbage Collector. So we can always say that Java provides us a better memory management as we don’t have to make extra effort on creating functions to delete unused or unreferenced objects .
so till now I know you guys are known to the fact what is the purpose of java garbage collector and why java does not have destructor (as java has its own java garbage collection so no need to have destructor as c and c++ have) .
But I am sorry to say that you need to know more in details otherwise you may have wrong conception on this topic. ( like we can use function to free memory in java too like c++ )
so I am going deeper to clear all the questions that might be appeared on your mind .
What is Destructor:
Objects are born with a life cycle. when an object’s life cycle is over , a special method is called in order to clear off the memory and de-allocate the resources. This method is known as destructor. It is also called manual memory management . destructor is used in order to avoid memory leaks.
The destructor is used by the programmer and there are several rules of using a destructor .
Rule 1. The class name and the destructor name must be same.
Rule 2. There must not be arguments.
Rule 3. The destructor must not have any return type.
So it is clear that we have to make extra effort here to clean up the memory .
Concept Of garbage collection/collector :
As you saw on the above few lines we should manually implement destructor and it is done by the programmer But in case of java there is a concept of garbage collection where JVM automatically performs the task of cleaning up the unused memory.
It is a program that actually runs on Java Virtual Machine. This program delete the objects that are not used anymore in the future or delete the objects that are not accessible from the code any more. (these types of objects are also sometime called unreferenced objects ) . This runs automatically on JVM and checks periodically if there is any object which is unreferenced in the memory heap. If any unreferenced object is found in the memory heap that signifies that the object is totally useless and will never be used in future , so the garbage collector gets rid of the object and frees up the memory which was allocated by the unreferenced object.
So there are two main basic principle of garbage collection.
#1. To find unreferenced objects that can not be used in the future anymore
#2. To clean up the memory and reclaim the resources used by the object .
You might now thinking that how java finds the unreferenced objects?
It is very interesting to know that actually java does not find unreferenced objects , java actually finds all the referenced objects in a program and the mark rest of the objects in that program as unreferenced objects. (cool way of finding unreferenced objects in a java program )
Those who are interested in Using Garbage Collection manually can use the below parameters to use different types of Garbage Collection.
1. The serial collector:
-XX:+UseSerialGC
2. Parallel Collector:
-XX:+UseParallelGC
There are more types we will discuss those in advance garbage collector in later.
How an object is become unreferenced ?
#1. Nulling a reference
Student e=new Student(); e=null;
#2. Assigning a reference object to another
Student r1=new Student(); Student r2=new Student(); r1=r2;//now the first object referred by r1 is available for garbage collection
We programmer can use finalize() method . This method is used to clean up memory in java.
This method is used in the below format
protected void finalize(){}
We can create an object using new keyword and we can create an object without the new keyword too. But in JVM garbage collector only collect those objects which are created by using new keyword so In case if you have created an object without using the new keyword than you have to use this finalize() method to use clean up process manually.
Now I think you have enough knowledge on garbage collection in java . So now we can take a look at simple java garbage collection example by coding .
public class MyGarbage{ public void finalize(){ System.out.println("Garbage collected successfully"); } public static void main(String args[]){ MyGarbage s1=new MyGarbage(); MyGarbage s2=new MyGarbage(); s1=null; s2=null; System.gc(); } }
the gc() method is also used to clean up the memory and it is used in system and runtime classes.
Output:
Garbage collected successfully Garbage collected successfully
Reading this blog I hope you are sure that there are lot of advantages of java garbage collector.
But there is an another side of this coin.
like everything this garbage collection too have some disadvantages.
#1. Java Garbage Collector runs on its own thread still it can make effect on performance.
#2. Since Java Garbage Collector has to keep constant tracking on the objects which are not referenced It adds overhead.
#3. Java Garbage Collector needs some amount of resource to identify which memory need to be freed and which not.
#4. Its almost impossible to predict how much time can be taken to collect garbage by the JVM.
Hope you enjoyed learning. | https://www.codespeedy.com/java-garbage-collection/ | CC-MAIN-2018-51 | refinedweb | 1,141 | 60.95 |
It's not the same without you
Join the community to find out what other Atlassian users are discussing, debating and creating.
Hi,
An issue is created and have a selected date in a custom field.
On a self-transition, I want to check if the date field is updated (if the the old selected date != to new selected date)
Thanks
Hi Robi,
According to documentation you can get the old and new values in a post function (and in your case should be a condition that returns true or false after the comparison)
def change = transientVars.changeItems.find {it.field == "Name of custom field"} if (change) { // you have the value, do something with them and return true or false def oldValue = change.oldstring def newValue = change.newstring }
Note: Tested in my instance (JIRAv7.1)and instead of oldstring and newstring for a Date picker custom field is change.fromString and change.toString
Kind regards
Hi Robi,
Do you get any errors in your logs ? Also the above requires a change, which means that you have a screen during the transition and you change the value of the custom field in that screen.. | https://community.atlassian.com/t5/Marketplace-Apps-questions/Check-if-field-is-updated/qaq-p/241772 | CC-MAIN-2019-04 | refinedweb | 193 | 71.65 |
Everything is possible.
It would have to be a new combined library though, and that is a lot ofwork.
I wonder if you could run Cayenne on an ESP as well, then pass it datathrough to the serial port. The ESP could be set to wake-up on pin change.Just use the same dashboard ID on both.
Cheers,
Craig
Not a coading guy that's why having trouble
Want to develop a deviceby reading a digital input value use esp or Ethernet ..
What about mqtt code you mentioned to try earlier
I have the Arduino code to use MQTT here however it's not a copy and paste. Try the code below and see if it works. I did not test it.
Change settings on the line "if (client.connect(clientID, username, password)) {" to match your MQTT info.
#include <PubSubClient.h>
#include <ESP8266WiFi.h>
const char* ssid = "SSID";
const char* password = "PASSWORD";
const char* mqtt_server = "mqtt.mydevices.com";
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;
void setup() {
int timeoutcounter = 0;
Serial.begin(9600);
WiFi.begin(ssid, password);
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
while (WiFi.status() != WL_CONNECTED) {
timeoutcounter++;
delay(500);
Serial.print(".");
if (timeoutcounter >= 30){
Serial.println("Failed to connect to wireless - sleeping for 5 minutes");
delay(100);
ESP.deepSleep(300000000, WAKE_RF_DEFAULT);
delay(100);
}
}
Serial.println("");
Serial.println("WiFi connected");
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(clientID, username, password)) {
Serial.println("connected");
client.subscribe("CayenneInput");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Sleep for 5 minutes before retrying
Serial.println("Failed to connect to MQTT server - sleeping for 5 minutes");
delay(100);
ESP.deepSleep(300000000, WAKE_RF_DEFAULT);
delay(100);
}
}
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
float t = 20.2;
float h = 30.3;
float hif = 40.4;
String mqtt_message = "temp,f=" + String(t) + ",channel=10";
mqtt_message.toCharArray(msg, 50);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("arduino_1_data", msg, true);
mqtt_message = "rel_hum,rel_hum=" + String(h) + ",channel=11";
mqtt_message.toCharArray(msg, 50);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("arduino_1_data", msg, true);
mqtt_message = "temp,f=" + String(hif) + ",channel=12";
mqtt_message.toCharArray(msg, 50);
Serial.print("Publish message: ");
Serial.println(msg);
client.publish("arduino_1_data", msg, true);
delay(5000);
}
Thnx will try it soon and then report u
Hi .
What is the prefered version of AT commands with cayenne? 0.22 or the new 1.1?
Hi @vapor83,
It is very confusing. Doesn't help that there are multiple ways to program, multiple softwares, and multiple ESP devices and boards based on those devices.
I prefer to tell people to just program the ESP directly with Cayenne, and use an I/O expander if you need more I/O.
So I don't have an answer for you. What we need to do is try, and let us know what works. Then we can create a detailed procedure and a table showing what works.
I've been using mainly the .22 which seems to work good. Just starting to use the 1.1 and that seems to work fine too. Just a fyi
Don't think it matters as long as it works.
What ESP, and how are you programming them?
Can you share a rough procedure for us?
So I've been using the ESP8266-01 & the new ESP8266-01S. I take a proto shield and mount the ESP to it or use a breadboard adapter if you want to be able to remove it (see pics). I basically make a ESP shield that goes to the Serial RX/TX with a switch on it for easy uploading to the arduino.
First you need to upload the AT firmware for the ESP so the arduino/cayenne can talk to it using AT commands. You need the following: ESP_download_tool_v2.4 & the ESP_IOT_SDK 1.0.0. I included just the files you need here for simplicity. Open the download tool and setup the files and addresses(ADDR) exactly as shown.
blank.bin --> 0xFE000boot_v1.5.bin --> 0x00000user1.1024.new.2.bin --> 0x1000blank.bin --> 0x7E000esp_init_data_default.bin --> 0xFC000
Now you should have AT command set firmware! Unground GPIO0 and reboot the ESP. Open up a serial terminal and test with come commands.
Set Baud at 115200 and try typing AT. It should send back "ok" if everything worked.
Now we need to set it to station mode. Type AT+CWMODE_DEF? and it will probably return the number 2... we want it to say 1. Now type AT+CWMODE_DEF=1 and it should say ok. Verify with the first command AT+CWMODE_DEF? and it should return 1 now. Now enter AT+RST and it will reboot and say ready. Now were ready to connect it to our sketch/cayenne.
You need to include this library : #include In the header of your sketch you need to define which serial were using which is usually the first Serial (pins 0 &1): #define EspSerial Serial ESP8266 wifi(EspSerial);
Then in setup you need to tell it to start by: EspSerial.begin(1115200); delay(10);
So when were done it looks like this:
#include <CayenneESP8266Shield.h>
char token[] = "blah";
char ssid[] = "devices";
char password[] = "password";
#define EspSerial Serial
ESP8266 wifi(EspSerial);
void setup()
{
EspSerial.begin(115200);
delay(10);
Cayenne.begin(token, wifi, ssid, password);
}
void loop()
{
Cayenne.run();
}
Thats it!
Cheers. That's awesome!
Thx,
The DS18B20 does not work on WeMos D1 R2 on Cayenne.Connected to pin D9, Virtual V1.Code:
#include "CayenneDefines.h"
#include "BlynkSimpleEsp8266.h"
#include "CayenneWiFiClient.h"
#define CAYENNE_DEBUG
#define CAYENNE_PRINT seryjny
#include <OneWire.h>
#include <DallasTemperature.h>
// Virtual Pin of the DS18B20 widget.
#define VIRTUAL_PIN V1
// Digital pin the DS18B20 is connected to. Do not use digital pins 0 or 1 since those conflict with the use of Serial.
const int tmpPin = D9;
OneWire oneWire(tmpPin);
DallasTemperature sensors(&oneWire);
char token[] = "..........";
char ssid[] = "............";
char password[] = "";
void setup()
{
Serial.begin(115200);
Cayenne.begin(token, ssid, password);
}
void loop()
{
Cayenne.run();
}
// This function is called when the Cayenne widget requests data for the Virtual Pin.));
}
I personally don't like running sensors.requestTemperatures in a CAYENNE_OUT call. No big deal when it's quick, but if you have multiples on the one wire bus, it can take some time.
I think standard practice should be to run it in a timed loop using the timer library interval function, then store the values into global variables that the CAYENNE_OUT functions can simply grab when requested.
Here's an example scheme you can implement.
i think the problem in that code is:where it says Cayenne.celsiusWrite(VIRTUAL_PIN, sensors.getTempCByIndex(0));
mod to Cayenne.virtualWrite(VIRTUAL_PIN, sensors.getTempCByIndex(0));
thats gets my ds18b20 sensor up and running.
regardsrck
hi there,i run esp8266-01 with ssr attached to it using thatfor the ssr, i use channel 3 cause all other channel boot with the ssr high and relay modules needs 5v ssr needs 3v to activatesimply copy and paste in arduino ide then change all ***** with your infos then upload
1 #define CAYENNE_DEBUG // Uncomment to show debug messages2 #define CAYENNE_PRINT Serial // Comment this out to disable prints and save space34 #include "CayenneDefines.h"5 #include "BlynkSimpleEsp8266.h"6 #include "CayenneWiFiClient.h"78 // Cayenne authentication token. This should be obtained from the Cayenne Dashboard.9 char token[] = "********";10 // Your network name and password.11 char ssid[] = "*******";12 char password[] = "*******";1314 void setup()15 {1617 Serial.begin(9600);18 Cayenne.begin(token, ssid, password);19 }20 21 void loop()22 { 23 Cayenne.run();24 }
Code should work the same, just need to research how to put it in programmode and set the device setting for the amount of memory etc your devicehas.
Google your device and set the Arduino IDE settings to match.
change celsiusWrite for virtualWrite | http://community.mydevices.com/t/esp8266/820?page=6 | CC-MAIN-2017-51 | refinedweb | 1,355 | 62.04 |
Question 1: (Strings, Numbers, Boolean)
var num = 8; var num = 10; console.log(num);
Answer 10 **Explanation — **With the var keyword, you can declare multiple variables with the same name. The variable will then hold the latest value. You cannot do this with let or const since they're block-scoped.
Question 2:
function sayHi() { console.log(name); console.log(age); var name = 'Ayush'; let age = 21; } sayHi();
Answer undefined and ReferenceError **Explanation — *.
Question 3:
function getAge() { 'use strict'; age = 21; console.log(age); } getAge();
Answer ReferenceError Explanation With "use strict", you can make sure that you don't accidentally declare global variables. We never declared the variable age, and since we use "use strict", it will throw a reference error. If we didn't use "use strict", it would have worked, since the property age would have gotten added to the global object.
Question 4:
+true; !'Ayush';
Answer 1 and false Explanation The unary plus tries to convert an operand to a number. true is 1, and false is 0.
The string 'Ayush' is a truthy value. What we're actually asking, is "is this truthy value falsy?". This returns false.
Question 5:
let number = 0; console.log(number++); console.log(++number); console.log(number);
Answer 0 2 2. Explanation The postfix unary operator ++:
Returns the value (this returns 0).
Increments the value (number is now 1).
The prefix unary operator ++:
Increments the value (number is now 2).
Returns the value (this returns 2).
This returns 0 2 2.
Question 6:
function sum(a, b) { return a + b; } sum(1, '2');
Answer "12" Explanation JavaScript is a dynamically typed language: we don’t specify what types of certain variables are. Values can automatically be converted into another type without you knowing, which is called implicit type coercion. Coercion is converting from one type into another.
In this example, JavaScript converts the number 1 into a string, in order for the function to make sense and return a value. During the addition of a numeric type (1) and a string type ('2'), the number is treated as a string. We can concatenate strings like "Hello" + "World", so what's happening here is "1" + "2" which returns "12".
Question 7:
String.prototype.giveAyushPizza = () => { return 'Just give Ayush pizza already!'; }; const name = 'Ayush'; name.giveAyushPizza();
Answer "Just give Ayush pizza already!" Explanation String is a built-in constructor, which we can add properties to. I just added a method to its prototype. Primitive strings are automatically converted into a string object, generated by the string prototype function. So, all strings (string objects) have access to that method!
Question 8:
for (let i = 1; i < 5; i++) { if (i === 3) continue; console.log(i); }
Answer 1 2 4 Explanation The continue statement skips an iteration if a certain condition returns true.
Question 9:
function sayHi() { return (() => 0)(); } console.log(typeof sayHi());
Answer "number" Explanation The sayHi function returns the returned value of the immediately invoked function expression (IIFE). This function returned 0, which is type "number".
FYI: there are only 7 built-in types: null, undefined, boolean, number, string, object, and symbol. "function" is not a type, since functions are objects, it's of type "object".
Question 10:
console.log(typeof typeof 1);
Answer "string" Explanation typeof 1 returns "number". And typeof "number" returns "string".
Question 11:
!!null; !!''; !!1;
Answer false false true Explanation null is falsy. !null returns true. !true returns false.
"" is falsy. !"" returns true. !true returns false.
1 is truthy. !1 returns false. !false returns true.
Question 12:
[...'Ayush'];
Answer ["A", "y", "u", "s", "h"] Explanation A string is an iterable. The spread operator maps every character of an iterable to one element.
Question 13:
console.log(3 + 4 + '5');
Answer "75" **Explanation — **Operator associativity is the order in which the compiler evaluates the expressions, either left-to-right or right-to-left. This only happens if all operators have the same precedence. We only have one type of operator: +. For addition, the associativity is left-to-right.
3 + 4 gets evaluated first. This results in the number 7.
7 + '5' results in "75" because of coercion. JavaScript converts the number 7 into a string. We can concatenate two strings using the +operator. "7" + "5" results in "75".
Question 14:
var a = 10; var b = a; b = 20; console.log(a); console.log(b); var a = 'Ayush'; var b = a; b = 'Verma'; console.log(a); console.log(b);
**Answer — **1. 10 and 20 2. "Ayush" and "Verma" Explanation The value assigned to the variable of primitive data type is tightly coupled. That means, whenever you create a copy of a variable of primitive data type, the value is copied to a new memory location to which the new variable is pointing to. When you make a copy, it will be a real copy.
Question 15:
function sum(){ return arguments.reduce((a, b) => a + b); } console.log(sum(1,2,3)); (1) function sum(...arguments){ return arguments.reduce((a, b) => a + b); } console.log(sum(1,2,3)); (2)
**Answer — **1. Error will be thrown. 2. 6 Explanation —
- Arguments are not fully functional array, they have only one method length. Other methods cannot be used on them.
- ... rest operator creates an array of all functions parameters. We then use this to return the sum of them.
Question 16:
console.log(1 == '1'); console.log(false == '0'); console.log(true == '1'); console.log('1' == '01'); console.log(10 == 5 + 5);
Answer true true true false true. Explanation —'1' == '01' as we are comparing two strings here they are different but all other equal.
Question 17:
console.log('1' - - '1'); (1) console.log('1' + - '1'); (2)
**Answer — **1. 2 2. “1–1” Explanation —
- With type coercion string is converted to number and are treated as 1 - -1 = 2. 2.+ operator is used for concatenation of strings in javascript, so it is evaluated as '1' + '-1' = 1-1.
Question 18:
let lang = 'javascript'; (function(){ let lang = 'java'; })(); console.log(lang); (1) (function(){ var lang2 = 'java'; })(); console.log(lang2); (2)
**Answer — **1. “javascript” 2. Error will be thrown. Explanation —
- Variables defined with let are blocked scope and are not added to the global object.
- Variables declared with var keyword are function scoped, so wrapping the function inside a closure will restrict it from being accessed outside that is why it throws error
Question 19:
(function(){ console.log(typeof this); }).call(10);
Answer object** Explanation** — call invokes the function with new this which in this case is 10 which is basically a constructor of Number and Number is object in javascript.
Question 20:
console.log("[ayushv.medium.com/]()" instanceof String); (1) const s = new String('[ayushv.medium.com/]()'); console.log(s instanceof String); (2)
**Answer — **1. false 2. true Explanation — Only strings defined with String() constructor are instance of it.
Question 21: (Objects, Arrays)
const obj = { a: 'one', b: 'two', a: 'three' }; console.log(obj);
Answer { a: "three", b: "two"}" Explanation If you have two keys with the same name, the key will be replaced. It will still be in its first position, but with the last specified value.
Question 22:
let c = { greeting: 'Hey!' }; let d; d = c; c.greeting = 'Hello'; console.log(d.greeting);
Answer Hello **Explanation — **In JavaScript, all objects interact by reference when setting them equal to each other.
First, a variable c holds a value to an object. Later, we assign d with the same reference that c has to the object. When you change one object, you change all of them.
Question 23:
let a = 3; let b = new Number(3); let c = 3; console.log(a == b); console.log(a === b); console.log(b === c);
Answer true false false Explanation new Number() is a built-in function constructor. Although it looks like a number, it's not really a number: it has a bunch of extra features and is an object.
When we use the == operator, it only checks whether it has the same value. They both have the value of 3, so it returns true.
However, when we use the === operator, both value and type should be the same. It's not: new Number() is not a number, it's an object. Both return false.
Question 24:
function getAge(...args) { console.log(typeof args); } getAge(21);
Answer "object" Explanation The rest parameter (...args) lets us "collect" all remaining arguments into an array. An array is an object, so typeof args returns "object".
Question 25:
let greeting; greetign = {}; // Typo! console.log(greetign);
Answer {} Explanation It logs the object, because we just created an empty object on the global object! When we mistyped greeting as greetign, the JS interpreter actually saw this as global.greetign = {} (or window.greetign = {} in a browser).
In order to avoid this, we can use "use strict". This makes sure that you have declared a variable before setting it equal to anything.
Question 26:
function checkAge(data) { if (data === { age: 18 }) { console.log('You are an adult!'); } else if (data == { age: 18 }) { console.log('You are still an adult.'); } else { console.log(`Hmm.. You don't have an age I guess`); } } checkAge({ age: 18 });
Answer Hmm.. You don't have an age I guess Explanation When testing equality, primitives are compared by their value, while objects are compared by their reference. JavaScript checks if the objects have a reference to the same location in memory.
The two objects that we are comparing don’t have that: the object we passed as a parameter refers to a different location in memory than the object we used in order to check equality.
This is why both { age: 18 } === { age: 18 } and { age: 18 } == { age: 18 } return false.
Question 27:
const obj = { 1: 'a', 2: 'b', 3: 'c' }; const set = new Set([1, 2, 3, 4, 5]); obj.hasOwnProperty('1'); obj.hasOwnProperty(1); set.has('1'); set.has(1);
Answer true true false true Explanation All object keys (excluding Symbols) are strings under the hood, even if you don’t type it yourself as a string. This is why obj.hasOwnProperty('1') also returns true.
It doesn’t work that way for a set. There is no '1' in our set: set.has('1') returns false. It has the numeric type 1, set.has(1) returns true.
Question 28:
const a = {}; const b = { key: 'b' }; const c = { key: 'c' }; a[b] = 123; a[c] = 456; console.log(a[b]);
Answer 456 Explanation Object keys are automatically converted into strings. We are trying to set an object as a key to object a, with the value of 123.
However, when we stringify an object, it becomes "[object Object]". So what we are saying here, is that a["[object Object]"] = 123. Then, we can try to do the same again. c is another object that we are implicitly stringifying. So then, a["[object Object]"] = 456.
Then, we log a[b], which is actually a["[object Object]"]. We just set that to 456, so it returns 456.
Question 29:
const numbers = [1, 2, 3]; numbers[10] = 11; console.log(numbers);
Answer [1, 2, 3, 7 x empty, 11] Explanation When you set a value to an element in an array that exceeds the length of the array, JavaScript creates something called “empty slots”. These actually have the value of undefined, but you will see something like:
[1, 2, 3, 7 x empty, 11]
depending on where you run it (it’s different for every browser, node, etc.).
Question 30:
let person = { name: 'Ayush' }; const members = [person]; person = null; console.log(members);
Answer [{ name: "Ayush" }] Explanation We are only modifying the value of the person variable, and not the first element in the array, since that element has a different (copied) reference to the object. The first element in members still holds its reference to the original object. When we log the members array, the first element still holds the value of the object, which gets logged.
Question 31:
const person = { name: 'Ayush', age: 21, }; for (const item in person) { console.log(item); }
Answer "name", "age" Explanation With a for-in loop, we can iterate through object keys, in this case name and age. Under the hood, object keys are strings (if they're not a Symbol). On every loop, we set the value of item equal to the current key it’s iterating over. First, item is equal to name, and gets logged. Then, item is equal to age, which gets logged.
Question 32:
[1, 2, 3].map(num => { if (typeof num === 'number') return; return num * 2; });
Answer [undefined, undefined, undefined] Explanation When mapping over the array, the value of num is equal to the element it’s currently looping over. In this case, the elements are numbers, so the condition of the if statement typeof num === "number" returns true. The map function creates a new array and inserts the values returned from the function.
However, we don’t return a value. When we don’t return a value from the function, the function returns undefined. For every element in the array, the function block gets called, so for each element, we return undefined.
Question 33:
var obj = {a:1}; var secondObj = obj; secondObj.a = 2; console.log(obj); console.log(secondObj); var obj = {a:1}; var secondObj = obj; secondObj = {a:2}; console.log(obj); console.log(secondObj);
**Answer — 1. { a:2 }and { a:2 } 2. { a:1 }and { a:2 } Explanation — **1. If the object property is changed, then the new object is pointing to the same memory address, so the original object property will also change. ( call by reference ) 2. If the object is reassigned with a new object then it is allocated to a new memory location, i.e it will be a real copy (call by value).
Question 34:
const arrTest = [10, 20, 30, 40, 50][1, 3]; console.log(arrTest);
Answer 40** Explanation** The last element from the second array is used as the index to get the value from first array like arrTest[3].
Question 35:
console.log([] + []); (1) console.log([1] + []); (2) console.log([1] + "abc"); (3) console.log([1, 2, 3] + [1, 3, 4]); (4)
**Answer — **1. "" 2. "1" 3. "1abc" 2. "1,2,31,3,4" **Explanation — **1. An empty array is while printing in console.log is treated as Array.toString(), so it prints an empty string. 2. An empty array when printed in console.log is treated as Array.toString() and so it is basically “1” + “” = "". 3. “1” + “abc” = "1abc". 4.“1, 2, 3” + “1, 3, 4” = "1,2,31,3,4".
Question 36:
const ans1 = NaN === NaN; const ans2 = Object.is(NaN, NaN); console.log(ans1, ans2);
Answer false true Explanation NaN is a unique value so it fails in equality check, but it is the same object so Object.is returns true.
Question 37:
var a = 3; var b = { a: 9, b: ++a }; console.log(a + b.a + ++b.b);
Answer 18 **Explanation — **Prefix operator increments the number and then returns it. So the following expression will be evaluated as 4 + 9 + 5 = 18.
Question 38:
const arr = [1, 2, undefined, NaN, null, false, true, "", 'abc', 3]; console.log(arr.filter(Boolean)); (1) const arr = [1, 2, undefined, NaN, null, false, true, "", 'abc', 3]; console.log(arr.filter(!Boolean)); (2)
**Answer —
- [1, 2, true, “abc”, 3].
- **It will throw an error. **Explanation — **1. Array.filter() returns the array which matches the condition. As we have passed Boolean it returned all the truthy value.
- As Array.filter() accepts a function, !Boolean returns false which is not a function so it throws an error Uncaught TypeError: false is not a function.
Question 39:
const person = { name: 'Ayush Verma', .25e2: 25 }; console.log(person[25]); console.log(person[.25e2]); console.log(person['.25e2']);
Answer 25 25 undefined** Explanation** While assign the key the object evaluates the numerical expression so it becomes person[.25e2] = person[25]. Thus while accessing when we use 25 and .25e2 it returns the value but for '.25e2' is undefined.
Question 40:
console.log(new Array(3).toString());
Answer “,,”** Explanation** Array.toString() creates string of the array with comma separated values.
Question 41: (setTimeout and “this” keyword)
const foo = () => console.log('First'); const bar = () => setTimeout(() => console.log('Second')); const baz = () => console.log('Third'); bar(); foo(); baz();
Answer First Third Second Explanation We have a setTimeout function and invoked it first. Yet, it was logged last.
This is because, in browsers, we don’t just have the runtime engine, we also have something called a WebAPI. The WebAPI gives us the setTimeout function to start with and for example the DOM. The WebAPI can’t just add stuff to the stack whenever it’s ready. Instead, it pushes the callback function to something called the queue. An event loop looks at the stack and task queue. If the stack is empty, it takes the first thing on the queue and pushes it onto the stack.
Question 42:
for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1); } for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 1); }
Answer 3 3 3 and 0 1 2 **Explanation — **Because of the event queue in JavaScript, the setTimeout callback function is called after the loop has been executed. Since the variable i in the first loop was declared using the var keyword, this value was global. During the loop, we incremented the value of i by 1 each time, using the unary operator ++. By the time the setTimeout callback function was invoked, i was equal to 3 in the first example.
In the second loop, the variable i was declared using the let keyword: variables declared with the let (and const) keyword are block-scoped (a block is anything between { }). During each iteration, i will have a new value, and each value is scoped inside the loop.
Question 43:
let obj = { x: 2, getX: function() { setTimeout(() => console.log('a'), 0); new Promise( res => res(1)).then(v => console.log(v)); setTimeout(() => console.log('b'), 0); } } obj.getX();
Answer 1 a b** Explanation** When a macrotask is completed, all other microtasks are executed in turn first, and then the next macrotask is executed.
Mircotasks include: MutationObserver, Promise.then() and Promise.catch(), other techniques based on Promise such as the fetch API, V8 garbage collection process, process.nextTick() in node environment.
Marcotasks include initial script, setTimeout, setInterval, setImmediate, I/O, UI rendering.
An immediately resolved promise is processed faster than an immediate timer because of the event loop priorities dequeuing jobs from the job queue (which stores the fulfilled promises’ callbacks) over the tasks from the task queue (which stores timed out setTimeout() callbacks).
Question 44:
const shape = { radius: 10, diameter() { return this.radius * 2; }, perimeter: () => 2 * Math.PI * this.radius, }; console.log(shape.diameter()); console.log(shape.perimeter());
Answer 20 and NaN Explanation Note that the value of diameter is a regular function, whereas the value of perimeter is an arrow function.
With arrow functions, the this keyword refers to its current surrounding scope, unlike regular functions! This means that when we call perimeter, it doesn't refer to the shape object, but to its surrounding scope (window for example).
There is no value radius on that object, which returns NaN.
Question 45:
function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } const member = new Person('Ayush', 'Verma'); Person.getFullName = function() { return `${this.firstName} ${this.lastName}`; }; console.log(member.getFullName());
Answer TypeError Explanation In JavaScript, functions are objects, and therefore, the method getFullName gets added to the constructor function object itself. For that reason, we can call Person.getFullName(), but member.getFullName throws a TypeError.
If you want a method to be available to all object instances, you have to add it to the prototype property:
Person.prototype.getFullName = function() { return `${this.firstName} ${this.lastName}`; };
Question 46:
function Person(firstName, lastName) { this.firstName = firstName; this.lastName = lastName; } const ayush = new Person('Ayush', 'Verma'); const sarah = Person('Sarah', 'Smith'); console.log(ayush); console.log(sarah);
Answer Person {firstName: "Ayush", lastName: "Verma"} and undefined Explanation For sarah, we didn't use the new keyword. When using new, this refers to the new empty object we create. However, if you don't add new, this refers to the global object!
We said that this.firstName equals "Sarah" and this.lastName equals "Smith". What we actually did, is defining global.firstName = 'Sarah' and global.lastName = 'Smith'. sarah itself is left undefined, since we don't return a value from the Person function.
Question 47:
const person = { name: 'Ayush' }; function sayHi(age) { return `${this.name} is ${age}`; } console.log(sayHi.call(person, 21)); console.log(sayHi.bind(person, 21));
Answer Ayush is 21 function Explanation With both, we can pass the object to which we want the this keyword to refer. However, .call is also executed immediately!
.bind. returns a copy of the function, but with a bound context! It is not executed immediately.
Question 48:
let obj = { x: 2, getX: function() { console.log(this.x); } } obj.getX(); (1) let x = 5; let obj = { x: 2, getX:() => { console.log(this.x) } } obj.getX(); (2) let x = 5; let obj = { x: 2, getX: function(){ let x = 10; console.log(this.x); } } let y = obj.getX; y(); (3)
**Answer — **1) 2 2) 5 3) 5 Explanation First case is a regular function, the this keyword is bound to different values based on the context in which the function is called. Here obj is calling the function to this will point to current obj.
The second case is an arrow function, it will use the value of this in their ***lexical scope **i.e *value of x in surrounding scope. Here surrounding is the global scope or window object and “x” is also present. If “x” is not present then it is undefined.
In the third case, “y” is assigned a value of obj.getX,and “y” is in the global scope or window object. Hence “this” will point to global scope i.e. 5.
Question 49:
let a = 10, b = 20; setTimeout(function () { console.log('Ayush'); a++; b++; console.log(a + b); }); console.log(a + b);
Answer 30 “Ayush” 32. Explanation Settimeout pushes the function into BOM stack in event loop or it is executed after everything is executed in main function. So the results are printed after the console.log of main function.
Question 50:
function a() { this.site = 'Ayush'; function b(){ console.log(this.site); } b(); } var site = 'Wikipedia'; a(); (1) function a() { this.site = 'Ayush'; function b(){ console.log(this.site); } b(); } var site = 'Wikipedia'; new a(); (2) function a() { this.site = 'Ayush'; function b(){ console.log(this.site); } b(); } let site = 'Wikipedia'; new a(); (3)
**Answer —
- 'Ayush'.
- 'Wikipedia'
- undefined
Explanation
When a function with normal syntax is executed the value of this of the nearest parent will be used if not set at execution time, so in this case it is window, we are then updating setting the property site in the window object and accessing it inside so it is 'Ayush'.
When a function is invoked as a constructor with new keyword then the value of this will be the new object which will be created at execution time so currently, it is { site: 'Ayush' }.
But when a function with normal syntax is executed, the value of this will default to global scope if it is not assigned at the execution time so it is window for b() and var site = 'Wikipedia'; adds the value to the global object, hence when it is accessed inside b() it prints 'Wikipedia'.
- Variables defined with let are not added to the global scope. Hence, undefined.
I hope you have found this useful. Thank you for reading! | https://plainenglish.io/blog/50-javascript-output-questions | CC-MAIN-2022-40 | refinedweb | 3,942 | 60.61 |
Details
- Type:
Bug
- Status: Closed
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: 0.7
-
- Component/s: JavaScript - Compiler, Node.js - Compiler
- Labels:
- Patch Info:Patch Available
Description.
Issue Links
- incorporates
THRIFT-1134 Node.js test suite
- Closed
Activity
- All
- Work Log
- History
- Activity
- Transitions
I wonder if we should instead make a backwards incompatible change for the 0.8 release and change the callback style to match the rest of Node.js: callback(err, result). instead of the current: callback(result).
+1 to incompatible change to use the node.js style of callback(err, result); All of our existing code uses this style, and it is essential when dealing with async handlers in a service.
It looks like Russell Haering has a good example of how this should look:
I'll start working on a patch for this next week if no-one jumps in.
New patch, with callback(err, result) instead.
Updated gist:1151782 usecase also.
Should support syntax from gist:1098395 (Russel Haering) as well.
Implemented it using instanceof and early returns. What do you think?
New version. The previous one didn't get the namespace right for exceptions that where included from other files.
I'm new to this project but this is a show stopper for Node.JS usage. I dont consider it a priority to support backwards compatibility with the old mechanism or waiting until 0.8 release to commit this fix.
Hans, can you please add the test cases into the lib/test for this
I was trying to extend Roger's new test.sh to use a nodejs server but I noticed that the compiler wasn't working any more... no exceptions, namespaces, etc. I've also create a first draft of a test server (see attached test/nodejs/server.js)
under thrift/test run:
../compiler/cpp/thrift --gen js:node -o ./nodejs ThriftTest.thrift export NODE_PATH=../lib/nodejs/lib/thrift/ node nodejs/server.js
I had to re-base this old patch 'thrift-1267-callback-ns-fix.patch' and make some other small changes. Please someone have a look/test and commit this. Otherwise we won't be able to use nodejs.
That's what I was trying to archive, if anyone wants to have a look, I think there is still something missing since it doesn't seem to close the stream properly... (I only see the first test)
test/test.sh:
do_test "cpp-nodejs" "binary" "buffered-ip" \ "cpp/TestClient" \ "node nodejs/server.js" \ "1"
Thanks
Would be great to add all that stuff!
I'm currently not familiar with node...
I have the same issue with the testcase, just shows the first test case.
The other thing is, that the [^THRIFT-1267-ns-fixes.patch] breaks the examples located at lib/nodejs/examples/
OK thanks for the feedback Roger,
a line too much in the compiler and the client were outdated (see comments above). The example should work again now.
I'm also adding the 4 files I have under test/nodejs, including a package.json but it wasn't tested with npm.
The client.js is just a start, it only test a 12 of the services and it would look a lot nicer with qunit, but it'd add a dependency...
From these few unit tests we can see already that a lot of stuff is not working as it should, e.g. int64 (negative and large values), maps and services with exceptions only work partially (app. exceptions come as 'null' and nothing comes back on success)
Anyway, I think that's an improvement already.
Yes, this is a improvement => committed!
Thanks Henrique!
Integrated in Thrift #385 (See)
THRIFT-1267 Node.js can't throw exceptions
Patch: Henrique Mendonca
roger :
Files :
- /thrift/trunk/.gitignore
- /thrift/trunk/compiler/cpp/src/generate/t_js_generator.cc
- /thrift/trunk/configure.ac
- /thrift/trunk/lib/nodejs/examples/Makefile
- /thrift/trunk/lib/nodejs/examples/server.js
- /thrift/trunk/lib/nodejs/examples/server_multitransport.js
- /thrift/trunk/test/Makefile.am
- /thrift/trunk/test/nodejs
- /thrift/trunk/test/nodejs/Makefile.am
- /thrift/trunk/test/nodejs/client.js
- /thrift/trunk/test/nodejs/package.json
- /thrift/trunk/test/nodejs/server.js
- /thrift/trunk/test/test.sh
Applies to both 0.7.x and trunk atm. | https://issues.apache.org/jira/browse/THRIFT-1267?focusedCommentId=13185320&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel | CC-MAIN-2016-07 | refinedweb | 705 | 60.82 |
Python SDK for CloudPassage Halo API
Project description
cloudpassage-halo-python-sdk
Installation
Requirements:
- requests
- pyaml
Install from pip with pip install cloudpassage. If you want to make modifications to the SDK you can install it in editable mode by downloading the source from this github repo, navigating to the top directory within the archive and running pip install -e . (note the . at the end).
Quick Start
Here’s the premise: you store your session configuration information (API credentials, proxy settings, etc) in the cloudpassage.HaloSession object. This object gets passed into the various class methods which allow you to interact with the CloudPassage Halo API.
Practical example: We’ll print a list of all servers in our account:
import cloudpassage api_key = MY_HALO_API_KEY api_secret = MY_API_SECRET session = cloudpassage.HaloSession(api_key, api_secret) server = cloudpassage.Server(session) list_of_servers = server.list_all() for s in list_of_servers: print "ID: %s Name: %s" % (s["id"], s["hostname"])
Docs
Where to download
Documentation can be found at
Building documentation
1. Clone the repository locally 1. Navigate to cloudpassage-halo-python-sdk/docs 1. run sphinx-build -b pdf source build/pdf 1. Docs will be located at cloudpassage-halo-python-sdk/docs/build/pdf/CloudPassage_Python_SDK_$VERSION.pdf
Testing
Testing procedure is documented at:
Changelog
v1.1.4 (2018-03-12)
- Bug Fix: set default hostname if empty. [Ash Wilson]
v1.1.3 (2018-03-07)
- CS-479 Add CloudPassageRateLimit Exception Class. [Jye Lee]
- Add Timeseries.stop() [Ash Wilson]
v1.1.2 (2018-02-26)
- Adding tests for TimeSeries() for events, scans, and issues endpoints. [Ash Wilson]
- Adding docs for TimeSeries class. [Ash Wilson]
- CS-458 Python SDK: Move multiple servers into a target group. [Hana Lee]
v1.1 (2018-01-05)
V1.1. [Hana Lee]
CS-426 add Agent Upgrades class. [Hana Lee]
CS-428 Add CveDetails class. [Hana Lee]
CS-428 Add CveDetails class. [Hana Lee]
CS-429 add cve exceptions class. [Hana Lee]
Conflict. [Hana Lee]
CS-427 add processes endpoint to servers class. [Hana Lee]
CS-427 add processes endpoint to servers class. [Hana Lee]
Add Accept-Encoding ‘gzip’ [Jye Lee]
Add Accept-Encoding ‘gzip’ [Jye Lee]
CS-359 Added traffic discovery endpoint to Server and ServerGroup classes. [Hana Lee]
Rev to v1.0.6.8. [Jye Lee]
Rev to v1.0.6.7. [Jye Lee]
CS-322 Fix naming from Server to Issue. [Jye Lee]
V1.0.6.6. [Jye Lee]
flake8: expected 2 blank lines, found 1
This is it @2. [Hana Lee]
This is it. [Hana Lee]
Test: see travis. [Hana Lee]
Test:add +x. [Hana Lee]
Test: use travis.sh. [Hana Lee]
Test: edit yml. [Hana Lee]
Test: travis.sh. [Hana Lee]
Test: script onlt. [Hana Lee]
Test: added if statement. [Hana Lee]
Test: took up typo. [Hana Lee]
Added echo branch. [Hana Lee]
Test: added travis after_success. [Hana Lee]
Test: print env. [Hana Lee]
Test: run py.test. [Hana Lee]
Test: run test_wrapper.sh. [Hana Lee]
Test: added ls. [Hana Lee]
Test: remove –it. [Hana Lee]
Test: show docker images. [Hana Lee]
Test: added image id. [Hana Lee]
Test: put docker run in before_install. [Hana Lee]
Test: using docker exec to run test_wrapper.sh. [Hana Lee]
Added test_wrapper.sh. [Hana Lee]
Edited the changelog. [Hana Lee]
Added converge version lock. [Hana Lee]
Added email notification. [Hana Lee]
Fix logic in api_key_manager class. [Hana Lee]
Modified pagination for servers endpoint. [Hana Lee]
Fixed logic in api key manager. [Hana Lee]
rev init to 1.0.6.3
Fixed logic in api key manager. [Hana Lee]
Bug/CS-283 fix kwargs params if 500. [Jye Lee]
remove unexpected spaces around =
Rev to 1.0.6.2. [Jye Lee]
Bug CS-269 edit doc server_id to issue_id. [Jye Lee]
v1.0.6 (2017-05-01)
Rev to v1.0.6. [Jye Lee]
Fixed flake8. [Hana Lee]
Added LocalUserGroup to __init__.py Fixed typo in server.py. [Hana Lee]
Fixed status_code 500s. [Hana Lee]
CS-267 add local user account endpoint to SDK. [Hana Lee]
CS-269 add issues endpoint to the SDK. [Jye Lee]
added list_all, describe, and resolve methods
CS-259. [Jye Lee]
Add delayed retry to http helper
Added required openssl version and python version. [Hana Lee]
v1.0.5 (2017-02-18)
Changes
- Improvents to list FIM baseline with detail information. [Hana Lee]
Other
- Fixed Flake8 styling issue. [Hana Lee]
- Changed the output FIM baseline to include more detail information. [Hana Lee]
- Change the child server group name to avoid “Name Peer groups cannot have the same name” [Hana Lee]
v1.0.4 (2017-01-31)
- Rev to v1.0.4. [Jye Lee]
- Fixes firewall log paging. [Spencer Herzberg]
v1.0.3 (2017-01-24)
Changes
- Improvements to server group creation, use grid-side input sanitization for post data. [Ash Wilson]
Other
- Rev setup.py version to 1.0.3. [Jye Lee]
- Rev to v1.0.3 to changelog. [Jye Lee]
- Scan history should use since and until. [Spencer Herzberg]
v1.0.1 (2016-12-02)
Changes
-]
Fix
- Fix: test: Corrected logic for running codeclimate (thanks @mong2) [Ash Wilson]
Other
- Remove -z from codeclimate if statement. [mong2]
v1.0 (2016-11-21))
New
- .gitchangelog.rc now takes latest version from cloudpassage/__init__.py. [Ash Wilson]
Fix
-]
Other
- Add all supported search fields for servers endpoint. [Jye Lee]
v0.100 (2016-10-11)
Fix
- Typo = should be == in requirements-testing.txt. [Jye Lee]
Other-09-02)]
Project details
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/cloudpassage/ | CC-MAIN-2018-26 | refinedweb | 922 | 80.48 |
Answered by:
Write data to SQL database
- I have a small program that I am writing and it scans through a .txt file to find "key" information for me. The "key" information is stored in a 1-dimension arrary temporarily. As I find the data I want to write it to a SQL database for storage until I call for the data to populate a calendar in CrystalReports. Can someone please help me! I don't know how to do anything with SQL in VB.NET .
Question
Answers
All replies
Learning ADO.NET
And here are some data samples:
Hi
A good ADO.NET book is probably the best place to start.
Check out the System.Data namespace. Depending on the data source (eg oracle, sql server) there are various different base class implementations you would prefer to use, but as a starter, take a look at ...
System.Data.SqlClient (SQL Server specific implementations)
SqlConnection ... handles connection to a database
SqlCommand ..... handles issuing commands against a connection
SqlTransaction ... defines transaction boundaries
SqlDateAdaptor / SqlDataReader etc ... for reading data into eg a dataset
Personally, I rarely work with these classes direct and prefer to delegate to the enterprise services addins from Microsoft ... Microsoft.Practices.EnterpriseLibrary.Data The Data factory abstracts most of the db interaction into a simple api .. well worth an inspection if you are working with SQL Server.
Good luck
Richard
Okay,
So say that I have a db called Schedule with two tables inside of it: Employee and Patient. The following are the entities of each tables.
Employee
Employee_ID (pk)
Employee_First_Name
Employee_Last_Name
Patient
Patient_ID (pk)
Patient_First_Name
Patient_Last_Name
Patient_Date
Patient_Notes
Employee_ID (fk)
As the program scans the a .txt file for information, how should I feed that info into the SQL db? I want it to write the data to the db as soon as it finishes each record in the .txt file. Im currnetly using Split to gather the info that I want off of each line.
Also, on a side note. In my .txt file, I have a section callled Notes: and notes can sometimes continure onto another line underneath it and I was wondering how I would capture all that info with a slip or if I should even be using the Split function for this. This is what my current Split function looks like.....
Dim NotesSplitValues() As String = {"Notes:", ""}
Thanks for any help,
QWERTYtech
Hi
There isn't enough information here for me to give you some robust code, so I've included below a simple flow structure which you may be able to adapt to your exact needs .. something along these lines .. (I've assumed you are using sql server)Using cn As New SqlClient.SqlConnection("connStr") Using sr As IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader("filepath")
cn.Open()Using trans As SqlClient.SqlTransaction = cn.BeginTransaction Do While sr.Peek >= 0 Dim data As String = sr.ReadLine '' Split the data row up into the relevant bits per the layout of your text file '' Now build the command objects that will call the stored procedures used to insert the data Dim cmd As New SqlClient.SqlCommand("dbo.InsertEmployee", cn)
cmd.CommandType = CommandType.StoredProcedure
'' Add all the parameters you needDim param As SqlClient.SqlParameter = cmd.CreateParameter
param.DbType = DbType........
param.Value = ParamValue
cmd.Parameters.Add(param)
'' Execute the stored procedure
cmd.ExecuteNonQuery()Loop
trans.Commit()End Using End Using End Using
Apologies if there are errors therein as I haven't actually done this for quite some time, but it serves as an example of which types you might choose to use and how you might go about using them.
I started by creating a connection object. This requires a connection string to locate the relevant database to insert into (see if you need help here).
Next we open the connection and create a transaction. Transactions are used to package bulk operations into a logical atomic group. The idea here is that if an exception is raised an some point within the group insert, the whole update process can be rolled back as if it never happened. These may or may not be the semantics you are looking for and if you are unfamiliar with transaction processing I'd recommend you take some time out to read up on them before proceeding much further with your application.
The next interesting part is the use of a command object. There are many reasons why this is the preferred mechanism for adding data to your database, but suffice to say at this juncture, you simply create a stored procedure in your database that accepts the incoming data through parameters. The stored proc will do the actual inserting/validation etc. There are lots of online examples on how to create a stored procedure.
The command object requires a parameter object for each parameter the stored procedure accepts. I have shown an simple example of adding one, however you will need to look closely at this objects properties (eg size, precision) which are dependant on the underlying parameters data type. Again, there are loads of articles on line that you should easily find.
Once all the parameters are added, execute the command object and (assuming it succeeds) move onto the next row.
Once all the data is added successfully, commit the transaction (rollback if there is an exception at some point).
Now the above is a very simple example that you will want to expand upon. There are many ways to configure connections etc to better suit your environment (isolation levels etc) so I would urge you to work on the enclosed and not actually use it as is.
Hope this helps set you off along the "right" path and good luck.
Richard
PS - With regard to extract the data from your text file; this operation is as simple as the structure of the data therein lets it be. If the parse is too complicated, maybe look to change the file layout to ease the operation.
- I actually don't have the ability to change the way the info in the .txt file is layed out. It is generated by another program we use. That program doesn't do what we need it to do so we are writing a small app to take the information it gives us in the .txt file and are using it to make something more useful. In my case I have to take the data from the .txt file and read it in and store it until I finish the entire .txt file, then I have to organize the data into a Calendar for each employee.
First, you need to create the Dataset and set it up with the tables and columns you want. Add a new file to your project, and in the wizard that follows indicate that you are creating a Dataset (I'll call it the default value of Dataset1). If you have an underlying database, create a TableAdapter for each of your tables (otherwise, create a DataTable for each table and add the columns yourself). The wizard that follows will ask for two basic things:
1. A connection string leading to your database.
2. An SQL statement describing what data you want the table to represent. In this case, you probably want to use "Select * FROM Table", replacing Table with the table name (Employee or Patient).
You want to be sure the wizard generates Insert statements (at least), because that is the one you'll be using the most. Once you have the two TableAdapters, you have the basic skeleton you need for database access. Note the names of the TableAdapters, because you will be using them in code.
Now, in your code, set up an instance of your Dataset and the two TableAdapters. This should look something like:
Dim oData As New DataSet1 ' or whatever you called the DataSet you created
Dim oEmployeeAdapter As New Dataset1TableAdapters.EmployeeTableAdapter
Dim oPatientAdapter As New Dataset1TableAdapters.PatientTableAdapter
Now you start parsing your text file, inserting rows into the tables as needed:
While Not EndOfFile ‘ or whatever you use to read the file
‘ read and line of text and parse it
‘ decide which table and which the text is supposed to be put in
‘ put the text in a row of the appropriate table
‘ for instance, say an array named Parsed() has data for the Employee table:
Select Case RowType
Case “Employee”
Dim row As New oData.Employee.NewEmployeeRow
row.EmployeeID = Parsed(0)
row.First_Name = Parsed(1)
row.Last_Name = Parsed(2)
oData.Employee.Rows.Add(row)
Case “Patient”
‘ code to add patient row
End Select
End While
Your dataset will be ready to hook up to the report now, but you need to issue an update statement to permanently assign the data to the database:
oEmployeeAdapter.Update(oData.Employee)
oPatientAdapter.Update(oData.Patient)
I've spelled it out as much as I am capable. You should be able to tackle the rest on your own.
Okay so I have found a code snippit on the web for a basic Insertion of data into a db.
I'm looking at the insert command and I was wondering how I could use it with data being gathered from my program.
myCommand = New SqlCommand("Insert into Employee values .........")
I not sure how to pass values to the insert command that are stored in a temporary String.
Can someone please help me?
QWERTYtech
- Thanks alot that really helps me out.... One quick question though...... I have two tables Employee & Patient . Employee has a PK of Employee_ID that is autogenerated. I also have a Patient table that has Patient_ID as PK and Employee_ID as FK. How would i link these together?
I'm not sure what you mean by "link these together" so I will make some guesses.
You don't need to include autogenerated fields in INSERT statements, so you can leave out the _ID fields and values (since you have no idea what they are before inserting them). If you want to know the key value of what you just entered, use ExecuteScalar rather than ExecuteNonQuery(), like:
key = theSqlCommand.ExecuteScalar()
This will return the first column of the first row added (make sure the primary key is the first column).
I don't know how your text file stores patient records. It probably either has its own employee ID's, or it uses something like the employee's name. If it's the name, then the employee ID can be determined by running a SELECT query on the database. Something like:
Dim oData as New DataSet
oData.Tables.Add("Employee")
Dim oSelect as New SqlCommand("SELECT Employee_ID FROM Employees WHERE First_Name=@First AND Last_Name=@Last ", oConnection)
oSelect.AddWithValue("First", StoredFirstName)
oSelect.AddWithValue("Last", StoredLastName)
Dim oAdapter As New SqlDataAdapter(oSelect)
oAdapter.Fill(oData.Tables("Employee")
If oData.Tables("Employee").Rows.Count > 0 Then
StoredEmployeeID = oData.Tables("Employee").Rows(0).Item("Employee_ID")
Else
' No employees of this name... think about adding the employee here!
End If
Hi
I'd recommend you try and stay away from issuing sql statements from within your application if you can. It's a bad design and makes your application less secure, less performant, less scalable and generally less abstracted from the data tier.
Try to use stored procedures to handle the inserts etc (assuming your db supports them) as shown in my previous example.
If you are using sql server, in the stored procedure, you can use the SCOPE_IDENTITY function to return the identity id assigned to the insert of the Employee etc and then use that as the foreign key in your other table ...
eg (exception handling etc omitted for clarity)
create procedure addData(@Name varchar ....... ) as
begin
insert into dbo.employee(name, ....) values (@name ....);
declare @employeeId integer;
set @employeeId = scope_identity();
insert into dbo.patient ( ... employeeid ....) values ( .... @employeeid ... );
end
Richard
Richard,
What I'm trying to do is write a small app that will allow our employee's to run a report that is generated by our "Patient Care" software and use some of the info from it to build a weekly Calendar of what patients each employee is seeing. What would u reconmend doing to store the information to then turn around and read it into a CrystalReport to populate my Calendars?
Thanks,
QWERTYtech
Hi,
Got a very simple question, I'm trying to follow the instructions above to add some rows to a database and I'm getting a little confused.
Dim row As New oData.Employee.NewEmployeeRow
I can't repeat the above line, here's what I got
and when I try to make
dim row as new, odata is not one of the options to use. The only thing similar I found was
Dimrow As ServiceArchiveDBDataSet.ServicesRow
but that don't work ofcourse.
ServiceArchiveDBDataset was created with a wizard
ServicesTableAdapter was created with a wizard as well.
Thanks everyone.
Viktor. | https://social.msdn.microsoft.com/Forums/vstudio/en-US/4dcf5546-6aa9-4e37-be39-9b963d69659b/write-data-to-sql-database?forum=vbgeneral | CC-MAIN-2015-35 | refinedweb | 2,143 | 64 |
Opened 10 years ago
Closed 10 years ago
#752 closed Bug (Fixed)
_ArrayUnique
Description
Hi,
#include <Array.au3> $r = StringSplit('a,u,t,o,i,t, , a, a', ',') ConsoleWrite(_ArrayToString($r, ' ') & @CRLF) $r = _ArrayUnique($r) ConsoleWrite(_ArrayToString($r, ' ') & @CRLF)
Output is:
9 a u t o i t a a 8 9 a u t o i a
There is also a typo in the helpfile : 2x containing
Success: Returns a 1-dimensional array containing containing only the unique elements of that Dimension
Mega
Attachments (0)
Change History (2)
comment:1 Changed 10 years ago by Jpm
comment:2 Changed 10 years ago by Jpm
- Milestone set to 3.2.13.14
- Owner changed from Gary to Jpm
- Resolution set to Fixed
- Status changed from new to closed
Fixed in version: 3.2.13 for me as the StringSplit return a first element which is the number of splitted strings. use new lag=2 in beta to suppress it if you don't like.
I leave it open so Gary cant correct the doc | https://www.autoitscript.com/trac/autoit/ticket/752 | CC-MAIN-2019-22 | refinedweb | 174 | 62.72 |
The
LineColumnReader is an extension to
BufferedReader
that keeps track of the line and column information of where the cursor is.
Constructor wrapping a
Reader
(
FileReader,
FileReader,
InputStreamReader, etc.)
reader- the reader to wrap
Closes the stream and releases any system resources associated with it. Once the stream has been closed, further read(), ready(), mark(), reset(), or skip() invocations will throw an IOException. Closing a previously closed stream has no effect.
Marks the present position in the stream. Subsequent calls to reset() will attempt to reposition the stream to this point.
readAheadLimit- Limit on the number of characters that may be read while still preserving the mark..
Reads a single character.
Reads characters into a portion of an array.
chars- Destination array of char
startOffset- Offset at which to start storing characters
length- Maximum number of characters to read
Reads characters into an array. This method will block until some input is available, an I/O error occurs, or the end of the stream is reached.
chars- Destination buffer
Not implemented.
buffer- Destination buffer
Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.
Resets the stream to the most recent mark.
Skips characters.
toSkip- the number of characters to skip | http://docs.groovy-lang.org/latest/html/gapi/groovy/io/LineColumnReader.html | CC-MAIN-2015-18 | refinedweb | 224 | 58.18 |
1. RenderingHigh-end for Spin Tires is GeForce GTX 260 which is at best considered mid-end in the industry. Let's say Spin Tires is good looking, so there are several unique algorithms that make it work fast, all based on a fact that a driving game like that is essentially a 2D game. Spin Tires basically consists of a heightmap and trees!
1a. Daylight with no sun
- 220 meters visibility distance (below average for 3D game)
- 3340 trees (below average for Spin Tires)
- 420 DIPs (a lot of instancing), 50 various pixel/vertex shaders (DirectX effects system used)
*DIP - "draw indexed primitive", a basic operation of submitting draw command to GPU, amount of DIPs defines how much CPU time does rendering system use.
- 280000 faces, opaque color pass overdraw: 1.5
- No Z prepass!
For GTX 260, GPU opaque color pass time: 7-8ms (resolution 1450x860)
Z prepass time: 4-5ms, consecutive color pass: 5-8ms, plus CPU time required to draw scene twice.
So for scene where hi-z doesnt work well, z prepass does not give performance gain (it's even worse on slower videocards like Intel Graphics).
Consequences of not having depth texture in color pass will be discussed later.
- Shader model 3.0 (DirectX 9)
Average shader instructions count: vertex 140, pixel 90.
Grass shader (most fillrate heavy): vertex 189, pixel 46 - per-vertex lighting
Heaviest shader: vertex 202, pixel 207 - terrain surface with parallax (tessellated near camera, uses per-vertex lighting)
- Per-vertex fog
- Per-vertex DOF factor outputted into A channel
- Static occlusion from trees is used to attenuate ground and bottom parts of trees using local vertex position Y component
- SSAO is computed after opaque color pass - so it is applied on top of lighting (but before transparent color pass).
The idea is, we don't want to have too much SSAO on grass and trees leaves, so by detecting green color (typical foliage color) and multiplying it by stencil mask, we approximate material AO intensity.
This tricky approach works surprisingly well - and is very scalable. If you don't have Z prepass, you need to use IntZ texture to read back depth buffer - but that is not always supported!
Alternatively it is possible to write out material AO intensity to alpha channel - but it is reserved for DOF factor in Spin Tires, which is considered more important effect and it works wihout IntZ support.
- Level in Spin Tires is divided into rectangular 16x16 (meters) blocks - called terrain blocks.
Each block contains list of trees, precomputed lightmaps, and a block map - ARGB8888 texture:
B - muddiness factor. Muddy areas are marked with darker/yellowish tint
G - material factor. Each block can only mix 2 diffuse textures
R - heightmap value. Block also contains float-value heights for 4 corners of the block, so BYTE is sufficient to store height
A - extruded flag. Extruded vertices are simply pushed down (along world "Y" direction) and mud (high-res terrain with different shader) is rendered inplace
Block can also contain "overlay" (a road) - in which case it uses additional diffuse and additional per-block ARGB8888 texture:
BG - packed "overlay" UV texture coordinates
R - "overlay" transparency
A - unused (no 3-channel texture available unforunately, and Spin Tires hits limit of 4 vertex samplers)
Each block selects its LOD, and uses one of pre-generated meshes to render itself.
static const float _OCCL_FALLOFF = .4f; static const float _OCCL_HEIGHT_FALLOFF = .3f; // XZ center of OBB shared float2 g_vOcclCenter = float2(0, 0); // g_vOcclData[0].xy = XZ components of OBB local "X direction" // g_vOcclData[0].z = local space OBB size along "X direction" // g_vOcclData[1].xy = XZ components of OBB local "Z direction" // g_vOcclData[1].z = local space OBB size along "Z direction" shared float3 g_vOcclData[2] = { float3(0, 0, 0), float3(0, 0, 0) }; // world-space heights of each of bottom OBB corners shared float4 g_vOcclHeight = float4(0, 0, 0, 0); float GetOBBOcclusion(in float3 vertexPos) { float deflectFactor = 1.f; float isInside = 1.f; // Along X, then Z float2 heights; float heightAt; [unroll] for (int i = 0; i < 2; i++) { const float3 data = g_vOcclData; float deflectorSize = data.z; float distPlane = dot(vertexPos.xz - g_vOcclCenter, data.xy) + deflectorSize * .5f; float distSecondPlane = deflectorSize - distPlane; if (i == 0) { heights = lerp(g_vOcclHeight.xy, g_vOcclHeight.zw, distPlane / deflectorSize); } else { heightAt = lerp(heights.x, heights.y, distPlane / deflectorSize); // just some shrinking of the occl volume near top distPlane -= saturate(vertexPos.y - (heightAt - 1.f)) * .4f; distSecondPlane -= saturate(vertexPos.y - (heightAt - 1.f)) * .4f; } // Need a smooth transition isInside *= saturate(1.f + (distPlane - _OCCL_FALLOFF) / _OCCL_FALLOFF); isInside *= saturate(1.f + (distSecondPlane - _OCCL_FALLOFF) / _OCCL_FALLOFF); } float heightFactor = saturate((vertexPos.y - heightAt) / _OCCL_HEIGHT_FALLOFF); isInside *= 1.f - heightFactor; return 1.f - isInside; }
1b. Daylight with sun
static const float MAX_LIGHT_HEIGHT = 64.f; const float shadowStartY = (1.f - lightMap2.r) * MAX_LIGHT_HEIGHT; const float shadowEndY = lightMap2.a * MAX_LIGHT_HEIGHT; const float shadowEndDelta = 3.f; float smAtten = 1.f - saturate((worldPos.y - shadowStartY) / .5f); smAtten = max(smAtten, 1.f - saturate((shadowEndY - worldPos.y) / shadowEndDelta));It also generates soft-looking shadows, which when blended with sharp PCF shadowmap gives a nice look. Another big problem though is that the maximum encoded height is 64 (meters) - and precision is awful. It can be fixed by moving to FP texture.
1c. Nighttime
float UnpackLightHeight(in float h) { return UnpackHeight(h, 0, MAX_LIGHT_HEIGHT); } float3 UnpackLightColor(in float3 rgb) { return rgb * MAX_LIGHT_COLOR_CHANNEL_VALUE; } float UnpackLightRange(in float r) { return r * MAX_LIGHT_RADIUS; } float3 UnpackXYZDirection(in float2 xzDir, in float heightOffset) { static const float yUnpackEmpiric = 1.5f; float yScale = heightOffset / yUnpackEmpiric; float2 xzDirSigned = (xzDir - .5f) * 2.f; float yComponent = sqrt( 1 - dot(xzDirSigned, xzDirSigned) ) * yScale; return normalize( float3(xzDirSigned.x, yComponent, xzDirSigned.y) ); } void AddTerrainPackedLighting(inout LIGHTING_DESC lighting, in SURFACE_DESC surface, in float4 lightMap1, in float4 lightMap2) { // lightMap1: RGB - light color, A - light occlusion (used for both direct and ambient lighting) // lightMap2: RG - xz dir to light, B - light height, A - light atten range float3 lightColor = UnpackLightColor(lightMap1.rgb) * g_fLightingMode; float lightHeight = UnpackLightHeight(lightMap2.b); float attenRange = UnpackLightRange(lightMap2.a); // Attenuation is computed with regards to height offset, XZ offset is already embeded to lightColor float heightOffset = lightHeight - surface.worldPos.y; // float3 dirToLight = UnpackXYZDirection(lightMap2.rg, heightOffset); float lambertAtten = GetLambertAtten(-dirToLight, surface.worldNormal, g_fBacksideLighting); // 2.0 multiplier makes distAtten 1.0 for < attenRange * 0.5 then linearly fades to 0 by attenRange float attenParam = heightOffset / attenRange; float distAtten = saturate( (1.f - abs(attenParam)) * 2.f ); // the same as : saturate( 1.0 + (1.0 - abs(heightOffset) / (attenRange / 2.0) ); lighting.diffuse += lightColor * lambertAtten * distAtten; #if defined(SPECULAR) float phongSpecular = GetSpecular(-dirToLight, surface); lighting.specular += lightColor * phongSpecular * distAtten; #endif }And it basically looks "satisfying". Lightmaps for the level are generated at export time - but dynamic lights can be blended with static lightmaps using a special shader.
atten = lerp(NdotL, 1.f, .25f);
2. Simulation
2a. VehicleSpin Tires uses Havok Physics. Havok Physics provides the interface to create vehicles, and would handle all simulation (and even most of user input/camera following). You can create a raycast vehicle - in which case, while simulating, Havok would shoot rays from a position of hardpoint of a wheel to determine its position, or linear cast vehicle, in which case Havok would use wheel geometry to determine collision points with ground. Neither of them work good when you drive over dynamic rigid bodies - because the wheel isn't an actual body in Havok's simulation, so it responds to collisions incorrectly (and incorrectly affects other bodies). Another problem is that with a Havok vehicle, all wheels are attached to a single ridig body (the chassis). But the chassis of a big truck can twist a lot (not to mention exotic trucks) - so if you want the chassis to be multiple bodies+constraint, at best you would have to create multiple vehicles. So Spin Tires doesn't use any of the Havok vehicle interfaces - it creates a vehicle as a set of bodies linked by constraints. And gets two problems: stability at high speed This is the reason Havok uses raycast/linearcast vehicles; rigid bodies dont get simulated correctly when they are moving fast, and if vehicle wheels don't get simulated correctly, vehicle dynamics breaks up completely. Unfortunately, that's what happens in Spin Tires - so top speed for vehicles is very limited. Possible solution would be to gradually reduce the radius of the wheel when it starts moving fast (either linear of angular velocity) - and compute the forces applied to the chassis on your own (reimplementing parts of Havok raycast Havok vehicle). rotating the wheels in response to user input Applying force to a wheel looks like this:
hkVector4 wheelTorque; wheelTorque.setMul4( wheelForceMultiplier * PHYSICS_TIMESTEP, wheelAxle ); pWheelBody->applyAngularImpulse( wheelTorque );Looks easy, but wheelForceMultiplier can't be simply proportional to user input (joystick position). If it is, and let's say wheelTorque is big enough to overcome friction - once static friction turns into dynamic friction, wheel angular velocity would exponentially increase and it will become unstable. Even worse, if a wheel hangs in the air - it would go ballistic immediately. So you have to use feedback (check how wheel angular velocity changes before applying torque). Not going into details - in Spin Tires it's one hack on top of another, but having established feedback, implementing locking/unlocking differentials is pretty easy and is more or less "physically correct". Wheels Physical simulation for wheels use Havok Softness Modifier. To make appearance of soft body, a single (average) contact point is passed to vertex shader in local space, and following code offsets vertices:
float3 GetSoftnessOffset(in float3 localPos, in CUSTOM_BASE_INPUT cbi) { const float halfWidth = g_wheelParams.x; const float radius = g_wheelParams.y; const float contactOffsetZ = g_softParams.y; const float contactAngle = g_softParams.z; const float contactDepth = g_softParams.w; // Upack COLOR float4 vDir = UnpackNormal4(cbi.vDir); vDir.z *= TANGENTSPACE_BINORMAL_SIGN; float a0 = .6f * (contactDepth + .1f) / radius; float a1 = 1.0f * (contactDepth + .1f) / radius; float a = abs(vDir.a - contactAngle); if (a > 1.f) { a = 2.f - a; } // Radial offset { float factor = lerp(-0.8f, 1.0f, pow(saturate(a/a0),2)); factor *= lerp(1.f, 0.f, saturate((a - a0)/(a1 - a0))); vDir.xy = vDir.xy * factor * contactDepth; } // Perpendicular offset { float factor = 1.f - saturate(a / a1 * .8f); float zOffset = vDir.z * factor * contactDepth; vDir.z = clamp(zOffset, -halfWidth * .4f, halfWidth * .4f) * 2.f; } float dZ = abs(localPos.z - contactOffsetZ) / halfWidth; dZ = saturate(1.8f - dZ); vDir *= dZ; return vDir.xyz; }Additonally, per-vertex offset noise is applied when wheel gets dirty to make appearance of mud sticking to wheel:
const float mudCoef = g_wheelParams.w; float seed = localPos.x * 7.371f + localPos.z * 5.913f + localPos.y * 3.598f; localPos *= 1.f + lerp(0.f, abs(fmod(seed, .06f)) - 0.02f, mudCoef);
2b. Water/mudHavok provides a lot of useful interfaces, so to create water (or mud, in SpinTires they use the same algorithm), you need to detect bodies that are inside volume of water (using so-called Havok-phantom), compute forces and apply them! Water
- Opaque color pass
- Underwater particles
- Apply SSAO
- Copy backbuffer into a texture to be used for water refraction
- Draw water surface (with z-write), use depth buffer for caustics, refraction, water transparency
- Draw transparent stuff, apply color LUT, finish rendering
#define RIVER_MAP_OPACITY(x) x.r #define RIVER_MAP_SPEED(x) x.gb #define RIVER_MAP_FOAM(x) x.a static const float4 RIVER_MAP_DEFAULT = float4(.5f, .50196f, .50196f, .1f); float2 GetRiverFlow(in float4 riverMap, out float flowSpeed) { float2 d = (RIVER_MAP_SPEED(riverMap) - .50196f) * 2.f; flowSpeed = length(d); return d; } float4 updateMapPS(in float2 t : TEXCOORD0) : COLOR0 { #ifdef NO_VFETCH return RIVER_MAP_DEFAULT; #endif const float unitWeight = 1.f; const float diagonalWeight = 0.707f; const float2 txl = g_vRiverMapSizeInv; const float3 offsets[8] = { float3(-txl.x, -txl.y, diagonalWeight), float3(0 , -txl.y, unitWeight), float3(+txl.x, -txl.y, diagonalWeight), float3(-txl.x, 0 , unitWeight), float3(+txl.x, 0 , unitWeight), float3(-txl.x, +txl.y, diagonalWeight), float3(0 , +txl.y, unitWeight), float3(+txl.x, +txl.y, diagonalWeight), }; float4 riverMap = tex2D( g_samRiverMap, t ); static const float dampCoef = 0.8f; static const float traverseCoef = 0.9f; static const float2 globalFlow = float2(-1.f, 0); float foamSumm = 0; // Update flow { float flowSpeed; float2 flowDir = GetRiverFlow(riverMap, flowSpeed); flowDir = normalize(flowDir + globalFlow * g_fFlow * .25f) * flowSpeed; for (int i = 0; i < 8; i++) { float4 neighbor = tex2D( g_samRiverMap, t + offsets.xy ); foamSumm += RIVER_MAP_FOAM(neighbor); float s; float2 d = GetRiverFlow(neighbor, s); float dp = dot(normalize(d), -normalize(offsets.xy)); flowDir += d * saturate((s - flowSpeed) / .25f - .5f) * saturate(dp) * offsets.z * traverseCoef; } flowDir *= dampCoef; if (abs(flowDir.x) <= .05f) { flowDir.x = 0; } if (abs(flowDir.y) <= .05f) { flowDir.y = 0; } // fade quickly at low opacity float waterOpacity = RIVER_MAP_OPACITY(riverMap); flowDir *= saturate(waterOpacity * 8.f); RIVER_MAP_SPEED(riverMap) = flowDir / 2.f + .50196f; } // Update foam { float4 riverFlow = tex2D( g_samRiverMap, t - globalFlow * txl ); float resultFoam = lerp( RIVER_MAP_FOAM(riverMap) = RIVER_MAP_FOAM(riverMap) * .49f + foamSumm / 8.f * .5f, lerp(RIVER_MAP_FOAM(riverMap), RIVER_MAP_FOAM(riverFlow), .8f) * .9f, g_fFlow); RIVER_MAP_FOAM(riverMap) = resultFoam; } return riverMap; }Mud
3. Tools for terrain creationIt so happened, there is a home-made terrain editor in Spin Tires (C++ MFC, shares engine with the game).
4. Few more things that might be interestingFull number of shaders in Spin Tires: 1200, collected by flying through scene - and of course some combinations are always missed what leads to retail-time stalls. Middleware used in Spin Tires: Havok Physics, LUA, PhysFS, pugiXML, zLib, DirectX samples' DXUT. Multithreading only used for Havok Physics - which does not give an obvious performance boost by simple observations. In-game GPU timers implemented. Nested CPU timers implemented - using Havok Physics SDK! 99% of performance problems can be solved with in-game timers, and very efficiently. In-game triggers are life savers. In Spin Tires, basically each keyboard key either triggers event or changes game state (analog to debug console). For instance, to freeze the game processing (while still maintaining free camera movement), need to press CTRL-C (in debug game build only). Having Spin Tires optimized like it is allows me to dream about porting it to X360/PS3 - the only problem might be fillrate when dealing with vast forest arrays. Relying on DirectX11 would prevent it. Some Spin Tires users even complain about not being able to run Spin Tires on videocard not supporting shader model 3.0. But it's hard to say how switching to DirectX11 would really affect userbase at this point. Trees in Spin Tires are rendered using hardware instancing. In area around truck, each tree has Havok Phantom - which detects collisions with tree AABB. When collided, tree instance is replaced with skinned model.
// EH for Effect Handle enum { EH_TERRAIN_TX_BLOCK_MAP = _EH_TCOMMON_LAST, EH_TERRAIN_TX_OVERLAY_MAP, EH_TERRAIN_TX_OVERLAY, EH_TERRAIN_TX_OVERLAY_HM, EH_TERRAIN_V_OVERLAY_TC_DATA, EH_TERRAIN_V_BLOCK_POS_DATA, EH_TERRAIN_V_CORNER_HEIGHTS, EH_TERRAIN_V_PARALLAX_SCALE, EH_TERRAIN_TX_GRASS, EH_TERRAIN_TX_DIRT, _EH_TERRAIN_LAST }; DEFINE_EFFECT_FILE_HANDLES("SpinTires/Terrain.fx", _EH_TCOMMON_LAST, _EH_TERRAIN_LAST, g_txBlockMap g_txOverlayMap g_txOverlay g_txOverlayHM g_vOverlayTcData g_vBlockPosData g_vCornerHeights g_vParallaxScale g_txGrass g_txDirt);And setting up a constant looks like this:
pEffect->SetTexture(EH_TERRAIN_TX_GRASS, _RESOURCE_TEXTURE(material.grass.pTex));Thats it, best regards and thanks for reading!!! | https://www.gamedev.net/articles/programming/general-and-gameplay-programming/rendering-and-simulation-in-an-off-road-driving-game-r3216 | CC-MAIN-2018-05 | refinedweb | 2,462 | 50.02 |
Test::Differences - Test strings and data structures and show differences if not ok
0.62
use Test; ## Or use Test::More use Test::Differences; eq_or_diff $got, "a\nb\nc\n", "testing strings"; eq_or_diff \@got, [qw( a b c )], "testing arrays"; ## Passing options: eq_or_diff $got, $expected, $name, { context => 300 }; ## options ## Using with DBI-like data structures use DBI; ... open connection & prepare statement and @expected_... here... eq_or_diff $sth->fetchall_arrayref, \@expected_arrays "testing DBI arrays"; eq_or_diff $sth->fetchall_hashref, \@expected_hashes, "testing DBI hashes"; ## To force textual or data line numbering (text lines are numbered 1..): eq_or_diff_text ...; eq_or_diff_data ...;
This module exports three test functions and four diff-style functions:
eq_or_diff
eq_or_diff_data
eq_or_diff_text
table_diff(the default)
unified_diff
oldstyle_diff
context_diff
When the code you're testing returns multiple lines, records or data structures and they're just plain wrong, an equivalent to the Unix
diff utility may be just what's needed. Here's output from an example test script that checks two text documents and then two (trivial) data structures:
t/99example....1..3 not ok 1 - differences in text # Failed test ((eval 2) at line 14) # +---+----------------+----------------+ # | Ln|Got |Expected | # +---+----------------+----------------+ # | 1|this is line 1 |this is line 1 | # * 2|this is line 2 |this is line b * # | 3|this is line 3 |this is line 3 | # +---+----------------+----------------+ not ok 2 - differences in whitespace # Failed test ((eval 2) at line 20) # +---+------------------+------------------+ # | Ln|Got |Expected | # +---+------------------+------------------+ # | 1| indented | indented | # * 2| indented |\tindented * # | 3| indented | indented | # +---+------------------+------------------+ not ok 3 # Failed test ((eval 2) at line 22) # +----+-------------------------------------+----------------------------+ # | Elt|Got |Expected | # +----+-------------------------------------+----------------------------+ # * 0|bless( [ |[ * # * 1| 'Move along, nothing to see here' | 'Dry, humorless message' * # * 2|], 'Test::Builder' ) |] * # +----+-------------------------------------+----------------------------+ # Looks like you failed 3 tests of 3..
The options to
eq_or_diff give some fine-grained control over the output.
context
This allows you to control the amount of context shown:
eq_or_diff $got, $expected, $name, { context => 50000 };
will show you lots and lots of context. Normally, eq_or_diff() uses some heuristics to determine whether to show 3 lines of context (like a normal unified diff) or 25 lines..
filename_aand
filename_b
The column headers to use in the output. They default to 'Got' and 'Expected'.
For extremely long strings, a table diff can wrap on your screen and be hard to read. If you are comfortable with different diff formats, you can switch to a format more suitable for your data. These are the four formats supported by the Text::Diff module and are set with the following functions:
table_diff(the default)
unified_diff
oldstyle_diff
context_diff
You can run the following to understand the different diff output styles:
use Test::More 'no_plan'; use Test::Differences; my $long_string = join '' => 1..40; TODO: { local $TODO = 'Testing diff styles'; # this is the default and does not need to explicitly set unless you need # to reset it back from another diff type table_diff; eq_or_diff $long_string, "-$long_string", 'table diff'; unified_diff; eq_or_diff $long_string, "-$long_string", 'unified diff'; context_diff; eq_or_diff $long_string, "-$long_string", 'context diff'; oldstyle_diff; eq_or_diff $long_string, "-$long_string", 'oldstyle diff'; }
Generally you'll find that the following test output is disappointing.
use Test::Differences; my $want = { 'Traditional Chinese' => '中國' }; my $have = { 'Traditional Chinese' => '中国' };' => '中國' }; my $have = { 'Traditional Chinese' => '中国' };|'中国' |'中國' * # +----+-----------------------+-----------------------+; } }
eval "use Test::Differences";
If you want to detect the presence of Test::Differences on the fly, something like the following code might do the trick for you:
use Test qw( !ok ); ## get all syms *except* ok eval "use Test::Differences"; use Data::Dumper; sub ok { goto &eq_or_diff if defined &eq_or_diff && @_ > 1; @_ = map ref $_ ? Dumper( @_ ) : $_, @_; goto Test::&ok; } plan tests => 1; ok "a", "b";
This method will let CPAN and CPANPLUS users download it automatically. It will discomfit those users who choose/have to download all packages manually.
By placing Test::Differences and its prerequisites in the t/lib directory, you avoid forcing your users to download the Test::Differences manually if they aren't using CPAN or CPANPLUS.
If you put a
use lib "t/lib"; in the top of each test suite before the
use Test::Differences;,
make test should work well.
You might want to check once in a while for new Test::Differences releases if you do this.
Testor
Test::More
This module "mixes in" with Test.pm or any of the test libraries based on Test::Builder (Test::Simple, Test::More, etc). It does this by peeking to see whether Test.pm or Test/Builder.pm is in %INC, so if you are not using one of those, it will print a warning and play dumb by not emitting test numbers (or incrementing them). If you are using one of these, it should interoperate nicely.
Exports all 3 functions by default (and by design). Use
use Test::Differences ();
to suppress this behavior if you don't like the namespace pollution.
This module will not override functions like ok(), is(), is_deeply(), etc. If it did, then you could
eval "use Test::Differences qw( is_deeply );" to get automatic upgrading to diffing behaviors without the
sub my_ok shown above. Test::Differences intentionally does not provide this behavior because this would mean that Test::Differences would need to emulate every popular test module out there, which would require far more coding and maintenance that I'm willing to do. Use the eval and my_ok deployment shown above if you want some level of automation.
Perls before 5.6.0 don't support characters > 255 at all, and 5.6.0 seems broken. This means that you might get odd results using perl5.6.0 with unicode strings.
Data::Dumperand older Perls.
Relies on Data::Dumper (for now), which, prior to perl5.8, will not always report hashes in the same order.
$Data::Dumper::Sortkeys is set to 1, so on more recent versions of Data::Dumper, this should not occur. Check CPAN to see if it's been peeled out of the main perl distribution and backported. Reported by Ilya Martynov <ilya@martynov.org>, although the Sortkeys "future perfect" workaround has been set in anticipation of a new Data::Dumper for a while. Note that the two hashes should report the same here:
not ok 5 # Failed test (t/ctrl/05-home.t at line 51) # +----+------------------------+----+------------------------+ # | Elt|Got | Elt|Expected | # +----+------------------------+----+------------------------+ # | 0|{ | 0|{ | # | 1| 'password' => '', | 1| 'password' => '', | # * 2| 'method' => 'login', * | | # | 3| 'ctrl' => 'home', | 2| 'ctrl' => 'home', | # | | * 3| 'method' => 'login', * # | 4| 'email' => 'test' | 4| 'email' => 'test' | # | 5|} | 5|} | # +----+------------------------+----+------------------------+
Data::Dumper also overlooks the difference between
$a[0] = \$a[1]; $a[1] = \$a[0]; # $a[0] = \$a[1]
and
$x = \$y; $y = \$x; @a = ( $x, $y ); # $a[0] = \$y, not \$a[1]
The former involves two scalars, the latter 4: $x, $y, and @a[0,1]. This was carefully explained to me in words of two syllables or less by Yves Orton <demerphq@hotmail.com>. The plan to address this is to allow you to select Data::Denter or some other module of your choice as an option.
Barrie Slaymaker <barries@slaysys.com> - original author Curtis "Ovid" Poe <ovid@cpan.org> David Cantrell <david@cantrell.org.uk>
You may use this software under the terms of the GNU public license, any version, or the Artistic license. | http://search.cpan.org/~dcantrell/Test-Differences-0.64/lib/Test/Differences.pm | CC-MAIN-2017-30 | refinedweb | 1,174 | 60.24 |
C
C graphics programs
- Draw shapes
- Bar chart
- Pie chart
- 3d bar chart
- Smiling face animation
- captcha
- Circles in circles
- Countdown
- Paint program in C
- Press me button game
- Web browser program
- Traffic light simulation
- Mouse pointer restricted in circle
C graphics examples
1. Drawing concentric circles
#include <graphics.h> int main() { int gd = DETECT, gm; int x = 320, y = 240, radius; initgraph(&gd, &gm, "C:\\TC\\BGI"); for ( radius = 25; radius <= 125 ; radius = radius + 20) circle(x, y, radius); getch(); closegraph(); return 0; }
2. C graphics program moving car
#include <graphics.h> #include <dos.h> int main() { int i, j = 0, gd = DETECT, gm; initgraph(&gd,&gm,"C:\\TC\\BGI"); settextstyle(DEFAULT_FONT,HORIZ_DIR,2); outtextxy(25,240,"Press any key to view the moving car"); getch(); for( i = 0 ; i <= 420 ; i = i + 10, j++ ) { rectangle(50+i,275,150+i,400); rectangle(150+i,350,200+i,400); circle(75+i,410,10); circle(175+i,410,10); setcolor(j); delay(100); if( i == 420 ) break; if ( j == 15 ) j = 2; cleardevice(); // clear screen } getch(); closegraph(); return 0; }
Graphics in Windows 7 or Vista
Most, use install button and then browse the package location. Now create a new project and select WinBGIm. This library also offers many functions which can be used for image manipulation, you can open image files, create bitmaps and print images, RGB colors and mouse handling. | https://www.programmingsimplified.com/c/graphics.h/ | CC-MAIN-2018-30 | refinedweb | 232 | 55.58 |
In Java, static is a keyword that we mainly use to manage memory. In this tutorial, we will discuss in detail how to use the static keyword in Java and its different purpose. We will also discuss about Java Static Class, Java Static Method, and Java Static Variables in this tutorial.
What is Java static keyword
We use Java static keyword mainly when we want to access the members without creating an instance of the class. This means the static members are part of the class and does not belong to the class instance. We can use the Java static keyword for the following:
- Block
- Variable
- Method
- Class
Whenever we create the above with static keyword, we can directly access them without creating an object. We need to precede with the java keyword static in the declaration. Static members share the memory for any instance of the class and hence we say that we use it to manage memory.
In Java, we always label the main method with the java static keyword because we can use it directly and it loads along with the class.
Let us discuss each of them in detail.
Java Static block
When a block contains the name as java keyword static, we call it a static block. We use static block when we want to initialize any static members while loading the class. It first executes this static block before it calls the main method. We can understand this further with an example below.
Syntax:
static { //code }
Example of a single static block
We have created a single static block with a print statement and static variable i value assignment. Now during execution, when the class loads, first it executes the static block where it prints the statement and then assigns the value to the variable i. After this, it calls the main method and executes the remaining statements. This is the reason that first, it prints “Inside static block” and then it prints “Inside main method”
public class StaticBlockExample { static int i; static { System.out.println("Inside the static block"); i = 10; } public static void main(String[] args) { System.out.println("Inside the main method"); System.out.println("Value of i: " + i); } }
Inside the static block Inside the main method Value of i: 10
Example of multiple static blocks
We can also create multiple static blocks in Java. It executes in the same order as it is written in the program. In the below example, we can see that in the output it prints the String value as “Good evening” as the value in static block 1 is overridden by the value in static block 2. Similarly the same is the reason for the integer value.
public class MultipleStaticBlockExample { static String value; static int number; static { System.out.println("Inside the static block 1"); value = "good afternoon"; number = 30; } static { System.out.println("Inside the static block 2"); value = "good evening"; number = 20; } public static void main(String[] args) { System.out.println("Inside the main method"); System.out.println("String value: " + value); System.out.println("Integer value: " + number); } }
Inside the static block 1 Inside the static block 2 Inside the main method String value: good evening Integer value: 20
Now let’s move on to understand the static variable.
Java Static Variables
When we declare a variable with the java static keyword before the variable name, we call it a static variable. Static variables are public and generally belong to the class rather than the instance of the class. Hence these are also called Class variables. We can directly access these static variables without using any object which is in contrast to the non-static variables that require an object to access them. Static variables share the same memory for any instance of a class that is created. These variables are stored in a space called Metaspace in the JVM memory pool.
If a program contains both static blocks and variables, then it executes them in the same order in which it is present.
Syntax:
static datatype variable_name; //Example static int i;
Example of Static variable with multiple objects
Consider the below example where we have a class named Student. We have also declared 1 static variable college and 2 non-static variables name and dept. Inside the static block, we have initialized the static variable. Now during execution when the class loads, it initializes this static variable first and then calls the main method where it invokes the constructor. We have 2 separate Student objects s1 and s2 with different name and dept. But if you notice in the output college value is the same for both the objects. This is because the static variable shares the same value for all class instances and memory is allocated only once.
public class Student{ static String college; public String name; public String dept; static { System.out.println("Static Block"); college = "BITS"; } Student(String name, String dept){ this.name = name; this.dept = dept; } public static void main(String[] args) { Student s1 = new Student("Harsh", "IT"); Student s2 = new Student("Kiran", "CSE"); System.out.println(s1.name + " " + s1.dept + " " + college); System.out.println(s2.name + " " + s2.dept + " " + college); } }
Static Block Harsh IT BITS Kiran CSE BITS
Example of Static variable using counter
Now we will see the difference between static and non-static variables which will help you understand the concept better. We have created a static variable counter and a non-static variable count both initialized to value 0. In the constructor, we increment both the values and print them. Now. when we create the first object, it prints both the values as 1. When we create the second object, the non-static variable is initialized again and hence the value will be still 1 but the static variable holds the same memory and hence value will be incremented to 2. This is because static variables are initialized only once during the loading of the class and are common for all the objects. Hope now we have understood the static keyword in java with respect to variables clearly.
public class StaticCounter { static int counter = 0; public int count = 0; StaticCounter(){ counter ++; count ++; System.out.println("Static Counter: " + counter); System.out.println("Non static Count: " + count); } public static void main(String[] args) { StaticCounter sc1 = new StaticCounter(); StaticCounter sc2 = new StaticCounter(); } }
Static Counter: 1 Non static Count: 1 Static Counter: 2 Non static Count: 1
Next, we will move on to static methods.
Java Static Method
When we use the java static keyword before any method, then we call it a static method. A static method does not require any class instance to access it and it belongs to a class rather than the object. We can directly access these methods and also access the static variables within this method to change its value. One best example of a static method in Java is the main method.
Below are the restrictions of using a static method:
- We cannot access non-static members within a static method
- Cannot call any non-static methods from a static method
- Cannot use super keyword within a static method
Syntax:
static return_type method_name() { //code } //Example static void display() { //code }
Now let us see an example of using a static method along with the static variables. We have a non-static method displayValue with an instance variable initialization and a static method display with static variable initialization. Within the main method, we don’t need an object to access a static method.
public class StaticMethodDemo { static int a; public String value; //Non Static method public void displayValue() { value = "Java"; System.out.println("String value: " + value); } //Static Method static void display() { a = 10; System.out.println("Value of a: " + a); } public static void main(String[] args) { StaticMethodDemo s = new StaticMethodDemo(); display(); s.displayValue(); } }
Value of a: 10 String value: Java
Now, consider that we call a non-static method and access an instance variable from a static method. We will get the below compilation error.
public class StaticMethodDemo { static int a; public String value; //Non Static method public void displayValue() { value = "Java"; System.out.println("String value: " + value); } //Static Method static void display() { a = 10; System.out.println("Value of a: " + a); value = "Hello"; displayValue(); } public static void main(String[] args) { StaticMethodDemo s = new StaticMethodDemo(); display(); s.displayValue(); } }
Exception in thread "main" java.lang.Error: Unresolved compilation problems: Cannot make a static reference to the non-static field value Cannot make a static reference to the non-static method displayValue() from the type StaticMethodDemo at StaticMethodDemo.display(StaticMethodDemo.java:16) at StaticMethodDemo.main(StaticMethodDemo.java:22)
Lets, move on to understand static class.
Java Static Class
If we create a class with prefix as a java static keyword, we call it a static class. We can use static class only for nested classes ie. a class within another class. Only inner classes can be made as a static class.
Features of a static class
- Can access only static variables of the outer class
- Cannot access other non-static variables or non-static methods of the outer class.
- A static class can contain non-static methods.
- We don’t need to create an object for the static class if we need to access a static method of that class.
- We cannot declare the outer class as static and can use a java static keyword only for the inner class.
Syntax:
public class classname { static class innerclassname { } }
Now let’s see various examples of using the nested static class.
Example of static class with a non-static method
In this example, we have a nested static class Inner with a non-static method display. Inside this method, we can access the static variables of the Outer class directly. In order to call this method from the Outer class main method, we need to create an object of the inner class, since the method is non-static. This is not required if we create a static method. We will see this in the next example below.
public class OuterClass { static int i = 5; static class Inner { public void display() { i ++; System.out.println(" Value of i: " + i); } } public static void main(String[] args) { OuterClass.Inner i = new OuterClass.Inner(); i.display(); } }
Value of i: 6
Example of static class with a static method
Now let’s see how to call a static method of a static class from the main method. Since the method is static, we can access the method from the main by directly using the inner class name as seen in the below example.
public class OuterClass { static int i = 5; static class Inner { static void display() { i++; System.out.println("Value of i: " + i); } } public static void main(String[] args) { OuterClass.Inner.display(); } }
Value of i: 6
Example of all Java static members
To summarize below is an example that covers all the java static keyword members like block, variable, method, and class.
public class StaticExample { static int number; public String value; static { number = 5; System.out.println("Value of number inside static block: " + number); } public void displayString() { value = "Hello"; System.out.println("Value of string: " + value); number =20; System.out.println("Value of number inside Outer class method: " + number); } static class Inner { static void display() { number = 10; System.out.println("Value of number inside static class method: " + number); } } public static void main(String[] args) { StaticExample s = new StaticExample(); StaticExample.Inner.display(); s.displayString(); } }
Value of number inside static block: 5 Value of number inside static class method: 10 Value of string: Hello Value of number inside Outer class method: 20 | https://www.tutorialcup.com/java/java-static-keyword.htm | CC-MAIN-2021-49 | refinedweb | 1,927 | 54.22 |
The web is full of tutorials about regular expressions. But I realized that most of those tutorials lack a thorough motivation.
- Why do regular expressions exist?
- What are they used for?
- What are some practical applications?
Somehow, the writers of those tutorials believe that readers are motivated by default to learn a technology that’s complicated and hard to learn.
Well, readers are not. If you’re like me, you tend to avoid complexity and you first want to know WHY before you invest dozens of hours learning a new skill. Is this you? Then keep reading. (Otherwise, leave now—and don’t tell me I didn’t warn you.)
So what are some applications of regular expressions?
As you read through the article, you can watch my explainer video:.
Here’s the ToC that also gives you a quick overview of the regex applications:
Search and Replace in a Text Editor
The most straightforward application is to search a given text in your text editor. Say, your boss asks you to replace all occurrences of a customer
'Max Power' with the name
'Max Power, Ph.D.,'.
Here’s how it would look like:
I used the popular text editor Notepad++ (recommended for coders). At the bottom of the “Replace” window, you can see the box selection “Regular expression”. But in the example, we used the most straightforward regular expression: a simple string.
So you search and replace all occurrences of the string ‘Max Power’ and give it back to your boss. But your boss glances over your document and tells you that you’ve missed all occurrences with only
'Max' (without the surname
'Power'). What do you do?
Simple, you’re using a more powerful regex:
'Max( Power)?' rather than only
'Max Power':
Don’t worry, it’s not about the specific regex
'Max( Power)?' and why it works. I just wanted to show you that it’s possible to match all strings that either look like this:
'Max Power' or like this:
'Max'.
Anyways, if you’re interested, you can read about the two regex concepts on the Finxter blog: matching groups and the question mark operator.
Searching Your Operating System for Files
This is another common application: use regular expressions to search (and find) certain files on your operating system.
For example, this guy tried to find all files with the following filename patterns:
abc.txt.r12222 tjy.java.r9994
He managed to do it on Windows using the command:
dir * /s/b | findstr \.r[0-9]+$
Large parts of the commands are a regular expression. In the final part, you can already see that he requires the file to end with
.r and an arbitrary number of numeric symbols.
As soon as you’ve mastered regular expressions, this will cost you no time at all and your productivity with your computer will skyrocket.
Searching Your Files for Text
But what if you don’t want to find files with a certain filename but with a certain file content? Isn’t this much harder?
As it turns out, it isn’t! Well, if you use regular expression and grep.
Here’s what a grep guru would do to find all lines in a file
'haiku.txt' that contain the word
'not'.
Grep is an aged-old file search tool written by famous computer scientist Ken Thompson. And it’s even more powerful than that: you can also search a bunch of files for certain content.
A Windows version of grep is the find utility.
Search Engines
Well, using regular expressions to find content on the web is considered the holy grail of search. But the web is a huge beast and supporting a full-fledged regex engine would be too demanding for Google’s servers. It costs a lot of computational resources. Therefore, nobody actually provides a search engine that allows all regex commands.
However, web search engines such as Google support a limited number of regex commands. For example, you can search queries that do NOT contain a specific word:
The search “Jeff -Bezos” will give you all the Jeff’s that do not end with Bezos. If a firstname is dominated like this, using advanced search operators is quite a useful extension.
Here’s an in-depth Google search guide that shows you how to use advanced commands to search the huge web even faster.
With the explosion of data and knowledge, mastering search is a critical skill in the 21st century.
Validate User Input in Web Applications
If you’re running a web application, you need to deal with user input. Often, users can put anything in the input fields (even cross-site scripts to hack your webserver). Your application must validate that the user input is okay—otherwise you’re guaranteed to crash your backend application or database.
How can you validate user input? Regex to the rescue!
Here’s how you’d check whether
- The user input consists only of lowercase letters:
[a-z]+,
- The username consists of only lowercase letters, underscores, or numbers:
[a-z_0-9]+, or
- The input does not contain any parentheses:
[^\(\)]+.
With regular expressions, you can validate any user input—no matter how complicated it may seem.
Think about this: any web application that processes user input needs regular expressions. Google, Facebook, Baidu, WeChat—all of those companies work with regular expressions to validate their user input. This skill is wildly important for your success as a developer working for those companies (or any other web-based company for that matter).
Guess what Google’s ex tech lead argues is the top skill of a programmer? You got it: regular expressions!
Extract Useful Information With Web Crawlers
Okay, you can validate user input with regular expressions. But is there more? You bet there is.
Regular expressions are not only great to validate textual data but to extract information from textual data.
For example, say you want to gain some advantage over your competition. You decide to write a web crawler that works 24/7 exploring a subset of webpages. A webpage links to other webpages. By going from webpage to webpage, your crawler can explore huge parts of the web—fully automatized.
Imagine the potential! Data is the asset class of the 21st century and you can collect this valuable asset with your own web crawler.
A web crawler can be a Python program that downloads the HTML content of a website:
Your crawler can now use regular expressions to extract all outgoing links to other websites (starting with
"<a href=").
A simple regular expression can now automatically get the stuff that follows—which is the outgoing URL. You can store this URL in a list and visit it at a later point in time.
As you’re extracting links, you can build a web graph, extract other information (e.g., embedded opinions of people) and run complicated subroutines on parts of the textual data (e.g., sentiment analysis).
Don’t underestimate the power of web crawlers when used in combination with regular expressions!
Data Scraping and Web Scraping
In the previous example, you’ve already seen how to extract useful information from websites with a web crawler.
But often the first step is to simply download a certain type of data from a large number of websites with the goal of storing it in a database (or a spreadsheet). But the data needs to have a certain structure.
The process of extracting a certain type of data from a set of websites and converting it to the desired data format is called web scraping.
Web scrapers are needed in finance startups, analytics companies, law enforcement, eCommerce companies, and social networks.
Regular expressions help greatly in processing the messy textual data. There are many different applications such as finding titles of a bunch of blog articles (e.g., for SEO).
A minimal example of using Python’s regex library
re for web scraping is the following:
from urllib.request import urlopen import re html = urlopen("").read() print(str(html)) titles = re.findall("\<title\>(.*)\</title\>", str(html)) print(titles) # ['What's The Best Way to Start Learning Python? A Tutorial in 10 Easy Steps! | Finxter']
You extract all data that’s enclosed in opening and closing title tags:
<title>...</title>.
Data Wrangling
Data wrangling is the process of transforming raw data into a more useful format to simplify the processing of downstream applications. Every data scientists and machine learning engineer knows that data cleaning is at the core of creating effective machine learning models and extracting insights.
As you may have guessed already, data wrangling is highly dependent on tools such as regular expression engines. Each time you want to transform textual data from one format to another, look no further than regular expressions.
In Python, the regex method
re.sub(pattern, repl, string) transforms a
string into a new one where each occurrence of
pattern is replaced by the new string
repl. You can learn everything about the substitution method on my detailed blog tutorial (+video).
This way, you can transform currencies, dates, or stock prices into a common format with regular expressions.
Parsing
Show me any parser and I show you a tool that leverages hundreds of regular expressions to process the input quickly and effectively.
You may ask: what’s a parser anyway? And you’re right to ask (there are no dumb questions). A parser translates a string of symbols into a higher-level abstraction such as a formalized language (often using an underlying grammar to “understand” the symbols). You’ll need a parser to write your own programming language, syntax system, or text editor.
For example, if you write a program in the Python programming language, it’s just a bunch of characters. Python’s parser brings order into the chaos and translates your meaningless characters into more meaningful abstractions (e.g. keywords, variable names, or function definitions). This is then used as an input for further processing stages such as the execution of your program.
If you’re looking at how parsers are implemented, you’ll see that they heavily rely on regular expressions. This makes sense because a regular expression can easily analyze and catch parts of your text. For example, to extract function names, you can use the following regex in your parser:
import re code = ''' def f1(): return 1 def f2() return 2 ''' print(re.findall('def ([a-zA-Z0-9_]+)', code)) # ['f1', 'f2']
You can see that our mini parser extracts all function names in the code. Of course, it’s only a minimal example and it wouldn’t work for all instances. For example, you can use more characters than the given ones to define a function name.
If you’re interested in writing parsers or learning about compilers, regular expressions are among the most useful tools in existence!
Programming Languages
Yes, you’ve already learned about parsers in the previous point. And parsers are needed for any programming language. To put it bluntly: there’s no programming language in the world that doesn’t rely on regular expressions for their own implementation.
But there’s more: regular expressions are also very popular when writing code in any programming language. Some programming languages such as Perl provide built-in regex functionality: you don’t even need to import an external library.
I assure you, if you’re becoming a professional coder, you will use regular expressions in countless of coding projects. And the more you use it, the more you’ll learn to love and appreciate the power of regular expressions.
Syntax Highlighting Systems
Here’s how my standard coding environment looks like:
Any code editor provides syntax highlighting capablities:
- Function names may be blue.
- Strings may be yellow.
- And normal code may be white.
This way, reading and writing code becomes far more convenient. More advanced IDEs such as PyCharm provide dynamic tooltips as an additional feature.
All of those functionalities are implemented with regular expressions to find the keywords, function names, and normal code snippets—and, ultimately, to parse the code to be highlighted and enriched with additional information.
Lexical Analysis in a Compiler
In compiler design, you’ll need a lexical analyzer:
The lexical analyzer needs to scan and identify only a finite set of valid string/token/lexeme that belong to the language in hand. It searches for the pattern defined by the language rules.
Regular expressions have the capability to express finite languages by defining a pattern for finite strings of symbols. The grammar defined by regular expressions is known as regular grammar. The language defined by regular grammar is known as regular language.Source
As it turns out, regular expressions are the gold standard for creating a lexical analyzer for compilers.
I know this may sound like a very specific application but it’s an important one nonetheless.
Formal Language Theory
Theoretical computer science is the foundation of all computer science. The great names in computer science, Alan Turing, Alonzo Church, and Steven Kleene, all spent significant time and effort studying and developing regular expressions.
If you want to become a great computer scientist, you need to know your fair share of theoretical computer science. You need to know about formal language theory. You need to know about regular expressions that are at the heart of these theoretical foundations.
How do regular expressions relate to formal language theory? Each regular expression defines a “language” of acceptable words. All words that match the regular expression are in this language. All words that do not match the regular expression are not in this language. This way, you can create a precise sets of rules to describe any formal language—just by using the power of regular expressions.
Where to Go From Here?
Regular expressions are widely used for many practical applications. The ones described here are only a small subsets of the ones used in practice. However, I hope to have given you a glance into how important and relevant regular expressions have been, are, and will remain in the future.
Want to learn more about how to convert your computer science skills into money? Check out my free webinar that shows you a step-by-step approach to build your thriving online coding business (working from home). You don’t need to have any computer science background though. The only thing you need is the ambition to learn.
Click:
>>IMAGE. | https://blog.finxter.com/what-are-regular-expressions-used-for-10-applications/ | CC-MAIN-2021-43 | refinedweb | 2,407 | 56.35 |
Details
- Type:
Bug
- Status: Resolved
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: 2.7.1
- Fix Version/s: 2.8.0, 2.7.4, 3.0.0-alpha2
-
- Labels:None
- Hadoop Flags:Reviewed
Description.
Issue Links
- breaks
HDFS-11312 Fix incompatible tag number change for nonDfsUsed in DatanodeInfoProto
- Resolved
- is broken by
-
- is related to
-
Activity
- All
- Work Log
- History
- Activity
- Transitions
2 ways we can solve this,
1) passing non-dfsused as a metric directly from DN side itself, similar to other stats, i.e. Moving the calculation to DN side
2) passing 'reserved' values and using that to calculate non-dfs usage at NN side.
Reserved is not updated in the DatanodeDescriptor so need to propogate back to NN side via heartbeat if we want to update that..So We can solve it by anyone of above apporach..
Thanks brahma for the options.
#1 would be better IMO.
Moving out all non-critical / non-blocker issues that didn't make it out of 2.7.2 into 2.7.3.
Uploading the patch to makes nonDFSUsed accurate by considering reservedForReplicas also.Actually bug is not there as mentioned in description,Since reserved was already subtracted from total capacity, nonDfsUsed was not including the reserved.
But getAvailable() value was calculated directly from DF, but there reserved was not considered, which was fixed.
Uploaded the patch fix the checkstyle issues.. Testcase failures are unrelated..Compilation errors are strange..? Chris Nauroth/Vinayakumar B kindly review..
..
-1 mvninstall 0m 33s hadoop-hdfs in the patch failed.
Compile done on parent but mvn install done only on hadoop-hdfs.Allen Wittenauer can you please take look on this..?
Yup. Working as intended.
Yup. Working as intended.
IMO, since the patch contains multi-module changes (hadoop-hdfs-client and hadoop-hdfs),
either "mvn install" should be done on parent directory, same as "mvn test-compile",
or, should be executed in dependency order (hadoop-hdfs-client and hadoop-hdfs).
Right?
should be executed in dependency order (hadoop-hdfs-client and hadoop-hdfs).
It's being done in the dependency order as dictated by the Yetus hadoop personality. If you feel the ordering is wrong, patches accepted.
Brahma Reddy Battula, thank you for working on this. My earliest opportunity to code review this will be next Tuesday, 11/17. Of course, if someone else in the community would like to take up the review, that's great too.
Brahma Reddy Battula, thank you for the patch. This looks pretty good to me, though I'd also appreciate a second code review, maybe from Vinayakumar B or Arpit Agarwal.
I just have one point of feedback right now. In DatanodeStorageInfo#toStorageReport, should the call to the StorageReport constructor pass along nonDfsUsed instead of hard-coding 0L?
After that's addressed, I'll put this through some manual testing too.
In DatanodeStorageInfo#toStorageReport, should the call to the StorageReport constructor pass along nonDfsUsed instead of hard-coding 0L?
That was a good catch. Chris Nauroth.
Apart from that everything else looks good to me as well. +1 once addressed.
Chris Nauroth and Vinayakumar B thanks a for your reviews..uploaded the patch to address above comment.Kindly review..
Please check the failure of hadoop.hdfs.server.namenode.metrics.TestNameNodeMetrics
This is not failing locally.But there is chance that this testcase can fail intermittently after this change(There is a chance that nonDFS usage might have slightly due to testlogs,).So I am keeping safeside as I did TestNamenodeCapacityReport.java
Check following results for same
Hi Brahma Reddy Battula, thanks for taking this up. The approach looks good.
- The calculation in FsVolumeImpl#getNonDfsUsed looks wrong. Won't it always be zero? The correct calculation should replace getAvailable() with actual volume free space. Something like Files.getFileStore(currentDir.toPath()).getUnallocatedSpace() perhaps. Also I think reservedForReplicas need not be subtracted in the nonDFSUsed calculation, since it is purely a bytes on disk calculation.
public long getAvailable() throws IOException { long remaining = getCapacity() - getDfsUsed() - reservedForReplicas.get(); ... public long getNonDfsUsed() throws IOException { long nonDFSUsed = getCapacity() - getDfsUsed() - getAvailable() - reservedForReplicas.get();
- Can you add a targeted unit test for the above calculation? A mock-based test would be ideal.
- If the DN does not report nonDfsUsed, the NN should initialize it using the older calculation. Else the NN will report nonDfsUsed as zero for older DNs e.g. during upgrade. The fix can be done in PBHelperClient#convert(DatanodeInfoProto).
- We can expose nonDfsUsed via StorageTypeStats and DatanodeStatistics. Okay to do in a separate Jira.
- Also we can expose reservedForReplicas in a separate Jira. Previously this space was accounted for in nonDfsUsed but now it will not be accounted for anywhere.
- Unrelated - we should replace DatanodeInfo constructors with a builder pattern in a separate Jira.
The calculation in FsVolumeImpl#getNonDfsUsed looks wrong. Won't it always be zero?
Do you mean, nonDfsUsed will be zero? from the logs and tests, nonDFSUsage, is giving not zero.
From the earlier table, Brahma posted, Jenkins machine had 2887306715136 bytes of non-dfs usage out of 23318276997120 capacity, which seems reasonable.
The correct calculation should replace getAvailable() with actual volume free space. Something like Files.getFileStore(currentDir.toPath()).getUnallocatedSpace() perhaps.
IMO, This is also good point. Though earlier calculation was not entirely wrong, which basically calculates the nonDfsUsed by subtracting available space and dfsUsed from capacity. Available space is based on File.getUsableSpace() api, which according to javadoc, usable by this JVM not of entire partition.
Even though, I dont have any objection to use, Files.getFileStore(currentDir.toPath()).getUnallocatedSpace(), how about using currentDir.getFreeSpace()? Do you find any difference between them?
Updated calculation might look like this
public long getNonDfsUsed() throws IOException { long totalFreeSpace = currentDir.getFreeSpace(); return getCapacity() - getDfsUsed() - totalFreeSpace; }
Is this looks okay Arpit Agarwal ?
Hi Vinayakumar B, yes looks like it will be zero unless the remaining > available check is triggered in #getAvailable.
Even though, I dont have any objection to use, Files.getFileStore(currentDir.toPath()).getUnallocatedSpace(), how about using currentDir.getFreeSpace()? Do you find any difference between them?
That makes sense. Your code snippet LGTM.
Thanks you guys.. soon will update the patch based your comments..
Uploaded the patch..Kindly review..
Raised separate jira's for above three improvements (
HDFS-9480, HDFS-9481 and HDFS-9482).And uploaded the patch to address Vinayakumar B and Arpit Agarwal comments,kindly review..
Thanks for the further reviews. I'm catching up on patch v005 now.
-).
- The latest getNonDfsUsed does not include reservedForReplicas. I think it should, since the reservedForReplicas amount is effectively in use by HDFS.
- I think we should cap the returned value to 0 as a matter of defensive coding against negative values. There could be a possibility of race conditions in between pulling the individual data items, resulting in an unexpected negative total.).
I agree that, to be in symmetry with pre
HDFS-5215 code, we can use File#getUsableSpace, But since we are trying to calculate entire non-dfs usage of the partition/disk, File#getFreeSpace is required. Both might result in same values, unless some quota set for the user.
Hi Arpit Agarwal, what you think?
Thanks for the updated patch Brahma Reddy Battula.
3. I think we should cap the returned value to 0 as a matter of defensive coding against negative values.
Hi Chris Nauroth, this is a good idea.
2. The latest getNonDfsUsed does not include reservedForReplicas. I think it should, since the reservedForReplicas amount is effectively in use by HDFS.
Brahma changed this at my suggestion. Exposing reserved bytes through nonDfsUsed was inadvertent side effect of
HDFS-6898. I see Brahma filed HDFS-9481 to expose reserved bytes as a separate counter which should present a clearer picture to administrators. What do you think?
I think we should stick with File#getUsableSpace here
I looked at the JDK code to find the difference between File#getUsableSpace and File#getFreeSpace.
So it comes down to the difference between f_bavail and f_b */
f_bavail does not include some system-reserved partition space. The consequence of using f_bavail is that non-DFS used will include this space which is 5% of the volume size on ext2fs and successors, because File#getTotalSpace counts everything.
This may be confusing to administrators.
Brahma changed this at my suggestion. Exposing reserved bytes through nonDfsUsed was inadvertent side effect of
HDFS-6898.
Sorry, I missed that earlier comment. I understand the rationale now, so I'll withdraw my comment about changing it.
Regarding File#getUsableSpace vs. File#getFreeSpace, I've been approaching this as a regression introduced by
HDFS-5215, with the goal of restoring the pre- HDFS-5215 behavior as closely as possible. Before HDFS-5215, non-DFS used was based on File#getUsableSpace, indirectly because of use of getAvailable in the calculation. This meant that "free but unusable" space would have counted towards non-DFS used.
However, that would then lead me to expect seeing a non-zero non-DFS used for the typical 5% reserved for privileged users. In practice, I haven't seen that happen though. I'm not sure why not.
I tried digging through revision history for past decisions. The use of File#getUsableSpace traces back to
HADOOP-5958, when the code switched from forking to df to using then-new JDK 1.6 APIs. There is a question posted about which method to use, but no specific discussion about why File#getUsableSpace was chosen.
I don't think switching to File#getFreeSpace is necessarily wrong, just different from the pre-
HDFS-5215 calculation, which might cause some surprises.
I wonder how these various methods react with pooled storage....
I don't think switching to File#getFreeSpace is necessarily wrong, just different from the pre-
HDFS-5215calculation, which might cause some surprises.
Yes, its surprising.
Difference in HDFS user about that ~5% space,
before patch --> It was taken as already used by someone (non-dfs) because its not usable by HDFS.
after patch --> It will display actual usage of someone (non-dfs) even though its not usable.
Only matter is, value of metric. Which doesnt affect HDFS functionality anyway.
But assumption in calculattion in tests capacityUsed + capacityRemaining + capacityUsedNonDFS == capacityTotal might need to change, as capacityRemaining doesnt include, that ~5%.
From the above Test Failure of TestNameNodeMetrics, below values have got
Now we have two options to go ahead with the patch.
- Update the tests with assumption of extra ~5-6% space for privileged users
- fallback to File.getUsablespace()
Which one do you prefer Chris Nauroth,Arpit Agarwal..?
btw, Allen Wittenauer, is
YETUS-170 included in recent precommit builds? when I checked for above failure, it was not there, so mvn install failed due to wrong order.
Ping Chris Nauroth/Arpit Agarwal/Vinayakumar B once again..
Ok.will wait till Arpit Agarwal give his thought.
Sorry for the delay in responding, I am out this week. I just did some quick testing with a single DN using a 40GB ext4 partition.
With Brahma's v005 patch modified to use File#getUsableSpace non-DFS usage is reported as 2GB, i.e. ~5%. The actual disk usage was 49MB.
$: 2215555072 (2.06 GB) <<<< DFS Remaining: 39925968896 (37.18 GB) DFS Used%: 0.00% DFS Remaining%: 94.74% $ df -h /mnt/sdb/ Filesystem Size Used Avail Use% Mounted on /dev/sdb 40G 49M 38G 1% /mnt/sdb <<<<
With File#getFreeSpace i.e. the v005 patch, the non-DFS used is more accurate.
$: 51302400 (48.93 MB)
I also checked the current behavior in trunk (no patch). It is already broken, counting the system-reserved space towards non-DFS used.
$ bin/hdfs dfsadmin -report ... Name: 127.0.0.1:50010 (localhost) Hostname: mint0 Decommission Status : Normal Configured Capacity: 42141548544 (39.25 GB) DFS Used: 24576 (24 KB) Non DFS Used: 2215555072 (2.06 GB)
I think File#getFreeSpace is the correct choice. However modifying Brahma's patch use File#getUsableSpace would not introduce a regression wrt what's in trunk already so it's fine to change it to address Chris's concern. I'll file a separate Jira to discuss fixing this part.
I also edited the Jira title to mention "DFS reserved space", to distinguish it from system-reserved space.
Arpit Agarwal updated previous patch(004) as per Chris comments and added check for -ve values..
I'll file a separate Jira to discuss fixing this part.
will discuss further in seperate jira.
I took patch v006 for a more thorough test run. Unfortunately, I'm still seeing the bug that was introduced by
HDFS-5215. Even though non-DFS used is now calculated explicitly by the DataNode and sent in a dedicated RPC field, it's still using an incorrect calculation.
To help illustrate the problem better, I'd like to walk through the math for calculating non-DFS used, both before
HDFS-5215 and after HDFS-5215. Here is a bit of pseudo-code, prefixed with line numbers.
1: nonDfsUsed = capacity - dfsUsed - available 2: = (File#getTotalSpace - dfs.datanode.du.reserved) - dfsUsed - available 3: = (File#getTotalSpace - dfs.datanode.du.reserved) - dfsUsed - File#getUsableSpace 4: = File#getTotalSpace - dfs.datanode.du.reserved - dfsUsed - File#getUsableSpace
1: nonDfsUsed = capacity - dfsUsed - available 2: = (File#getTotalSpace - dfs.datanode.du.reserved) - dfsUsed - available 3: = (File#getTotalSpace - dfs.datanode.du.reserved) - dfsUsed - (File#getUsableSpace - dfs.datanode.du.reserved) 4: = File#getTotalSpace - dfs.datanode.du.reserved - dfsUsed - File#getUsableSpace + dfs.datanode.du.reserved 5: = File#getTotalSpace - dfsUsed - File#getUsableSpace
The most important point to note is the difference in line 3 of the expansions. After
HDFS-5215, the definition of available removes dfs.datanode.du.reserved. However, the definition of capacity already removed dfs.datanode.du.reserved. Carrying out the expansion further in lines 4 and 5, we see that the 2 occurrences of dfs.datanode.du.reserved cancel each other out. That means implicitly that nonDfsUsed now includes (instead of excludes) dfs.datanode.du.reserved.
Patch v006 still has the same fundamental problem in the logic, because FsVolumeImpl#getNonDfsUsed still reuses the implementation of FsVolumeImpl#getAvailable, which in turn removes dfs.datanode.du.reserved.
I think FsVolumeImpl#getNonDfsUsed essentially needs to go back to the old pre-
HDFS-5215 calculation of remaining instead of calling FsVolumeImpl#getAvailable.
Thanks Chris Nauroth for the explanation.
Lets go through one simple example.
Lets consider following
1. Disk Capacity - 10GB – File#getTotalSpace
2. DFS reserved - 1GB – dfs.datanode.du.reserved
3. DFS Usage - 2GB – dfsUsed
4. Usage by other files - 3GB – Actual non-dfsusage.
Assuming, System reserved ( which is ~5%) as 0 for this example.
total disk used is 5GB = 2GB by dfs files + 3GB by non-dfs files.
File.getUsableSpace() returns 5GB.
Lets substitute this values in derived expressions.
Before
HDFS-5215
nonDfsUsage=File#getTotalSpace - dfs.datanode.du.reserved - dfsUsed - File#getUsableSpace nonDfsUsage = 10G - 1G - 2G - 5G nonDfsUsage = 2G.
nonDfsUsage=2GB is not same as actual non-dfs usage, 3GB.
After
HDFS-5215 and as per patch.
nonDfsUsage=(File#getTotalSpace - dfs.datanode.du.reserved) - dfsUsed - (File#getUsableSpace - dfs.datanode.du.reserved) nonDfSUsage= (10G - 1G ) - 2G - (5G - 1G) nonDfSUsage = 9G - 2G - 4G nonDfsUsage = 3G
nonDfsUsage = 3G is same as expected actual usage. i.e. 3G
By seeing the above example,
I believe, post
HDFS-5215, calculation turns out to be the correct one.
dfs.datanode,du.reserved is expected to be the freespace, which should not be used by DFS. So its reasonable to subtract this in getAvailable(), but not while finding the non-dfs usage.
Do you agree Chris Nauroth?
Meanwhile, Brahma Reddy Battula, forgot to update the test TestFsVolumeList.testNonDfsUsedMetricForVolume?
Vinayakumar B thanks for pointing..Corrected and uploaded the patch.
Apart from that added null check in TestNameNodeMetrics#tearDown and fixed javadoc error in FsVolumeImpl#getDataset which are not related this jira.
I believe, post
HDFS-5215, calculation turns out to be the correct one.
I disagree, because the post-
HDFS-5215 calculation has broken previously established operations workflows.
Non-DFS usage is "space unexpectedly consumed on data volumes by things that are not HDFS". As a cluster administrator, I would monitor the non-DFS usage value. If a node consistently showed a non-zero non-DFS usage, then that would signal me to login to the box, figure out where the space was consumed, free it up, and then address root cause (probably a rogue process running on the wrong box or misconfigured to write to the wrong volume). It's important to fix this, because high non-DFS usage reduces disk capacity that had been planned for HDFS.
After
HDFS-5215, this workflow no longer works. The monitoring will show false positives because of inclusion of dfs.datanode.du.reserved. An administrator would need to use additional checks, or simply disable this monitoring due to the noise.
dfs.datanode.du.reserved is a special case on top of what I described above. Setting a non-zero".
Bottom line: I have seen the post-
HDFS-5215 calculation cause confusion for administrators who had built a workflow around the old calculation.".
So you mean, when 1GB is configured as reserved, 'Non-DFS' usage metric should show 2GB, even though actual usage by files other than HDFS is 3GB.?
I was thinking 'NonDfsUsage' should show actual non-dfs usage. Not only unexpected part of it. So if actual non-dfs usage is within this reserved limit, metric should show 0. right?
In that case, wouldn't it be better to rename the 'NonDfsUsage' metric to 'UnexpectedNonDfsUsage' to make it more clear? Or mention somewhere to clear confusion in people like me.
So if actual non-dfs usage is within this reserved limit, metric should show 0. right?
Yes, that's my understanding, and that's the behavior pre-
HDFS-5215.
In that case, wouldn't it be better to rename the 'NonDfsUsage' metric to 'UnexpectedNonDfsUsage' to make it more clear? Or mention somewhere to clear confusion in people like me.
I don' t think it could be renamed easily due to backwards-compatibility, but I do think we could update Metrics.md.
Brahma, thanks for your patience as we work through the math. It may be useful to describe your proposed derivation as a Jira comment before you post another patch.
Chris Nauroth I think you are right in conclusion but there is a misstep in the equations in this comment. reserved should cancel out and it should not factor in the final computation.
The problem with the v005 patch we missed earlier is that getCapacity() subtracts reserved space. We should use the raw capacity.
One way to fix it is:
public long getNonDfsUsed() throws IOException { long totalFreeSpace = currentDir.getFreeSpace(); long nonDfsUsed = getCapacity() + reserved - getDfsUsed() - totalFreeSpace; return (nonDfsUsed >= 0) ? nonDfsUsed : 0; }
Then the derivation becomes:
1: non-DFS used = getCapacity() + reserved - getDfsUsed() - totalFreeSpace 2: = usage.getCapacity() - reserved + reserved - getDfsUsed() - totalFreeSpace 3: = usage.getCapacity() - getDfsUsed() - totalFreeSpace 4: = File#getTotalSpace - getDfsUsed() - File#getFreeSpace
Hope that makes sense.
Arpit Agarwal, thanks for jumping in for calculation.
I think considering We use File#getUsableSpace instead of File#getFreeSpace, current code after
HDFS-5215 also comes to same equation as mentioned by Arpit Agarwal, brahma's patch doesn't change anything in this, except subtracting 'reservedForReplicas' also.
But, I think what Chris Nauroth expects is,
Since reserved is hidden from the HDFS in getCapacity() itself, we can think that's already used for nonDfs and subtract it from actual ondisk nonDfsUsage, showing only HDFS visible nonDfsUsage. nonDfsUsage metric will be positive, only if the ondisk nonDfsUsage crosses beyond reserved, and it shows only excess usage beyond reserved.
i.e. nonDfsUsage will be 2GB instead of 3GB in my earlier example, where 1GB was reserved.
So final equation would be
nonDfsUsage=File#getTotalSpace - dfsUsed - File#getUsableSpace - reserved
Code would look like this.
public long getNonDfsUsed() throws IOException { long nonDfsUsed = getCapacity() - getDfsUsed() - getAvailable() - reserved - getReservedForReplicas(); return (nonDfsUsed > 0) ? nonDfsUsed : 0; }
Am I right Chris Nauroth?
Thanks everyone for sticking with this. This has turned out to be much trickier than I anticipated when I filed the issue. I'd like to summarize current status.
Arpit and I are in agreement about my analysis of how the calculation changed after
HDFS-5215. However, we are not yet in agreement about which calculation is truly correct. I believe the pre- HDFS-5215 calculation (subtracting dfs.datanode.du.reserved) is correct, because it allowed me to monitor for unexpected non-zero non-DFS usage and react. Since this was an established operations workflow (at least for me), I argue that we have a responsibility to restore that behavior. Arpit believes that it's correct to cancel out dfs.datanode.du.reserved, because then non-DFS used would report space used for non-HDFS purposes more accurately. Essentially, it's a question of whether this metric means "Raw Non-DFS Used" or "Unplanned Non-DFS Used".
We also discovered an interesting side issue about File#getUsableSpace vs. File#getFreeSpace. Pre-
HDFS-5215, it could be considered a bug that we did not account for system reserved space. Interestingly, it seems in our testing that ext holds back 5% by default, but xfs does not.
I pushed pretty hard for restoring the pre-
HDFS-5215 behavior in my earlier comments, but I'm just one voice. I suggest that we leave this issue open for a while for others to comment. I could be swayed if others think I'm approaching this incorrectly. Meanwhile, Brahma Reddy Battula, would you please hold off on posting more patches? Let's wait for the discussion to settle a little more first. Thanks for your patience.
I'd really like for someone to attach a simple test case so that we can run and see the differences on different file systems. In particular, every time we change this code, we only ever test on one or two Linux file systems and end up causing really oddball behaviors on others, especially those that don't use the traditional disk->partition->filesystem layout (e.g., ZFS).
tl; dr - We need agreement on the definition of non-DFS used.
The pre
HDFS-5215 calculation had two bugs.
- It incorrectly subtracted reserved space from the non-DFS used. (net negative). Chris suggests this is not really an issue as non-DFS used should be shown as zero unless it exceeds the DFS reserved value.
- It used File#getUsableSpace to calculate the volume free space instead of File#getFreeSpace. (net positive)
The net effect was that non-DFS used was displayed as zero unless the actual non-DFS used exceeded DFS reserved - system reserved.
HDFS-5215 fixed the first issue and the value that is now erroneously counted towards non-DFS used is in fact the system reserved 5%.
Also attached a trivial utility that dumps the free/available space.
From a mostly empty 40GB Ext4 partition:
$ java GetFree /mnt/sdb/hadoop/ Free space : 42,090,229,760 Available space : 39,925,968,896
Same partition reformatted as XFS:
Free space : 42,894,983,168 Available space : 42,894,983,168
So Ext derivatives hold back 5% free space while XFS does not.
Edit: Removed statement about Jira description being inaccurate since it too depends on how we define non-DFS used.
Hi Uma Maheswara Rao G/Yi Liu/Tsz Wo Nicholas Sze/Haohui Mai,
Do You have any opinions to here?
Ping.
Any update on this guys?
Ping Chris Nauroth.
I suggest that we leave this issue open for a while for others to comment. I could be swayed if others think I'm approaching this incorrectly
Chris Nauroth/Arpit Agarwal/Vinayakumar B can we discuss in mailing list Or do you want specific people to comment here.. Please let me know..
Hi Brahma Reddy Battula, I am sorry this patch is stuck after all the effort you put into it.
There is a disagreement on the definition of non-DFS used space. Quoting Chris Nauroth:
Essentially, it's a question of whether this metric means "Raw Non-DFS Used" or "Unplanned Non-DFS Used".
I don't see any harm in starting a discussion on hdfs-dev. I will think about this some more.
it's a question of whether this metric means "Raw Non-DFS Used" or "Unplanned Non-DFS Used".
I prefer (I'm +0 for) the following calculation, which is straightforward for me.
Non-DFS used = f.getTotalSpace() - f.getFreeSpace() - getDfsUsed()
When we reach an agreement, it should be well-documented.
I spent a few hours looking at this today. I now think that the current logic in FsVolumeImpl#getAvailable is too pessimistic and the impact of bug may be more severe than reported.
public long getAvailable() throws IOException { long remaining = getCapacity() - getDfsUsed() - reservedForReplicas.get(); long available = usage.getAvailable() - reserved - reservedForReplicas.get(); if (remaining > available) { remaining = available; } return (remaining > 0) ? remaining : 0; }
Specifically {{available = usage.getAvailable() - reserved ... }} can account for the non-DFS usage twice. e.g. say 10GB is reserved and YARN is using all of that 10GB. usage.getAvailable() has already accounted for that 10GB and further subtracting it makes us underestimate available.
Instead the calculation should only subtract the unused portion of non-DFS used. What do you guys think?
Instead the calculation should only subtract the unused portion of non-DFS used. What do you guys think?
I think below code change suggested by brahma in the mailing list does exactly what you suggesting. Right?
public long getAvailable() throws IOException { long remaining = getCapacity() - getDfsUsed() - reservedForReplicas.get(); - long available = usage.getAvailable() - reserved + long available = usage.getAvailable() - getRemainingReserved() - reservedForReplicas.get(); if (remaining > available) { remaining = available; @@ -391,6 +391,31 @@ public long getAvailable() throws IOException { return (remaining > 0) ? remaining : 0; } + private long getActualNonDfsUsed() throws IOException { + return usage.getUsed() - getDfsUsed(); + } + + private long getRemainingReserved() throws IOException { + long actualNonDfsUsed = getActualNonDfsUsed(); + if (actualNonDfsUsed < reserved) { + return reserved - actualNonDfsUsed; + } + return 0L; + } + + /** + * Unplanned Non-DFS usage, i.e. Extra usage beyond reserved. + * @return + * @throws IOException + */ + public long getNonDfsUsed() throws IOException { + long actualNonDfsUsed = getActualNonDfsUsed(); + if (actualNonDfsUsed < reserved) { + return 0L; + } + return actualNonDfsUsed - reserved; + } +
Thanks Vinay. I see Tsz Wo Nicholas Sze already brought this up on the mailing list thread. Brahma's proposed update looks good to me.
Will this delta be applied on top of the v7 patch?
Cool.. I will update v7 patch. thanks vinay and arpit..
Uploaded the patch.. Arpit Agarwal and Vinayakumar B kindly review.. and sorry for long delay.
Uploaded the patch to fix checkstyle issues..Testcases are passing locally..Seems to be there is a difference in jenkins and local run...
Hi Brahma Reddy Battula, thanks for the updated patch. I will try to review this next week.
2.7.3 is under release process, changing target-version to 2.7.4.
Uploaded the patch to fix the checkstyle issue and testcases fix. As ext filesystems will reserve 5% space which is not considered in non-dfs,hence TestNamenodeCapacityReport and TestNameNodeMetrics are failing..
Arpit Agarwal can you please look into latest patch..
Thanks for sticking with this difficult fix Brahma Reddy Battula. The patch looks good to me (I am still reviewing unit tests). Nitpick - convert(DatanodeInfoProto di) can use the new DataNodeInfo constructor.
Vinayakumar B, Chris Nauroth, Tsz Wo Nicholas Sze, do you have any comments on the latest patch.
Arpit Agarwal thanks for review.. will update patch once your review completed..
The tests also look fine to me. Thanks Brahma Reddy Battula. We should hold off committing for until next week in case Chris or Vinayakumar want to take a look at the new patch since they reviewed earlier revisions.
It'd be great to have a targeted unit test for PBHelperClient#convert(DatanodeInfoProto di) that verifies deserialization of protobufs with and without the new non-dfs used field.
Brahma Reddy Battula, Arpit Agarwal and Vinayakumar B, thank you for your dedication working through this issue. I am +1 to proceed with the patch after addressing Arpit's last round of feedback.
Attaching the updated patch with new test.
Nitpick - convert(DatanodeInfoProto di) can use the new DataNodeInfo constructor
This constructor was used intentionally as new constructor was expecting all fields to be specified, instead of just DatanodeID
Please review.
+1 lgtm. The javac warning is due to a deprecated function which we must invoke to handle wire compatibility. The checkstyle issue was also not introduced by this patch.
Thanks again Brahma Reddy Battula for persistently driving this issue to closure.
+1 for the latest changes.
Thanks Brahma Reddy Battula, Arpit Agarwal, Chris Nauroth for the co-operations.
Pushed to 2.8.0. Hit numerous conflicts cherry-picking to branch-2.7 that I didn't look into. 2.7.4 will likely need an updated patch.
SUCCESS: Integrated in Jenkins build Hadoop-trunk-Commit #10401 (See)
HDFS-9038. DFS reserved space is erroneously counted towards non-DFS (arp: rev 5f23abfa30ea29a5474513c463b4d462c0e824ee)
- (edit) hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestBlockManager.java
- (edit) hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsVolumeImpl/test/java/org/apache/hadoop/hdfs/server/namenode/TestDeadDatanode.java
- (edit) hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/metrics/TestNameNodeMetrics.java
- (edit) hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeStorageInfo/blockmanagement/DatanodeStats.java
- (edit) hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/BlockManagerTestUtil.java
- (edit) hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/TestFsVolumeList.java
- (edit) hadoop-hdfs-project/hadoop-hdfs-client/src/main/proto/hdfs.proto
- (edit) hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocol/DatanodeInfo.java
- (edit) hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/protocolPB/TestPBHelper.java
- (edit) hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/NNThroughputBenchmark.java
- (edit) hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/blockmanagement/DatanodeDescriptor/namenode/TestNamenodeCapacityReport.java
- (edit) hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/protocolPB/PBHelperClient.java
- (edit) hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/server/protocol/StorageReport.java
Gentle reminder, please set the appropriate 3.0.0 fix version when committing to trunk. Thanks!
Uploading the branch-2.7 patch..And thanks for Arpit,Vinay and Chris for helping closure of this issue .Please review branch-2.7 patch.
Reopening issue to run jenkins on branch-2.7 patch...
checkstyle : can be ignored ,those are related to file length,method parameters (>7) and hiddenfield.
javac: which is not introduced by this patch.
whitespace : Seems to be some problem with report..?
asflicense : Not related to this patch
unittest failures : Not related to this patch
Arpit Agarwal can please review branch-2.7 patch..?
+1 for the branch-2.7 patch also. Thanks Brahma.
Pushed to branch-2.7.
I'd appreciate if some of the participants on
HDFS-5215could chime in with their opinions. cc Brahma Reddy Battula, Uma Maheswara Rao G, Yongjun Zhang and Kihwal Lee. Thank you. | https://issues.apache.org/jira/browse/HDFS-9038 | CC-MAIN-2017-13 | refinedweb | 5,155 | 51.44 |
Created on 2018-12-27 16:18 by hyu, last changed 2019-01-09 06:47 by serhiy.storchaka. This issue is now closed.
>python
Fatal Python error: initfsencoding: unable to load the file system codec
zipimport.ZipImportError: can't find module 'encodings'
There are two vcruntime140.dll with no binary diff.
Date Time Attr Size Compressed Name
------------------- ----- -------- ------------ ----------------
2018-12-10 22:06:34 ..... 80128 45532 vcruntime140.dll
...
2018-12-10 22:06:34 ..... 80128 45532 vcruntime140.dll
Repeated downloads. Checked both versions:
Searched and read release and doc. Checked bugs since yesterday.
Have you tried a proper install as well? Could you do that to rule out any problem on your machine?
Are you repackaging anything as part of your app, or are you just testing the package first and getting this error?
It looks like you're running from the directory you extracted to. Is there anything else in that directory or just the Python files?
When you say there are two vcruntime140.dll, you mean one in each package and they're the same? That might be a problem, but it wouldn't show up like this, so I don't think it's yours. I'm not in A position to check the files right now but I'll get to it later
Okay, this looks like a zipimport issue. When I extract the "python37.zip" file containing the stdlib and reference the directory it works fine. But no matter what I do to the ZIP I can't get it to run.
It seems that zipimport either can't import .pyc files without a matching .py, or it can't import packages marked with __init__.pyc (I haven't gone deep enough, but adding encodings/__init__.py got me further).
This is a regression from 3.7.1.
Things to do:
* fix the regression (Serhiy?)
* add a regression test
* add a ".pyc-only stdlib in ZIP" test (I'll do this)
* remove the double vcruntime in ZIP issue (unrelated, so I'll just fix it)
Repeated on two clean install Windows hosts.
No (re)packaging, download and run/start python.
Repeated with versions 3.7.2, 3.7.1, and 3.6.8:
Windows Explorer properly extracted: \tmp\py372, \tmp\py371, \tmp\py368.
Python 3.6.8 and 3.7.1 properly started, executed import sys; sys.exit()
Python 3.7.2 failed to start. Please suggest proper commands if you claim these are not proper Windows commands.
Worked extra to show both 3.6 and 3.7 regressions. If you want to claim copying 3.6.8 vcruntime140.dll to 3.7.1 as (re)packaging, then ignore v3.7.1:260ec2c36a below.
Windows Explorer shows and 7-zip lists two vcruntime140.dll in 3.7.2. Please ignore 7-zip if you claim that is not proper or (re)package tool and I will attach Windows Explorer screen shot.
Microsoft Windows [Version 10.0.17763.195]
C:\>\tmp\py368\python
Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
>>> import sys; sys.exit()
C:\>\tmp\py372\python
Fatal Python error: initfsencoding: unable to load the file system codec
zipimport.ZipImportError: can't find module 'encodings'
Current thread 0x00002614 (most recent call first):
C:\>copy \tmp\py368\vcruntime140.dll \tmp\py371\
1 file(s) copied.
C:\>\tmp\py371\python
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)] on win32
>>> import sys; sys.exit()
C:\>
Thanks for the extra info, and for confirming that 3.6.8 isn't affected (I hadn't tried that you, so you saved me some work :) )
This is definitely a new zipimport regression in 3.7.2. Thanks for the report.
New changeset 59c2aa25ffc864bf11bf3b3973828f00e268a992 by Miss Islington (bot) (Steve Dower) in branch 'master':
bpo-35596: Fix vcruntime140.dll being added to embeddable distro multiple times. (GH-11329)
New changeset bbf695441af9def8a121ff3e245415d9fc0bab9a by Miss Islington (bot) in branch '3.7':
bpo-35596: Fix vcruntime140.dll being added to embeddable distro multiple times. (GH-11329)
There were no changes in zipimport between 3.7.1 and 3.7.2, and there were just few looking unrelated changes in the import machinery. Maybe this is caused by some changes in the interpreter initialization code?
Reviewing the diff at the only item I've spotted that seems like it could even plausibly be related is the tweak at
(Click the Files tab to get your browser to jump to the anchor in the second link)
That's a change to the function that emits the "Fatal Python error: initfsencoding: unable to load the file system codec" message.
That change means that embedding applications could potentially be hitting the codec name resolution at with the filesystem encoding set as "ascii", rather than handling that case through the "get_locale_encoding()" branch, which does the initial codec name lookup with the filesystem encoding still set to NULL (and hence falling back to the locale encoding as the default).
However, the only way that new branch could trigger is if check_force_ascii() (at ) is returning 1 for some reason, which we only expect it to do on some misbehaving BSD OSes, not on Windows:
None of the code you linked is defined on Windows at all, so it can't be that.
Are any stat checks done when there's only a .pyc to import? Could it be deciding that the .pyc is out of date and then failing to find source?
I took a closer look at the diff since 3.7.1, and I'm not seeing anything either. I suspect we need to step through zipimport/importlib and figure out exactly where it rejects the .pyc files in the zip.
Ah, you're right - I missed that the ForceASCII stuff was on the non-Windows side of an ifdef so it's literally impossible for that change to affect Windows, not just highly unlikely.
It would be interesting to compare the output of `python -vv` between the working case and the non-working case, as the second level of verbosity will print out all the different candidates the two versions are considering, and which ones they're accepting. For example, here's my Linux system Python up to the point where it finishes importing the UTF-8 codec:
========================
$ python3 -vv
import _frozen_importlib # frozen
import _imp # builtin
import '_thread' # <class '_frozen_importlib.BuiltinImporter'>
import '_warnings' # <class '_frozen_importlib.BuiltinImporter'>
import '_weakref' # <class '_frozen_importlib.BuiltinImporter'>
# installing zipimport hook
import 'zipimport' # <class '_frozen_importlib.BuiltinImporter'>
# installed zipimport hook
import '_frozen_importlib_external' # <class '_frozen_importlib.FrozenImporter'>
import '_io' # <class '_frozen_importlib.BuiltinImporter'>
import 'marshal' # <class '_frozen_importlib.BuiltinImporter'>
import 'posix' # <class '_frozen_importlib.BuiltinImporter'>
import _thread # previously loaded ('_thread')
import '_thread' # <class '_frozen_importlib.BuiltinImporter'>
import _weakref # previously loaded ('_weakref')
import '_weakref' # <class '_frozen_importlib.BuiltinImporter'>
# /usr/lib64/python3.7/encodings/__pycache__/__init__.cpython-37.pyc matches /usr/lib64/python3.7/encodings/__init__.py
# code object from '/usr/lib64/python3.7/encodings/__pycache__/__init__.cpython-37.pyc'
# trying /usr/lib64/python3.7/codecs.cpython-37m-x86_64-linux-gnu.so
# trying /usr/lib64/python3.7/codecs.abi3.so
# trying /usr/lib64/python3.7/codecs.so
# trying /usr/lib64/python3.7/codecs.py
# /usr/lib64/python3.7/__pycache__/codecs.cpython-37.pyc matches /usr/lib64/python3.7/codecs.py
# code object from '/usr/lib64/python3.7/__pycache__/codecs.cpython-37.pyc'
import '_codecs' # <class '_frozen_importlib.BuiltinImporter'>
import 'codecs' # <_frozen_importlib_external.SourceFileLoader object at 0x7f0ea616eb70>
# trying /usr/lib64/python3.7/encodings/aliases.cpython-37m-x86_64-linux-gnu.so
# trying /usr/lib64/python3.7/encodings/aliases.abi3.so
# trying /usr/lib64/python3.7/encodings/aliases.so
# trying /usr/lib64/python3.7/encodings/aliases.py
# /usr/lib64/python3.7/encodings/__pycache__/aliases.cpython-37.pyc matches /usr/lib64/python3.7/encodings/aliases.py
# code object from '/usr/lib64/python3.7/encodings/__pycache__/aliases.cpython-37.pyc'
import 'encodings.aliases' # <_frozen_importlib_external.SourceFileLoader object at 0x7f0ea6183550>
import 'encodings' # <_frozen_importlib_external.SourceFileLoader object at 0x7f0ea616e5c0>
# trying /usr/lib64/python3.7/encodings/utf_8.cpython-37m-x86_64-linux-gnu.so
# trying /usr/lib64/python3.7/encodings/utf_8.abi3.so
# trying /usr/lib64/python3.7/encodings/utf_8.so
# trying /usr/lib64/python3.7/encodings/utf_8.py
# /usr/lib64/python3.7/encodings/__pycache__/utf_8.cpython-37.pyc matches /usr/lib64/python3.7/encodings/utf_8.py
# code object from '/usr/lib64/python3.7/encodings/__pycache__/utf_8.cpython-37.pyc'
import 'encodings.utf_8' # <_frozen_importlib_external.SourceFileLoader object at 0x7f0ea6191278>
========================
I have tried zipping the stdlib myself form normal version's "Python37\Lib" with all files were end with ".py"(without "site-packages" of course). And then everything work fine. Maybe the loader only reject ".pyc" file from zip load?
Yes, we've established that zipimport is rejecting .pyc files now, but we need to dig through it to figure out why. I haven't had time yet, but if someone else can then don't wait for me.
Looks like zipimport in 3.7 always rejected CHECKED_HASH pycs, while in 3.8 it always accepts them (or runs it through a validation process that passes them when the source file doesn't exist - I only confirmed by testing a build, not by walking through the new sources).
Rather than changing the old zipimport now, it's more correct to fix the embeddable ZIP build to specify UNCHECKED_HASH.
And I assume now that the reason it broke in 3.7.2 is because the pyc mode for the embeddable distro changed. Which means the right place for tests is in a separate build that uses properly laid out Python rather than testing in the source tree (like what I have in the windows-appx-tests.yml file and Tools/msi/testrelease.bat script, but apparently also for the embeddable distro).
New changeset 872bd2b57ce8e4ea7a54acb3934222c0e4e7276b by Steve Dower in branch 'master':
bpo-35596: Use unchecked PYCs for the embeddable distro to avoid zipimport restrictions (GH-11465)
New changeset 69f64b67e43c65c2178c865fd1be80ed07f02d3c by Miss Islington (bot) in branch '3.7':
bpo-35596: Use unchecked PYCs for the embeddable distro to avoid zipimport restrictions (GH-11465)
This is now resolved, and only through modifying the build scripts. Which means I can take the existing build and republish a fixed embeddable package without needing a new release.
Unless Ned would prefer a complete release?
It seems like this need not trigger a complete new release and, ATM, I'm not aware of any other showstopper problems that would otherwise trigger an early 3.7.3. One question would be how and where to document this change in the build artificat. Suggestions, Steve?
> This is now resolved, and only through modifying the build scripts. Which means I can take the existing build and republish a fixed embeddable package without needing a new release.
Since Python itself doesn't make, I'm ok to not change the Python release. But for pratical issues, would it be possible to use a different *filename*? For example, Python website rely a lot on CDN caching. It can be surprising to have two files with the same name but different content.
CDN caching on python.org is not a problem; we know how to clear out the cache. But I also strongly dislike silent updates of released files so I agree that names should be changed if we do end up agreeing to replace one or more files.
I know how to purge the CDN cache, so that's not an issue. And there's no good reason to leave the old one up.
Perhaps we can just add a note to the download page and I'll post on a couple of lists? This is basically a product recall, and those are usually advertised at the point of sale.
I can add ".post1" to the version number in the file name, but I'd still want to take down the broken one. And anyone who's generating the download URL will get a broken link, which IMO is just as bad as a broken download when we could fix it.
I think we should change the name (post1 is fine), delete the original file, update the file name link in the release page () to use the new name, and add a sentence or two to the release page describing the change. If you could write up something for the page, I can add it and change the file name when ready.
It would be weird if building from sources will not give the same distribution as downloaded from official site. It would be not fair to alternate distributors.
I think this is a time to release 3.7.2.1. This would be not the first time of using the fourth number in the version.
> It would be weird if building from sources will not give the same distribution as downloaded from official site. It would be not fair to alternate distributors.
Yes, I agree with that in general but, as I understand it, the change here affects only how the Windows embeddable distribution is packaged. I don't think we expect alternate distributors to produce such distributions - or do we know of such cases? And, even if so, it's not a big deal for a third-party to pick up the change. There are parts of the PC and Mac source tree that really are intended only for building of python.org binary releases. If the changes affected the python executables or standard library files, that would be a very different matter. It is a trade-off; I just don't think that this is the type of change that needs to trigger a new release cycle and I don't want to go down the path of creating a new level of release. When was the last time we had a 3.x.y.z? I don't recall one.
Agreed. My plan is to just replace the precompiled ZIP file of the standard library in the embeddable package with one with PYCs missing the "check source" bit that the old zipimport rejects. It's as simple as a 1 line change in a supporting script in PC/layout (though the actual change I made is more significant to support other use cases).
The binary and library sources are so identical this doesn't even require a rebuild. And anyone building their own distro from source using this script will hit the issue and find this bug. The only reason I missed it was because I tested against master, not realising that the new zipimport changed behaviour here. Nobody else will be blindly releasing these packages with only tests against an incompatible versions the way we do (and now I have tests).
I've updated the files and sent Ned the info needed to confirm and update the download page.
Thanks, Steve. The download page for 3.7.2 has now been updated with the URLs for the modified embeddable files, the CDN caches updated, and the original embeddable download files and their GPG signature files are no longer accessible so references to the original URLs will result in hard failures. I considered updating the 3.7.2 blog announcement but decided against it as likely adding more confusion than it was worth. There just aren't that many users yet of the embeddable files.
> When was the last time we had a 3.x.y.z? I don't recall one.
My apologies, it seems my memory has tricked me. I thought there was on in the 3.3 branch, but it was just that the third number was bumped again just a month ago after a bugfix release. | https://bugs.python.org/issue35596 | CC-MAIN-2019-26 | refinedweb | 2,608 | 68.26 |
This is the third and final part of my article on exceptions. In this part we deal with:-
Dangers of exceptions
Standard Library exceptions
Guidelines.
Resource recovery is important in the face of errors. An acquired resource can easily be lost during stack unwinding unless it was acquired automatically (that is to say, not as a pointer). However, it is a common idiom in C++ to acquire resources by pointer.
To be exception safe, pointers, resource handles, important state variables (for example a "top of stack" if you're implementing a stack template class) need special attention. It's possible to provide that attention with specially written try(){…} catch() clauses. It is much easier to rely on C++'s constructor / destructor mechanism.
void f(const char *filename) { FILE *f = fopen(filename, "r"); try { // use f fclose(f); } catch (...) { fclose(f); throw; // rethrow the exception } }
In the above example, the resource (file) is acquired, then used. An exception may be thrown (not necessarily by the file specific code), so a handler is present to clean up the mess. This seems reasonable enough, but what happens if we have a lot of resources in one function? (critical sections, files, locks, events). It clearly gets too messy.
This is changing in the face of exceptions. Smart pointers are classes which acquire the resource pointer in the constructor, and safely release in the destructor. The pointer is accessed through an overloaded member access operator, or custom conversion.
class File_ptr { public: File_ptr(const char* name, const char *mode ) { fp = fopen(name, mode);} ~File_ptr() {fclose( fp); } operator FILE*(){return fp;} private: FILE *fp; // not implemented File_ptr( const File_ptr& ); File_ptr& operator=(const File_ptr& ); }
Now we use the atomic variable of class File_ptr where we would've used a pointer to FILE. In the case of an exception occurring before the File_ptr goes out of scope, stack unwinding takes care of the cleanup for you - you don't need special exception handlers for every resource.
For pointers created and destroyed by new and delete, STL provides the auto_ptr<> template. The resources can be allocated when the object is constructed (this is optional), the resources will be released when the object is deleted. (Note - consult your system documentation about the precise behaviour of auto_ptr<>).
The idiom of wrapping a raw pointer with an object to control its initialisation and release is called "resource acquisition is initialisation", and is covered on the QA Training Advanced C++ course, in Scott Meyers' "More Effective C++" (Item 9), and in Bjarne Stroustrup's "The C++ Programming Language" (14.4), where the phrase was coined.
Exceptions can be expensive to throw. Consider the difference between the following handlers:
Thing t; try { throw t; // 1 } catch (Thing x){ // 2 throw; } catch (Thing& x){ // 3 // whatever }
At point 1, a temporary copy of the local object is thrown, not the local object itself. The copy is necessary to extend the exception's lifetime until a handler has completed. The cost of this copy is one copy constructor.
The handler at point 2 catches by value; a copy is made of the thrown exception object. The cost of this is another copy constructor.
The handler at point 3 catches by reference; no copy is made.
Another reason not to catch by value is that of polymorphism. Consider this:
class A { /* .. */ }; class B : public A { /* .. */ }; void f() { try { throw B; } catch (A a) { // # throw a; // $ } }
At the point #, the exception object has been caught by value of type A (base class of the originally thrown type, B). At the point $, the exception is rethrown, except, the exception thrown now is of type A - we've lost our derived class information!
There is a good argument against throwing a pointer too. Should the handler delete the pointer? Clearly, catching by reference, or preferably const-reference is the best way of handling exceptions.
Destructors are called in three situations:
when the object goes out of scope or is deleted.
during the stack unwinding mechanism of exception handling.
by explicit call (rare).
Therefore, there may or may not be an exception active when a destructor is called. If another exception is thrown whilst an exception is already active, the program calls terminate(). This is not an acceptable outcome if you've decided to use exceptions to manage your programs (and exceptions have to be considered right through your code when you use them - no half measures).
There are two solutions to this situation:
use uncaught_exception() in the destructor to determine if an exception is active, and only throw if there isn't, or
never throw exceptions from destructors.
On the surface the first option may seem fine, but as Steve Clamage put it: "My question is why would it be good design to throw the exception only sometimes, and if you can sometimes get along without throwing it, why not always get along without throwing it?" - Steve Clamage, Sun Microsystems.
The only reasonable solution is never throw from destructors. This guideline is supported by all major commentators.
What? You mean they got constructors too? Well, if you've been paying attention so far, the intricacies of exceptions from constructors shouldn't be a problem to you.
The C++ Standard (15.2.2 [except.ctor]) says, "An object that is partially constructed or partially destroyed will have destructors executed for all of its fully constructed subobjects…".
If you've wrapped your resources with smart pointers, this shouldn't be a problem, right?
Exception handling (like all error-handling code) comes with costs. Programs will be slower and of a larger size when using exceptions; they have a lot more bookkeeping to do. Having try-blocks in your program may increase your code size and runtime cost by 5-10% (source: More Effective C++). To minimise this, avoid unnecessary try-blocks.
Exception specifications add a similar cost, but since we're not using those, that doesn't matter.
So how much of a hit do we take when we actually throw an exception? The best answer we can give is "a big one". Meyers suggests returning from a function by throwing an exception could cost up to three times what it does when returning normally. My own test with MS VC++ 5 showed a fourfold increase in run time.
This overhead will come down in time. In any case, for most programs it's more important to get the correct answer a bit slower, than to get the wrong answer fast. It is even conceivable that code with exception handling constructs could execute faster than old style error handling code, since a lot of if-else style constructs could be removed.
The standard C++ library defines a base class for the types of objects thrown as exceptions by C++ Standard library components in the header <exception>:
namespace std { class exception { public: exception() throw(); exception(const exception&) throw(); exception& operator=(const exception&) throw(); virtual ~exception() throw(); virtual const char* what() const throw(); }; }
The class bad_exception is also defined in <exception>. This exception is thrown when an exception specification has been compromised, but the exception specification allows exceptions of type bad_exception to be thrown. std::unexpected() performs the necessary remapping.
The following standard exceptions are defined in the header <stdexcept>:
logic_error domain_error invalid_argument length_error out_of_range
(the indented classes are publicly derived from logic_error).
runtime_error range_error overflow_error underflow_error
(the indented classes are publicly derived from runtime_error).
A logic_error is an error that is detectable in the logic of the code. A runtime_error is one that is not detected in the logic of the code.
catch by reference (or const reference) (8.2)
use the "resource acquisition is initialisation" idiom (8.1)
use exceptions only for exceptional circumstances, where other error handling techniques won't suffice
treat exceptions as another area of program design
make constructors & destructors exception safe using function try blocks (7.1)
The C++ Programming Language Third Edition Bjarne Stroustrup (Addison-Wesley, 1997)
More Effective C++ Scott Meyers (Addison-Wesley 1996)
The ISO/IEC C++ Language Standard (14882-1998) (ISO/IEC 1998)
Exception Handling: A False Sense of Security Tom Cargill (C++ Report, Volume 6, Number 9, Nov-Dec 1994)
Taligent's Guide to Programming Taligent (Addison-Wesley, 1995)
Counting Object in C++ (Sidebar: Placement new and placement delete) Scott Meyers (C/C++ Users Journal, April 1998) Downloadable from | https://accu.org/index.php/journals/505 | CC-MAIN-2020-16 | refinedweb | 1,385 | 54.12 |
Up to [cvs.NetBSD.org] / src / include
Request diff between arbitrary revisions
Default branch: MAIN
Current tag: netbsd-2-0-RELEASE
Revision 1.53.2.1 / (download) - annotate - [select for diffs], Fri Jul 2 18:13:45 2004 UTC (14 years, 10.53: +3 -3 lines
Diff to previous 1.53 (colored) next main 1.54 (colored)
Pull up revision 1.56 (requested by kleink in ticket #580): Tidy up the namespace: lint -> __lint__.
This form allows you to request diff's between any two revisions of a file. You may select a symbolic revision name using the selection box or you may type in a numeric name using the type-in text box. | http://cvsweb.netbsd.org/bsdweb.cgi/src/include/stdio.h?only_with_tag=netbsd-2-0-RELEASE | CC-MAIN-2019-22 | refinedweb | 114 | 68.87 |
Python Programming/Files< Python Programming
Contents
File I/OEdit
Read entire file:
inputFileText = open("testit.txt", "r").read() print(inputFileText)
In this case the "r" parameter means the file will be opened in read-only mode.
Read certain amount of bytes from a file:
inputFileText = open("testit.txt", :
>>> f=open("/proc/cpuinfo","r") >>>:
for line in open("testit.txt", .
Since Python 2.5, you can use with keyword to ensure the file handle is released as soon as possible and to make it exception-safe:
with open("input.txt") as file1: data = file1.read() # process the data
Or one line at a time:
with open("input.txt") as file1: for line in file1: print line
Related to the with keywords is Context Managers chapter.
Links:
- 7.5. The with statement, python.org
- PEP 343 -- The "with" Statement, python.org
Testing FilesEdit
Determine whether path exists:
import os os.path.exists('<path string>')
When working on systems such as Microsoft Windows™,
os.path('*:('C:\\')
External LinksEdit
- os — Miscellaneous operating system interfaces in Python documentation
- glob — Unix style pathname pattern expansion in Python documentation
- shutil — High-level file operations in Python documentation
- Brief Tour of the Standard Library in The Python Tutorial | https://en.m.wikibooks.org/wiki/Python_Programming/Files | CC-MAIN-2016-36 | refinedweb | 200 | 59.19 |
In this article, let’s see in detail about getting started with Angular 7 and ASP.NET Core 2.0 using Angular 7 Web Application (.NET Core) Template and ASP.NET Core MVC Application. We will also see in detail about how to work with Angular 7 new features of Virtual Scrolling and Drag and Drop Items.
If you are new to Angular, then read my previous articles from the below links:
Make sure you have installed all the prerequisites on your computer. If not, then download and install all, one by one.
Now, it’s time to create our first ASP.NET Core and Angular 7 application using the Template.
After installing all the prerequisites listed above, click Start >> Programs >> Visual Studio 2017 >> Visual Studio 2017, on your desktop.
Click New >> Project. Select Online >> Template >> Search for Angular 7 .NetCore 2 Template
style="width: 440px; height: 309px" data-src="/KB/aspnet/1274433/1.PNG" class="lazyload" data-sizes="auto" data->
Download and Install the Template.
style="width: 428px; height: 296px" data-src="/KB/aspnet/1274433/2.PNG" class="lazyload" data-sizes="auto" data->
We can see as the new Angular 7 web Application (.NET Core) template has been added. Select the template, add your project name and click ok to create your Angular 7 application using ASP.NET Core.
style="width: 425px; height: 215px" data-src="/KB/aspnet/1274433/3.PNG" class="lazyload" data-sizes="auto" data->
You can see as new Angular7 project has been created also, we can see the ASP.NET Core Controller and Angular 7 Client App folder from the solution explorer.
If we open the package.json file, we can see the new Angular 7 package has been installed to our project.
Note: We need to upgrade our Angular CLI to version 7. If you have not yet installed the Angular CLI, then first install the Angular CLI and upgrade to Angular CLI version 7.
Now, let’s start working with the Angular part.
First, we need to install the Angular CLI to our project.
Angular CLI is a command line interface to scaffold and build Angular apps using node.js style (commonJS) modules. For more details, click here.
To install the Angular CLI to your project, open the Visual Studio Command Prompt and run the below command.
npm i -g @angular/cli
Now our application is ready to build and run to see the sample Angular 7 page. Once we run the application, we can see a sample Angular 7-page like below:
Our Angular files will be under the ClientApp folder. If we want to work with component or HTML, then we open the app folder under ClientApp and we can see the app.Component.ts and app.Component.html.
ClientApp
Now we can change the Title from our component file and display the new sub title with date time in our app HTML page.
Title
In our app.Component.ts file, we changed the default title and also added a new variable to get the current date and time to display in our HTML page.
title = 'Welcome to Shanu Angular 7 Web page';
subtitle = '.NET Core + Angular CLI v7 + Bootstrap & FontAwesome + Swagger Template';
datetime = Date.now();
style="width: 424px; height: 142px" data-src="/KB/aspnet/1274433/9.png" class="lazyload" data-sizes="auto" data->
In our HTML page, we bind the newly declared variable datetime with the below code:
datetime
<h1>{{title}}</h1>
<h3>{{subtitle}}</h3>
<h4>
Current Date and Time: {{datetime | date:'yyyy-MM-dd hh:mm'}}
</h4>
When we run the application, we can see as the title has been updated and displaying today's date and time as shown in the below image:
style="width: 463px; height: 285px" data-src="/KB/aspnet/1274433/10.png" class="lazyload" data-sizes="auto" data->
Click Start >> Programs >> Visual Studio 2017 >> Visual Studio 2017, on your desktop.
Click New >> Project. Select Web >> ASP.NET Core Web Application. Enter your project name and click OK.
style="width: 481px; height: 244px" data-src="/KB/aspnet/1274433/11.PNG" class="lazyload" data-sizes="auto" data->
Select Angular Project and click OK.
By default, we can see the Angular 5 version has been installed in our project. We can check this from our Package.json file.
For upgrading to Angular 7, first we delete the ClientApp folder from project and create nee ClientApp from the Command prompt.
First, we delete the ClientApp folder from our project.
style="height: 478px; width: 500px" data-src="/KB/aspnet/1274433/14.png" class="lazyload" data-sizes="auto" data->
To install and create a new ClientApp with Angular7 packages, open a command prompt and go to our project folder. Enter the below command and run to install the Angular 7 Packages and create new ClientApp folder for working with Angular 7.
>> ng new ClientApp
style="width: 442px; height: 51px" data-src="/KB/aspnet/1274433/15.png" class="lazyload" data-sizes="auto" data->
It will take a few seconds to install all the Angular 7 Packages and we can see the installing package details and confirmation from our command window.
style="width: 478px; height: 329px" data-src="/KB/aspnet/1274433/16.PNG" class="lazyload" data-sizes="auto" data->
We can see new ClientApp folder has been created in our project and when we open the Package.json file, the Angular 7 Version has been installed to our project.
style="height: 320px; width: 640px" data-src="/KB/aspnet/1274433/17.PNG" class="lazyload" data-sizes="auto" data->
To install the Angular CLI to your project, open the Visual Studio Command Prompt and run the below command.
Now our application is ready to build and run to see the sample Angular 7 page. Once we run the application, we can see a sample Angular 7 page like below:
Virtual Scrolling and Drag and Drop are major features added in the Angular 7 CDK. If we have a large number of item in the list and want a fast performance scrolling to load and display all the items, then we can use the new Angular 7 Virtual Scrolling to scroll the items in the List. Using the Angular 7 Drag and Drop, now we can drag and drop the item to the same list or to another list. We will be seeing in detail how to work with Angular 7 Virtual Scrolling and Drag and Drop with example below.
For working with Virstual Scrolling and Drag and Drop, we need to install the Angular CDK package to our project. To add this, we open the command prompt and go to our project ClientApp Folder path and enter the below code and run the command.
style="width: 496px; height: 48px" data-src="/KB/aspnet/1274433/18.PNG" class="lazyload" data-sizes="auto" data->
We can see the confirmation message in command prompt as the Angular CDK packages have been added to our project.
style="width: 497px; height: 193px" data-src="/KB/aspnet/1274433/19.PNG" class="lazyload" data-sizes="auto" data->
In order to work with Virtual scrolling, after adding the CDK project, we need to import the ScrollingModule to our Modules app.
ScrollingModule
Modules
Open our Module.ts file, here we will be working with our default app.module.ts to import the ScrollingModule to create our Virtual Scrolling in our application.
Add the below code in import section of your module to import the ScrollingModule.
import
import { ScrollingModule } from '@angular/cdk/scrolling';
Also, we need to add the import section, add the ScrollingModule to work with Virtual Scrolling.
imports: [
BrowserModule,
AppRoutingModule,
ScrollingModule
],
Our code will look like the below image:
For adding item to the list, we need an Item, for creating the Item in our app component, we create a new Array and add items to the array in the constructor. By this, when the page loads, the new array item will be created with new values. Open the app.component.ts file and add the below code in your component export class.
incrementValue: number[] = [];
constructor() {
for (let index = 1; index <= 200; index++) {
this.incrementValue.push(index);
}
The complete code will look like this:
style="height: 348px; width: 640px" data-src="/KB/aspnet/1274433/22.PNG" class="lazyload" data-sizes="auto" data->
For our List scrolling, we will be adding the below CSS to design our list with c rounded corner and adding colors. Add the below css code to your app.component.css file:
ul {
max-width: 800px;
color: #cc4871;
margin: 20px auto;
padding: 2px;
}
.list li {
padding: 20px;
background: #f8d8f2;
border-radius: 12px;
margin-bottom: 12px;
text-align: center;
font-size: 12px;
}
Now, it's time to design our HTML page to add the Virtual Scrolling function to the List for scrolling the item from the list. Open app.component.html and add the below code to display the item in list with Virtual Scrolling features added.
List
Inside the list, we use the cdk-virtual-scroll-viewport to add the virtual scrolling to our list and here, we set the width and height of the List with the Itemsize per each scroll.
cdk-virtual-scroll-viewport
Itemsize
<h2>Angular 7 Virtual Scrolling </h2>
<hr />
<ul class="list">
<cdk-virtual-scroll-viewport
<ng-container *
<li> Loop {{incValue}} </li>
</ng-container>
</cdk-virtual-scroll-viewport>
</ul>
In order to work with Drag and Drop after adding the CDK project, we need to import the DragDrop Module to our Modules app.
DragDrop
Open our app.Module.ts file. Here, we will be working with our default app.module.ts to import the DragDrop Module to create our Drag and Drop items in our application.
Add the below code in import section of your module to import the Drag and Drop.
import { DragDropModule } from '@angular/cdk/drag-drop';
Also, we need to add the import section add the ScrollingModule to work with Virtual Scrolling.
imports: [
BrowserModule,
AppRoutingModule,
ScrollingModule ,
DragDropModule
],
Item
Array
incrementValue: number[] = [];
decrementValue: number[] = [];
constructor() {
for (let index = 1; index <= 200; index++) {
this.incrementValue.push(index);
}
for (let int1 = 400; int1 >= 201; int1--) {
this.decrementValue.push(int1);
}
}
drop(event: CdkDragDrop<string[]>) {
moveItemInArray(this.decrementValue, event.previousIndex, event.currentIndex);
}}
Here, we have used the Increment Array we use for the Virtual Scrolling and Decrement array item we use for the Drag and Drop.
Now, we need to Import the CdkDragDrop with MoveItemInArray to create the Drop event for adding the dragged item during drop at the selected position in the list.
CdkDragDrop
MoveItemInArray
Drop
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
Then, we add the drop event method inside our app component class for adding the selected item array to the selected current index.
drop(event: CdkDragDrop<string[]>) {
moveItemInArray(this.decrementValue, event.previousIndex, event.currentIndex);
}
style="height: 508px; width: 640px" data-src="/KB/aspnet/1274433/25.PNG" class="lazyload" data-sizes="auto" data->
For our List Drag Drop, we will be adding the below CSS to design our list. Add the below CSS code to your app.component.css file:
.divClasslist {
width: 200px;
border: solid 1px #234365;
min-height: 60px;
display: block;
background: #cc4871;
border-radius: 12px;
margin-bottom: 12px;
overflow: hidden;
}
.divClass {
padding: 20px 10px;
border-bottom: solid 1px #ccc;
color: rgba(0, 0, 0, 0.87);
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
cursor: move;
background: #f8d8f2;
font-size: 14px;
}
.divClass:active {
background-color: #cc4871;
}
Now, it’s time to design our HTML page to add the Drag and Drop function to the List. Open app.component.html and add the below code to display the item in list with Drag and Drop features added.
Here, we create the cdkDropList div element with Drop event using cdkDropListDropped. We add one more div element inside the cdkDroplist for adding the item with cdkDrag features for dragging the item inside the selected div element.
cdkDropList div
cdkDropListDropped
div
cdkDroplist
cdkDrag
<h2>Angular 7 Drag and Drop </h2>
<hr />
<div cdkDropList
<div class="divClass" *ngFor="let decValue of decrementValue" cdkDrag>{{decValue}}</div>
</div>
Hope you liked this article. In our next post, we will see in detail how to perform CRUD operation using Angular 7 and ASP.NET Core with and Web API.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Look forward to the next article
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://codeproject.freetls.fastly.net/Articles/1274433/Getting-Started-with-Angular-7-And-ASP-NET-Core-2?msg=5591020#xx5591020xx | CC-MAIN-2021-43 | refinedweb | 2,083 | 56.05 |
#include <vtkQtChartSeriesDomainGroup.h>
Definition at line 35 of file vtkQtChartSeriesDomainGroup.h.
Creates a chart series domain group.
Definition at line 43 of file vtkQtChartSeriesDomainGroup.h.
Gets the number of groups.
Gets the number of series in the given group.
Gets the list of series in the given group.
Finds the group index for the given series.
Updates the series indexes prior to an insert.
Inserts a new series in the specified group.
Sorts the newly inserted series if sorting is enabled.
Removes a series from its group.
Updates the series indexes after a removal.
Removes all the series groups.
Merges two sorted lists of series indexes.
Inserts a new group in the list.
Subclasses can override this method to set up data structures associated with the series group.
Removes a group from the list.
Subclasses should override this method to clean up any data structures associated with the series group. | http://www.vtk.org/doc/release/5.4/html/a01374.html | crawl-003 | refinedweb | 150 | 63.15 |
See Test Your Knowledge: Part I Exercises in Chapter 3 for the exercises.
Interaction. Assuming Python is configured properly, the interaction should look something like the following (you can run this any way you like (in IDLE, from a shell prompt, and so on):
%
python
"Hello World!"'Hello World!' >>> # Use Ctrl-D or Ctrl-Z to exit, or close window
Programs. Your code (i.e., module) file module1.py and the operating system shell interactions should look like this:
print('Hello module world!') %
python module1.pyHello module world!
Again, feel free to run this other ways—by clicking the file’s icon, by using IDLE’s Run→Run Module menu option, and so on.
Modules. The following interaction listing illustrates running a module file by importing it:
%
python>>>
import module1Hello module world! >>>
Remember that you will need to reload the module to run it again without stopping and restarting the interpreter. The question about moving the file to a different directory and importing it again is a trick question: if Python generates a module1.pyc file in the original directory, it uses that when you import the module, even if the source code (.py) file has been moved to a directory not in Python’s search path. The .pyc file is written automatically if Python has access to the source file’s directory; it contains the compiled byte code version of a module. See Chapter 3 for more on ... | https://www.safaribooksonline.com/library/view/learning-python-4th/9780596805395/apb.html | CC-MAIN-2016-44 | refinedweb | 239 | 64.71 |
I know that this topic has already appeared here and in other places. I tried to follow couple paths and can not make JupyterLab to display dash apps.
Probably there is some switch I need to turn on but can’t find out what it is and have no idea where else to look. Need some help, please.
Here is how I installed test environment
conda create --name env4 python=3.8 scipy pandas jupyterlab numpy "ipywidgets=7.5" matplotlib dash conda activate env4 conda install -c conda-forge -c plotly jupyter-dash ipython kernel install --user --name=env4 jupyter labextension install @jupyter-widgets/jupyterlab-manager plotlywidget@4.12.0 jupyter labextension install jupyterlab-plotly@4.12.0 conda install -c plotly plotly=4.12.0
(last command is there because v4.11 is loaded natively by conda).
Here is my JupyterLab extension list:
@jupyter-widgets/jupyterlab-manager v2.0.0 enabled OK jupyterlab-dash v0.3.0 enabled OK jupyterlab-plotly v4.12.0 enabled OK plotlywidget v4.12.0 enabled OK
Here is some code from Dash website as an example of what I can’t display in JupyterLab.
import plotly.graph_objects as go # or plotly.express as px fig = go.Figure() # or any Plotly Express function e.g. px.bar(...) # fig.add_trace( ... ) # fig.update_layout( ... ) import dash import dash_core_components as dcc import dash_html_components as html from jupyter_dash import JupyterDash app = JupyterDash(__name__) # app = dash.Dash() app.layout = html.Div([ dcc.Graph(figure=fig) ]) app.run_server(mode='jupyterlab', port = 8090, dev_tools_ui=True, #debug=True, dev_tools_hot_reload =True, threaded=True)
it opens new tab in JupyterLab but tab is blank.
The same when I use mode = inline
but
mode=external produces new tab in browser, as it should.
Sorry for so many words but I’m bit frustrated that I can’t make it work.
At the same time Plotly graphs are displayed properly.
As said, I’ve tried different combinations and none seems to work. Need some ideas what to do. pls. | https://community.plotly.com/t/no-dash-dislay-in-jupyterlab/46652 | CC-MAIN-2021-49 | refinedweb | 332 | 60.82 |
Factory pattern is a creational pattern as this pattern provides better ways to create an object.
In Factory pattern, we create object without exposing the creation logic to the client.
In the following sections we will show how to use Factory Pattern to create objects.
The objects created by the factory pattern would be shape objects, such as Circle, Rectangle.
First we design an interface to represent Shape.
public interface Shape { void draw(); }
Then we create concrete classes implementing the interface.
The following code is for."); } }
The core factory pattern is a Factory class. The following code shows how to create a Factory class for Shape objects.
The ShapeFactory class creates Shape object based on the String value passed in to the getShape() method. If the String value is CIRCLE, it will create a Circle object.; } }
The following code has main method and it uses the Factory class to get object of concrete class by passing an information such as type.
public class Main {(); } }
The code above generates the following result. | http://www.java2s.com/Tutorials/Java/Java_Design_Patterns/0010__Java_Factory_Pattern.htm | CC-MAIN-2017-04 | refinedweb | 171 | 58.08 |
curs_util(3) UNIX Programmer's Manual curs_util(3)
delay_output, filter, flushinp, getwin, key_name, keyname, putwin, unctrl, use_env, wunctrl - miscellaneous curses utility routines
#include <curses.h> char unctrl routine returns a character string which is a printable representation of the character c, ignoring attri- butes. Control characters are displayed in the ^X notation. Printing characters are displayed as is. The corresponding wunctrl returns a printable representation of a wide- character. The keyname routine returns a character string corresponding to the key c. Control characters are displayed in the ^X no- tation. Values above 128 are either meta characters, shown in the M-X notation, or the names of function keys, or null. The corresponding key_name returns a character string corresponding to the wide-character value w. The two func- tions do not return the same set of strings; the latter re- turns run- ning in a window (in which case default behavior would be to use the window size if LINES and COLUMNS are not set). Note that setting LINES or COLUMNS overrides the corresponding size which may be obtained from the operating system. MirOS BSD #10-current Printed 19.2.2012 1 curs_util(3) UNIX Programmer's Manual curs_util(3).
Except for flushinp, routines that return an integer return ERR upon failure and OK (SVr4 specifies only "an integer value other than ERR") upon successful completion. Routines that return pointers return NULL on error. X/Open does not define any error conditions. In this imple- mentation flushinp returns an error if the terminal was not initial- ized. putwin returns an error if the associated fwrite calls return an error.
The XSI Curses standard, Issue 4 describes these functions. It states that unctrl and wunctrl will return a null pointer if unsuccessful, but does not define any error conditions. im- plementations typically show both sets of control characters with `^', and may strip the parameter to 7 bits. This imple- mentation uses 8 bits but does not modify the string to re- MirOS BSD #10-current Printed 19.2.2012 2 curs_util(3) UNIX Programmer's Manual curs_util(3) flect locale. The keyname function may return the names of user-defined string capabilities which are defined in the terminfo entry via the -x option of tic.
curses(3), curs_initscr(3), curs_kernel(3), curs_scr_dump. | http://mirbsd.mirsolutions.de/htman/sparc/man3/putwin.htm | crawl-003 | refinedweb | 381 | 56.96 |
Introduction to Python PEP8
PEP or Python Enhancement Proposal is a draft or document which has the description of Python code writing guidelines which is the best practice to improve the consistency and readability of the Python codes. This document contains features such as Python’s Style and design which is used while writing the codes. As we know Python has a strict format or the order to write the scripts, so that it makes others easy to read the code therefore nice coding style helps tremendously to the developers or others who are reading the code. The developers must follow these guidelines. In Python, we see indentation is very important for code to execute syntactically.
Functions of PEP8 in Python
In general, Pep8 is a tool where you can check your Python code conventions with the conventions in the documentation of Pep8. Let us see a few features of Pep8 documentation:
1. Indentation
This is one of the most important features for writing the codes and for reading the codes in Python. It is also known as 4 space rule and this rule is not as mandatory as it can be overruled for the continuation of the line. Indentation also helps to know which code belongs to which function as we use braces in other programming languages in Python this done by following the rules of indentation.
In Pep8 the rules are use spaces in place of tabs, as the name of the rule use 4 consecutive spaces for indentation. If both these rules are used at once then this causes an error that issues warning by the interpreter.
Example
Code:
n = 10
if n> 5:
print “n is greater”
Output:
In the above program, the print statement follows indentation because the “if” statement is true then only the print statement is executed. If there is no proper indentation maintained then it will pop an error. The output of the above code without indentation will be:
Code:
n = 10
if n> 5:
print "n is greater"
Output:
2. Naming Conventions
To make the codes more readable and less complex there are few naming rules in Pep8 for Python coding. There are many things in the code to be given a name such as it may variables, class, methods, packages, etc. It. For naming functions or methods we can use all the letters in lowercase camel case like ClassName. For packages also follow the same as naming rules of class but instead of camel case, the letters in the package name should all be in lowercase. These all can be demonstrated in the below code.
Example()
Output:
3. Document String
This is also known as docstrings which have the document strings enclosed within both single and double quotes which are used to define the program or any particular function or methods.. One thing to note is that docstrings are not necessary for non-public methods instead you can have comments to describe the description of what method does. Also, note that for one line docstrings the end triple quotes come in the same line but for multiple lines, the end triple quotes come where the docstrings end.
Example
Code:
def addition:
a, b = 0
“““ This method is for addition”””
c = a + b
“““ This method is for addition and it is addition of two numbers.
This has a formula as shown above c = a+ b
And the addition of two numbers gives the result which is stored in c”””
return c
Some of the other few Pep8 documentation rules for Python codes are:
- We have to use UTF-8 or ASCII encoding for Python coding and it is also a default encoding that is meant for international environments.
- There is also a rule of where to use spaces. Spaces should be used only around the operators and after the comma not inside the brackets or before the comma.
- Characters should not be used for identifiers as they may lead to confusion such as for letter “l” which can be taken as lowercase “l” (el) and uppercase “I” and for the letter “O” capital O (oh) and number zero “0”.
There are many different document features of Pep8 for Python code styling and designing.
Conclusion
Pep8 is one of the tools for accurately writing Python codes with proper rules and styling for the codes. This documentation of rules is very important for the developers to write the code which is more readable and less complex for others. To note one point usually writing proper codes with proper comments and documents helps as codes are written only once but they are read many times by many people so the developers need to write the code to be readable and easy to understand the code for others. Therefore Pep8 would help you do this.
Recommended Articles
This is a guide to Python PEP8. Here we discuss the Introduction and working of python pep8 along with different examples and its code implementation. you may also have a look at the following articles to learn more – | https://www.educba.com/python-pep8/?source=leftnav | CC-MAIN-2021-04 | refinedweb | 840 | 65.46 |
31 August 2011 20:33 [Source: ICIS news]
HOUSTON (ICIS)--North American titanium dioxide (TiO2) producers are using tight supply conditions to leverage separate price-increase initiatives into more specialised end markets, a market analyst said on Wednesday.
Since the first quarter of 2009, producers have successfully raised prices by 42% for TiO2 used in paints and other general applications.
In August, however, four of the five major domestic producers announced plans to increase the price of TiO2 used in specialty markets such as plastics compounding and laminated paper products.
The latest of those specialties price-hike efforts – from Tronox – proffered an increase of 10 cents/lb ($220/tonne, €152/tonne) effective on 1 September. Previously, similar proposals were announced by Kronos, Cristal and DuPont.
If successful, those prices would be implemented in mid November or early December.
“They’re going back to a former pricing strategy – the one they used in the late `80s when supply-demand conditions were similar,” said analyst Gary Cianfichi, partner at the TiO2 consulting company Ti Insight.
TiO2 manufacturers have been absorbing the extra costs of producing pigment for plastics and many laminates’ products for several years. These products are more expensive and require a slower manufacturing process, he said.
“In my view, the market is strong enough for them to start passing through those costs,” he said.
Global efforts to get premium pricing in specialty markets began to surface early in the year, but such efforts have “firmer legs” now, he added.
Meanwhile, Huntsman’s plan to increase TiO2 prices market-wide by 10 cents/lb, effective on 1 September, is the first broad effort so late this year.
TiO2 contract prices in ?xml:namespace>
Buyers in all market segments are still frustrated with unabated price gains, but Cianfichi says further increases are inevitable despite talk to the contrary.
“All you’re hearing, in my view, is the normal pre-increase banter,” he said. “But there’s little TiO2 inventory out there. The buyers don’t have leverage. And for the next year, the ore guys who sell to TiO2 manufacturers will be cost pressured.”
TiO2 supply won’t grow fast enough to alleviate buyers’ pain. So the only hope for buyers is that demand slows, he said.
“It’s wishful thinking for the buyers to think they can successfully battle the increases," he said.
Buyers do not share that opinion.
“The ore suppliers are really running up the prices now,” a plastics compounder said. “But I believe the coatings guys are sitting on a boatload of TiO2 because their season has been soft. And I may stop buying in the fourth quarter to try and fend off the 35 cent/lb increase [expected by 1 October].”
However, the buyer offered a caveat, saying that could backfire because although the market may see a temporary glut of TiO2 due to the recent weak coatings season, supply will soon be constrained again heading into 2012 as demand returns without the benefit of additional production capacity.
“Then it will be as tight, as ever,” he said.
Asked if producers are greedy, Cianfichi said gross margins are not unfairly high, and that rising ore costs will continue to squeeze TiO2 margins.
Buyers concede upstream pressure on TiO2 producers, but continue to insist that margins have expanded at an excessive rate.
($1 = €0.69)
For more on TiO | http://www.icis.com/Articles/2011/08/31/9488874/n-america-tio2-specialty-grade-hikes-reflect-supply-side-strength.html | CC-MAIN-2014-10 | refinedweb | 561 | 61.67 |
With my new fangled REST API Python scripts I collect stats every 5 minutes for each machine electrical power Watts and Temperature plus Shared Storage Pool disk I/O.
Then I noted the the HMC "Manage Users and Tasks" shows 3000+ HMC sessions and growing a few every five minutes.
I add 5 and 5 and get "oops" so the REST API calls are creating sessions that are not closed or timing out.
Eventually your HMC will refuse further REST API calls - mine certainly did and it requires a reboot at that point.
You can't try Disconnect the session via the User Interface - it is actually a fun game to try - 3000 would take you about 3 hours!
I guess my HMC script guru could find a way using the HM CLI but it is best to not create ll these sessions in the first place.
Good news: we don't create 100's of sessions.
Bad news that token file is a security risk = allowing others to access the HMC without a user and password.
In the mean time, for Python programmers follow this below example. Curl programmers can work it out from here too.
The core is using the session token and the Logon URL (with no extra trimming like the username and password) and
use the DELETE request operation - it is a sort of a deleting the Logon request.
With REST API's we use GET, PUT and POST requests all the time. DELETE was new to me.
import sys
def disconnect(hmc, token):
headers = {'X-API-Session' : token }
url = 'https://'+hmc+':12443/rest/api/web/Logon'
ret = requests.delete(url,headers=headers,verify=False)
rcode = ret.status_code
# REST API delete officially can respond with these three good values
if rcode == 200 or rcode == 202 or rcode == 204:
print("Successfully disconnected from the HMC")
sys.exit(0)
else:
print("Logoff failed code=%d url=%s data=%s" %(rcode, url, ret.text))
sys.exit(rcode)
The HMC actually returns 204 = "No Content"
I hope that helps you, to clean up your HMC REST API scripts
Cheers, Nigel Griffiths | https://www.ibm.com/developerworks/community/blogs/aixpert/entry/Avoiding_HMC_REST_API_Session_Issues?lang=en_us | CC-MAIN-2018-39 | refinedweb | 351 | 70.33 |
I am about to finish the FLASKFM project but I am stuck in exercise 22.
This is about adding a song to the database by using the form provided.
When I enter any song, I should be able to see it on the list, however, they don’t appear.
Below is the code and not sure what is wrong with it:
@app.route(’/dashboard’, methods=[“GET”, “POST”])
def dashboard():
form = SongForm()
if request.method == ‘POST’ and form.validate():
new_song = None
new_song = Song(title = form.title, artist = form.artist, n = 1)
db.session.add(new_song)
db.session.commit()
This is the link to the exercise
[Flask FM]
() | https://discuss.codecademy.com/t/flaskfm-project/592351 | CC-MAIN-2021-39 | refinedweb | 106 | 79.06 |
#include <apr_crypto.h>
Structure describing a key to be generated by the apr_crypto_key() function.
Implementations must use apr_crypto_key_rec_make() to allocate this structure.
This is a key of arbitrary length used with a CMAC.
Key type: APR_CRYPTO_KTYPE_CMAC
This represents a simple digest with no key.
Key type: APR_CRYPTO_KTYPE_HASH
This is a key of arbitrary length used with an HMAC.
Key type: APR_CRYPTO_KTYPE_HMAC
Details of each key, based on the key type.
The type of the key.
The mode used with this crypto operation.
Non zero if padding should be used with this crypto operation.
This key is generated using a PBE algorithm from a given passphrase, and can be used to encrypt / decrypt.
Key type: APR_CRYPTO_KTYPE_PASSPHRASE
This is a raw key matching the block size of the given cipher, and can be used to encrypt / decrypt.
Key type: APR_CRYPTO_KTYPE_SECRET
The cipher used with this crypto operation. | https://ci.apache.org/projects/httpd/trunk/doxygen/structapr__crypto__key__rec__t.html | CC-MAIN-2021-21 | refinedweb | 145 | 67.76 |
import "crypto/ecdsa".
Verify verifies the signature in r, s of hash using the public key, pub. Its return value records whether the signature is valid.
VerifyASN1 verifies the ASN.1 encoded signature, sig, of hash using the public key, pub. Its return value records whether the signature is valid.
PrivateKey represents an ECDSA private key.
GenerateKey generates a public and private key pair.
func (priv *PrivateKey) Equal(x crypto.PrivateKey) bool
Equal reports whether priv and x have the same value.
See PublicKey.Equal for details on how Curve is compared...
Package ecdsa imports 11 packages (graph) and is imported by 10995 packages. Updated 2020-09-10. Refresh now. Tools for package owners. | https://godoc.org/crypto/ecdsa | CC-MAIN-2020-40 | refinedweb | 114 | 62.44 |
The Starcounter error log contains detailed information about warnings and errors. Whenever an error occurs, and whenever a component of Starcounter needs to issue a warning or a notice, a detailed message with the relevant severity is written to the error log.
You can access the error log via the Administrator Web UI. To view the error log on your machine:
Open a browser
Navigate to.
There are two ways to view the content of the log using the command-line tools: via
staradmin.exe and via
star.exe.
For greatest flexibility, use
staradmin.exe. Type
staradmin list --max=50 log to see the 50 most recent log entries.
By default,
staradmin list log will show you the 25 latest logged entries with severity
Notice and higher (i.e. including
Warning and
Error, but not
Debug).
Examples. To see,
all entries (
Notice and up), type
staradmin list --max=all log.
the 100 latest entries, including
Debug, type
staradmin log --max=100 debug.
all entries (
Notice and up), type
staradmin list --max=all log.
the 100 latest entries, including
Debug, type
staradmin list --max=100 log debug.
all errors, type
staradmin list --max=all log errors
the 20 latest errors and warnings, type
staradmin list --max=20 log warnings.
the 50 latest entries, independent of their severity, logged by the "Starcounter" log source, type
staradmin --max=50 list log all Starcounter.
Finally, entries displayed by
staradmin list log can be filtered by a named database by applying the global
-d option. For example, to see the 10 last entries from the
Starcounter.Host source, logging from within the
default database, type
staradmin -d=default list --max=10 log all Starcounter.Host.
You can instruct
star.exe to display log entries scoped to the operation star executes, for example starting an application. You do this using the new --logs option.
Typing
star --logs app.exe will first start "app.exe" and then output all log entries that was written to the log from the time when the command was invoked. By default, logs with
Notice and up is displayed. To see debug logs too, instead type
star --verbose --logs app.exe.
You can also see the direct content of the log by browsing the file content on your hard drive. To do this,
Locate the root server directory of your Starcounter installation. The default path for the personal server is:
C:\Users\[YourName]\Documents\Starcounter\Personal.
In older versions of Starcounter, it was:
C:\Users\[YourName]\Documents\Starcounter\[Version]\Personal
Open the
Logs subdirectory.
The log data is in one or more files named with the convention
Starcounter.[nnnnnnnnnn].log where [nnnnnnnnnn] is an opaque sequence number used by Starcounter. If you see several files, the one with the highest number contains the most recent entries.
Not only Starcounter components can write to the log. Applications running in Starcounter can do so too. Writing to the log is done using the
LogSource class, part of the
Starcounter.Logging namespace.
using Starcounter;using Starcounter.Logging;class Program{static void Main(){new LogSource("PerSamuelsson").LogWarning("I dont do any good!");}}
If you run the above application using
star app.cs, viewing the logged entry can be done with the
staradmin list log command, using
staradmin list log all PerSamuelsson.
The
LogSource class has support for logging errors (critical, text, and from exceptions), warnings and notices. Invoking any of the corresponding
LogSource methods, such as
LogWarning above, will assure the message ends up in the log.
In addition to errors, warnings and notices, Starcounter also allows diagnostic logging using the
Debug and
Trace methods respectively. Logging using the
Debug method will only be available in Starcounter versions built with the DEBUG configuration. Similarly, logging using the
Trace method will only be available in Starcounter versions built with the TRACE configuration.
Various Starcounter components also support low-level diagnostics in Starcounter TRACE builds by enabling trace logging. With trace logging turned on, trace messages emitted by the Starcounter runtime is routed to the log using the
Debug severity. Trace logging is an experimental feature and should not be considered future compatible. It is driven by an environment variable,
SC_ENABLE_TRACE_LOGGING. To set this flag and thereby effectively enable trace logging for a set of Starcounter components, make sure all Starcounter processes are stopped and apply the
--tracelogging flag to
scservice.exe.
staradmin kill allstart scservice --tracelogging | https://docs.starcounter.io/v/2.3.2/guides/working-with-starcounter/error-log | CC-MAIN-2020-45 | refinedweb | 729 | 58.38 |
I want to make a very specific menu, so I decided on creating a custom menu control like this:
public class MyMenu : System.Web.UI.WebControls.Menu
I want to override the existing menu control to be able to use the databinding capabilities, I want to use this menu with a sitemapprovider.
To be able to create my own menu HTML output I need to override the Render method:
protected override void Render(System.Web.UI.HtmlTextWriter writer)
Once you do that and don’t want to call the base.Render method, you are going to run into this runtime error:
Microsoft JScript runtime error: Unable to get value of the property ‘tagName’: object is null or undefined.
This is because the scripts from the asp.net menu control expect certain elements. The fix for this is to override the OnPreRender method and do NOT call the base:
protected override void OnPreRender(EventArgs e) { //prevent scripts from loading //base.OnPreRender(e); }
Now the control works, but when you set the DataSourceID the Items collection stays empty. I took me a while to find out this one: the solution is to call the PerformDataBinding method in the Render method. After this call you can use the Items collection to build your menu:
protected override void Render(System.Web.UI.HtmlTextWriter writer) { this.PerformDataBinding(); writer.Write("<div id='menu'>"); foreach (MenuItem item in Items) { ..your code here.. } writer.Write("</div>"); }
Hope this helps. | https://itq.nl/inherit-the-asp-net-menu-control/ | CC-MAIN-2018-34 | refinedweb | 241 | 56.76 |
On Sat, 11 Nov 2000, Linus Torvalds wrote:> On Fri, 10 Nov 2000, Alexander Viro wrote:> > diff -urN rc11-2/include/asm-i386/processor.h rc11-2-show_task/include/asm-i386/processor.h> > --- rc11-2/include/asm-i386/processor.h Fri Nov 10 09:14:04 2000> > +++ rc11-2-show_task/include/asm-i386/processor.h Fri Nov 10 16:08:15 2000> > @@ -412,7 +412,7 @@> > */> > extern inline unsigned long thread_saved_pc(struct thread_struct *t)> > {> > - return ((unsigned long *)t->esp)[3];> > + return ((unsigned long **)t->esp)[0][1];> > }> > The above needs to get verified: it should be something like> > unsigned long *ebp = *((unsigned long **)t->esp);> > if ((void *) ebp < (void *) t)> return 0;> if ((void *) ebp >= (void *) t + 2*PAGE_SIZE)> return 0;> if (3 & (unsigned long)ebp)> return 0;> return *ebp;> > because otherwise I guarantee that we'll eventually have a bug with a> invalid pointer reference in the debugging code and that would be bad.I would probably turn it into unsigned long *ebp = *((unsigned long **)t->esp); /* Bits 0,1 and 13..31 must be shared with the stack base */ if (((unsigned long)ebp ^ (unsigned long)t) & ~(2*PAGE_SIZE-4)) return 0; return *ebp;Comments? Alternative variant: just let schedule() store its return addressin the task_struct. Yeah, it's couple of tacts per schedule(). And much sanercode, without second-guessing the compiler. OTOH, the value is used onlyby Alt-SysRq-T, so... Hell knows. Cheers, Al-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgPlease read the FAQ at | https://lkml.org/lkml/2000/11/11/131 | CC-MAIN-2018-39 | refinedweb | 262 | 61.26 |
03 May 2012 09:52 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
The three oil firms - Indian Oil Corp (IOC), Bharat Petroleum (BPCL) and Hindustan Petroleum (HPCL) - raised the list prices of Group 1 SN150 and SN500 as well as Group II 150N and 500N base oils by Indian rupees (Rs) 5/litre ($0.09/litre) with effect from 1 May, they said.
Brightstock offers from IOC and HPCL are Rs3.50/litre higher compared to the previous month.
The price increases reflect the stronger international market and the weaker Indian rupee, which fell against the US dollar last month.
($1 = Rs | http://www.icis.com/Articles/2012/05/03/9556057/indian-refiners-increase-base-oil-prices-in-may.html | CC-MAIN-2014-41 | refinedweb | 102 | 64 |
/* winduni.c -- unicode support for the windres program. Copyright 1997, 1998, 2000, 2001, 2003 contains unicode support routines for the windres program. Ideally, we would have generic unicode support which would work on all systems. However, we don't. Instead, on a Windows host, we are prepared to call some Windows routines. This means that we will generate different output on Windows and Unix hosts, but that seems better than not really supporting unicode at all. */ #include "bfd.h" #include "bucomm.h" #include "winduni.h" #include "safe-ctype.h" #ifdef _WIN32 #include <windows.h> #endif /* Convert an ASCII string to a unicode string. We just copy it, expanding chars to shorts, rather than doing something intelligent. */ void unicode_from_ascii (int *length, unichar **unicode, const char *ascii) { int len; #ifndef _WIN32 const char *s; unsigned short *w; len = strlen (ascii); *unicode = ((unichar *) res_alloc ((len + 1) * sizeof (unichar))); for (s = ascii, w = *unicode; *s != '\0'; s++, w++) *w = *s & 0xff; *w = 0; #else /* We use MultiByteToWideChar rather than strlen to get the unicode string length to allow multibyte "ascii" chars. The value returned by this function includes the trailing '\0'. */ len = MultiByteToWideChar (CP_ACP, 0, ascii, -1, NULL, 0); if (len) { *unicode = ((unichar *) res_alloc (len * sizeof (unichar))); MultiByteToWideChar (CP_ACP, 0, ascii, -1, *unicode, len); } /* Discount the trailing '/0'. If MultiByteToWideChar failed, this will set *length to -1. */ len--; #endif if (length != NULL) *length = len; } /* Print the unicode string UNICODE to the file E. LENGTH is the number of characters to print, or -1 if we should print until the end of the string. FIXME: On a Windows host, we should be calling some Windows function, probably WideCharToMultiByte. */ void unicode_print (FILE *e, const unichar *unicode, int length) { while (1) { unichar ch; if (length == 0) return; if (length > 0) --length; ch = *unicode; if (ch == 0 && length < 0) return; ++unicode; if ((ch & 0x7f) == ch) { if (ch == '\\') fputs ("\\", e); else if (ISPRINT (ch)) putc (ch, e); else { switch (ch) { case ESCAPE_A: fputs ("\\a", e); break; case ESCAPE_B: fputs ("\\b", e); break; case ESCAPE_F: fputs ("\\f", e); break; case ESCAPE_N: fputs ("\\n", e); break; case ESCAPE_R: fputs ("\\r", e); break; case ESCAPE_T: fputs ("\\t", e); break; case ESCAPE_V: fputs ("\\v", e); break; default: fprintf (e, "\\%03o", (unsigned int) ch); break; } } } else if ((ch & 0xff) == ch) fprintf (e, "\\%03o", (unsigned int) ch); else fprintf (e, "\\x%x", (unsigned int) ch); } } | http://opensource.apple.com/source/gdb/gdb-1344/src/binutils/winduni.c | CC-MAIN-2015-32 | refinedweb | 390 | 79.3 |
class A { void m() { System.out.println("outer"); }} public class TestInners { public static void main(String[] args) { new TestInners().go(); } void go() { new A().m(); class A { void m() { System.out.println("inner"); } } } class A { void m() { System.out.println("middle"); } } }
You might have assumed the output is inner, since the class is in the same scope as the method. I don't know what are the Java language designers are thinking, it's more intuitive to choose the inner regardless of what line the class is declared. Java has some quirks on rules for resolving classes scope and accessibility, and this is one of those.
That code output is middle.
Move the class A at first line of go(), the output is inner:
void go() { class A { void m() { System.out.println("inner"); } } new A().m(); } | http://www.anicehumble.com/2012/05/java-moving-furnitures-around-is-no-no.html | CC-MAIN-2019-18 | refinedweb | 137 | 68.97 |
Evan Czaplicki, Elm’s creator, recently released Elm 0.19.1 with improved error messages. Elm 0.19.1 goes a step further in realizing Elm’s vision of being a delightful language for reliable webapps. The new release comes a year after the previous one (0.19) which emphasized smaller assets, and faster builds.
In the release blog post, Czaplicki explained his desire to “get the compiler to a point where people feel like it is actually helping them learn Elm syntax”. Czaplicki gives the hypothetical example of a JavaScript developers reusing the JavaScript syntax for imports in Elm:
import * as Set from 'set'
The error message displayed by Elm will be:
- EXPECTING IMPORT NAME ------------------------------------------ src/Main.elm I was parsing an `import` until I got stuck here: 1| import * as Set from 'set' ^ I was expecting to see a module name next, like in these examples: import Dict import Maybe import Html.Attributes as A import Json.Decode exposing (..) Notice that the module names all start with capital letters. That is required! Read <> to learn more.
Errors related to curly braces are also given specific attention. For instance, the following Elm code misses a closing curly brace:
type alias Student = { firstName : String , lastName : String , completedAssignmentIds : Set Int
The resulting error message suggests a viable fix:
-- UNFINISHED RECORD TYPE ----------------------------------------- src/Main.elm I was partway through parsing a record type, but I got stuck here: 4| { firstName : String 5| , lastName : String 6| , completedAssignmentIds : Set Int ^ I was expecting to see a closing curly brace next. Try putting a } next and see if that helps? Note: I may be confused by indentation. For example, if you are trying to define a record type across multiple lines, I recommend using this format: { name : String , age : Int , height : Float } Notice that each line starts with some indentation. Usually two or four spaces. This is the stylistic convention in the Elm ecosystem.
Previously, the 0.15.1 release focused on compiler errors, in particular locating the faulty code, content and formatting of the error message, together with hints to fix the error. The subsequent 0.16 release improved error messages further by leveraging the community feedback on Elm’s error message catalog. Concretely, the 0.16 release added better type diffs, provided more context around type errors and eliminated cascading errors.
Developers interested in exploring the new syntax error messages with Elm 0.19.1 may experiment with examples in Elm’s online editor or start working through the The Official Guide. The release note contains additional information on the new error messages brought about by the 0.19.1 release.
Czaplicki encourages Elm developers to share further any confusing error messages they encounter while learning Elm in
elm/error-message-catalog.
Community comments | https://www.infoq.com/news/2020/01/elm-learn-syntax-error-message/ | CC-MAIN-2021-04 | refinedweb | 461 | 56.76 |
At some stage in developing a server side application, I needed a way to check a particular user's download bandwidth. We have lots of client accounts in IIS6 and WMS (Windows Media Server), and each user has got a specific folder (like, where xxx is a number like 122, 133 etc.). So if someone downloads media content from a specific user's directory, it will get logged in the IIS and WMS logs (IIS will log the download, and WMS logs the streaming bandwidth).
I wrote an NT service in C# to periodically parse the IIS/WMS logs and fetch the bandwidth usage of each user, and log it to a database. The code snippet is simple and easily understandable, and I suggest you download Microsoft Log Parser 2.2 freely from Microsoft, and check the samples and example code and SQL statements. It has got tons of features.
The sample log file I used is as below. I've put in bold, the directory name for which the bandwidth usage will be retrieved. (The text gets wrapped.. just manage guys).
#Version: 1.0
#Fields: date time cs-method cs-uri cs-version c-ip x-distributor-id
x-ext-status sc-bytes time-taken sc-status cs(User-Agent) cs(Referer) cs(Cookie)
cs-uri-stem cs-uri-query
2006-03-10 21:19:15.382 GET /Temp/59/Media/movies.wmv HTTP/1.1
24.90.114.54 2011323 2000101 2018995 7393 206 "NSPlayer/9.0.0.3250 WMFSDK/9.0"
"-" "-" /Temp/59/Media/movies.wmv -
2006-03-10 21:19:36.068 GET /Temp/59/Media/movies.wmv HTTP/1.1
24.90.114.54 2011321 10 2020455 27 304 "Windows-Media-Player/9.00.00.3344" "-"
"-" /Temp/59/Media/movies.wmv -
2006-03-10 21:19:36.084 GET /Temp/59/Media/movies.wmv HTTP/1.0
206.24.192.232 2011323 121 2020455 1891 200 "Windows-Media-Player/9.00.00.3344"
"-" "-" /Temp/59/Media/movies.wmv -
Download and install Log parser 2.2 from Microsoft (Google it to find the download link.... very strange, it's been hidden somewhere deep in the MS site). After installing it, add a reference to LogParser.dll in the installation directory. Don't forget to put using MSUtil; on top.
using MSUtil;
//The passing argument "userID" is just the
//folder name for the bandwidth used need to be retrieved.
//This is just for demonstration.
//Re structure the SQL query for your needs.
public double ParseW3CLog( string userID )
{
// prepare LogParser Recordset & Record objects
ILogRecordset rsLP = null;
ILogRecord rowLP = null;
LogQueryClassClass LogParser = null;
COMW3CInputContextClassClass W3Clog = null;
double UsedBW = 0;
int Unitsprocessed;
double sizeInBytes;
string strSQL = null;
LogParser = new LogQueryClassClass();
W3Clog = new COMW3CInputContextClassClass();
try
{
//W3C Logparsing SQL. Replace this SQL query with whatever
//you want to retrieve. The example below
//will sum up all the bandwidth
//Usage of a specific folder with name
//"userID". Download Log Parser 2.2
//from Microsoft and see sample queries.
strSQL = @"SELECT SUM(sc-bytes) from C:\\logs" +
@"\\*.log WHERE cs-uri-stem LIKE '%/" +
userID + "/%' ";
// run the query against W3C log
rsLP = LogParser.Execute(strSQL, W3Clog);
rowLP = rsLP.getRecord();
Unitsprocessed = rsLP.inputUnitsProcessed;
if (rowLP.getValue(0).ToString() == "0" ||
rowLP.getValue(0).ToString() == "")
{
//Return 0 if an err occured
UsedBW = 0;
return UsedBW;
}
//Bytes to MB Conversion
double Bytes = Convert.ToDouble(rowLP.getValue(0).ToString());
UsedBW = Bytes / (1024 * 1024);
//Round to 3 decimal places
UsedBW = Math.Round(UsedBW, 3);
}
catch
{
throw;
}
return UsedBW;
}
Quite easy, without lines and lines of code... and you will get all sorts of examples from the downloaded toolkit itself. This can be used to retrieve usage stats/bandwidth usage/file type/browser info.. you name it... from almost all types of standard log files (IIS/Mail/WMS/Ap. | https://www.codeproject.com/articles/13504/simple-log-parsing-using-ms-log-parser-2-2-in-csha | CC-MAIN-2017-13 | refinedweb | 627 | 69.18 |
I wonder: if we have a decidable partial ordering: like
leq method in
PartialOrd type class in
lattices package.
Can we sort a list using
leq so we get kind of a topological sorting?
Note, topological sorting is used for graphs: there we don’t have
leq-like luxury. We’d first need to compute a transitive closure of a graph. On the other hand, given a list of "node", it may not include all nodes; and may include duplicates.
Insertion sort is a simple sorting algorithm, trivial to implement for lists (i.e. not in-place). I continue wondering: maybe it will produce topological ordering. Even insertion sort is simple, I still had an uneasy feeling: does it really work. Insertion sort terminates despite what function you pass as a comparator (even impure random one!), so what kind of output it produces when given lawful
leq?
I must admit that exposure to Haskell and Agda made me suspect all pen and paper proofs, especially made by myself. So let’s certify insertion sort. The plan is to show how to certify insertion order first for total order and then for partial order.
Module definitions and imports:
module Topo where open import Data.List open import Relation.Nullary open import Relation.Binary.PropositionalEquality
Next, the definition of
insert and
sort. These are straight-forward and are familiar. Note that
_≤?_ decides whether
≤-relation holds. Returning
Dec doesn’t forget what we compute (it returns the evidence), compared with simply returning
Bool.
module Sort {A : Set} (_≤_ : A → A → Set) (_≤?_ : (x y : A) → Dec (x ≤ y)) where insert : A → List A → List A insert x [] = x ∷ [] insert x (y ∷ ys) with x ≤? y ... | yes x≤y = x ∷ y ∷ ys ... | no ¬x≤y = y ∷ insert x ys sort : List A → List A sort [] = [] sort (x ∷ xs) = insert x (sort xs)
Twan van Laarhoven proved complete correctness of various sort algorithms (code gist). We’ll only do a sortedness of insertion sort.
Twan uses
_≤?_ : (x y : A) → (x ≤ y ⊎ y ≤ x) comparator (
⊎ is
Either), that implies that ordering have to be total. Our
... → Dec (x ≤ y) version is less powerful, therefore we’ll need to assume
≤-flip.
Twan also defines
insert to operate on
Sorted xs, our proof is completely external.
There are few auxiliary lemmas, culminating with lemma that
insert preserves sortedness, and the theorem that
sort produces a sorted list.
One could also show that
sort produces a permutation of input list, but that’s something I’m quite confident about already. Note: the proof of that fact won’t need any additional assumptions about
≤.
By the way, these proofs show how dependently typed programming is full with various lists.1 Luckily (or not) Agda allows reuse of constructor names.
module Total (A : Set) (_≤_ : A → A → Set) (_≤?_ : (x y : A) → Dec (x ≤ y)) (≤-trans : ∀ {x y z} → x ≤ y → y ≤ z → x ≤ z) (≤-flip : ∀ {x y} → ¬ (x ≤ y) → y ≤ x) -- precise enough! where infix 4 _≤*_ open Sort _≤_ _≤?_ data _≤*_ (x : A) : List A → Set where [] : x ≤* [] _∷_ : ∀ {y ys} → x ≤ y → x ≤* ys → x ≤* y ∷ ys data Sorted : List A → Set where [] : Sorted [] _∷_ : ∀ {x xs} → x ≤* xs → Sorted xs → Sorted (x ∷ xs) ≤*-trans : ∀ x y ys → x ≤ y → y ≤* ys → x ≤* ys ≤*-trans x y [] x≤y [] = [] ≤*-trans x y (y' ∷ ys) x≤y (y≤y' ∷ y'≤ys) = ≤-trans x≤y y≤y' ∷ (≤*-trans x y ys x≤y y'≤ys) lem-cons-all≤ : ∀ x y ys → x ≤ y → y ≤* ys → x ≤* y ∷ ys lem-cons-all≤ x y ys x≤y y≤ys = x≤y ∷ ≤*-trans x y ys x≤y y≤ys lem-skip : ∀ x y ys → y ≤ x → y ≤* ys → y ≤* insert x ys lem-skip x y [] y≤x y≤ys = y≤x ∷ y≤ys lem-skip x y (y' ∷ ys) y≤x (y≤y' ∷ y'≤ys ) with x ≤? y' ... | yes x≤y' = y≤x ∷ y≤y' ∷ y'≤ys ... | no ¬x≤y' = y≤y' ∷ (lem-skip x y ys y≤x y'≤ys)-all≤ x y ys x≤y y≤ys ∷ y≤ys ∷ sys ... | no ¬x≤y = lem-skip x y ys (≤-flip)
But what about partial order? Wikipedia says following about the topological sort:
In computer science, a topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge from vertex to vertex , comes before in the ordering.
We massage that into simple "there aren’t edges pointing backwards". So instead of saying: "for all sublists
x ∷ ys,
x is less-than-or-equal than any of
y
ys" we say "for all subsets
x ∷ ys, x is not greater-than any of
y
ys".
After that, the proof structure is quite similar. I needed to use antisymmetry of
≤, which shows that this
Sorted predicate won’t hold for preorder. I’m not sure whether insertion order would work for preorder, I’m not sure it won’t work either.
module Partial (A : Set) (_≤_ : A → A → Set) (_≤?_ : (x y : A) → Dec (x ≤ y)) (≤-trans : ∀ {x y z} → x ≤ y → y ≤ z → x ≤ z) (≤-antisym : ∀ {x y} → x ≤ y → y ≤ x → x ≡ y) where open Sort _≤_ _≤?_ record _<_ (x y : A) : Set where constructor le field is-le : x ≤ y not-eq : ¬ (x ≡ y) open _<_ <-trans₁ : ∀ {x y z} → x < y → y ≤ z → x < z <-trans₁ (le x≤y ¬x≡y) y≤z = le (≤-trans x≤y y≤z) (λ x≡z → ¬x≡y (≤-antisym x≤y (subst (λ i → _ ≤ i) (sym x≡z) y≤z))) infix 4 _¬>*_ -- x ¬>* ys = x is not larger than any in y ∈ ys data _¬>*_ (x : A) : List A → Set where [] : x ¬>* [] _∷_ : ∀ {y ys} → ¬ y < x → x ¬>* ys → x ¬>* y ∷ ys data Sorted : List A → Set where [] : Sorted [] _∷_ : ∀ {x xs} → x ¬>* xs → Sorted xs → Sorted (x ∷ xs) lem-trans-none> : ∀ x y ys → x ≤ y → y ¬>* ys → x ¬>* ys lem-trans-none> x y [] x≤y [] = [] lem-trans-none> x y (z ∷ zs) x≤y (¬z<y ∷ y≤zs) = (λ z<y → ¬z<y (<-trans₁ z<y x≤y)) ∷ lem-trans-none> x y zs x≤y y≤zs lem-flip : ∀ {x y} → x ≤ y → ¬(y < x) lem-flip {x} {y} x≤y with y ≤? x ... | yes y≤x = λ y<x → not-eq y<x (≤-antisym y≤x x≤y) ... | no ¬y≤x = λ y<x → ¬y≤x (is-le y<x) lem-cons-none> : ∀ x y ys → x ≤ y → y ¬>* ys → x ¬>* y ∷ ys lem-cons-none> x y ys x≤y y≤ys = lem-flip x≤y ∷ lem-trans-none> _ _ _ x≤y y≤ys lem-skip : ∀ x y ys → ¬ (x ≤ y) → y ¬>* ys → y ¬>* insert x ys lem-skip x y [] ¬x≤y [] = (λ p → ¬x≤y (is-le p)) ∷ [] lem-skip x y (z ∷ zs) ¬x≤y (¬z<y ∷ y≤zs) with x ≤? z ... | yes x≤z = (λ x<y → ¬x≤y (is-le x<y)) ∷ ¬z<y ∷ y≤zs ... | no ¬x≤z = ¬z<y ∷ (lem-skip x y zs ¬x≤y y≤zs)-none> x y ys x≤y y≤ys ∷ y≤ys ∷ sys ... | no ¬x≤y = lem-skip x y ys)
Would merge sort work with partial order? I don’t know yet!
Let’s try in Haskell. You should try your hypothesis first, before trying to formally prove them. Proving false statements can take a lot of time!
After a little of imports, we’ll defined
isSorted check, and try it on a
N5 lattice.
insertionSort works with
leq, but a
mergeSort only with
<=.
import Algebra.PartialOrd import Algebra.Lattice.N5 import Algebra.Lattice.Ordered import Data.List (sortBy) import Test.QuickCheck lt :: PartialOrd a => a -> a -> Bool lt x y = x /= y && leq x y notGt :: PartialOrd a => a -> a -> Bool notGt x y = not (lt y x) -- | This checks that list is sorted in PartialOrd sense. isSorted :: PartialOrd a => [a] -> Bool isSorted [] = True isSorted (x : ys) = isSorted ys && all (notGt x) ys -- | Sorted holds when list is sorted using @Ord@ -- -- +++ OK, passed 100 tests. totalProp :: [Ordered Int] -> Bool totalProp = isSorted . sortBy compare -- | Next, let's define insertion sort. insertionSort :: (a -> a -> Bool) -> [a] -> [a] insertionSort le = go where go [] = [] go (x:xs) = insert x (go xs) insert x [] = [x] insert x (y : ys) | le x y = x : y : ys | otherwise = y : insert x ys -- | And try with a partially ordered set. -- -- +++ OK, passed 100 tests. -- -- Works! m5Prop :: [N5] -> Bool m5Prop = isSorted . insertionSort leq -- Then, naive mergesort. mergeSort :: (a -> a -> Bool) -> [a] -> [a] mergeSort f = go where go [] = [] go [x] = [x] go xs = let (ys, zs) = split xs in merge (go ys) (go zs) merge [] ys = ys merge xs [] = xs merge (x:xs) (y:ys) | f x y = x : merge xs (y:ys) | otherwise = y : merge (x:xs) ys -- | >>> split [1..10] -- ([1,3,5,7,9],[2,4,6,8,10]) split :: [a] -> ([a],[a]) split [] = ([], []) split (x:xs) = case split xs of ~(ys,zs) -> (x:zs,ys) -- | Our 'mergeSort' returns correct results. Works like 'sort'. -- -- +++ OK, passed 100 tests mergeProp :: [Int] -> Property mergeProp xs = mergeSort (<=) xs === sortBy compare xs -- >>> quickCheck m5Prop2 -- *** Failed! Falsified (after 18 tests and 4 shrinks): -- [N5b,N5a,N5c] -- sorted [N5a,N5c,N5b] -- -- >>> insertionSort leq [N5b,N5a,N5c] -- [N5c,N5b,N5a] -- -- Sort is not unique: insertionSort finds an ordering: -- See picture at -- -- >>> leq N5b N5a -- True -- -- >>> isSorted [N5c,N5b,N5a] -- True -- -- >>> isSorted [N5b,N5a,N5c] -- True -- -- >>> isSorted [N5b,N5c,N5a] -- True -- m5Prop2 :: [N5] -> Property m5Prop2 xs = let xs' = mergeSort leq xs in counterexample ("sorted " ++ show xs') $ isSorted xs'
Note:
Sorted is somewhat lax:
-- >>> isSorted [N5b,N5c,N5b] -- True
But that’s not an issue to me, as I’ll be sorting lists with distinct elements. More on that later.
In Haskell there’s a variety of string types. In Dependent Haskell there will be a variety of various lists and naturals numbers... ... and strings types.↩︎ | https://oleg.fi/gists/posts/2019-07-19-insertion-sort-toposorts.html | CC-MAIN-2021-25 | refinedweb | 1,680 | 70.63 |
Today, Microsoft released the long waited Files-On-Demand support in macOS Mojave. As you might know Files-On-Demand (or FOD) has been available in Windows 10 for a while but it has been a featured that we have been waiting for in macOS for quite some time. Now at Ignite, Microsoft is giving you the opportunity to try it out. In order to try it out, you first have to upgrade to macOS Mojave 10.14. The latest version of macOS just came out today on September 24th and is now available to download. If you are running on a beta version still, you can try it out as well.
The second thing, you need to do is make sure you are in the Insiders Ring for Office and / or OneDrive. If you aren’t sure, download the script from the installation site. It’s a bash script, so you will need to make the script executable. If you aren’t familiar with this process, you have to get back to the Unix / BSD roots of OS X. Open a new Terminal, and go to the directory where you downloaded the script and then execute the following command:
chmod u+x ./EnableMacFilesOnDemand.sh
If you’ve had OneDrive installed on your Mac before, you’ll need to delete some cache files in the following folder: ~/Library/Caches/OneDrive. Delete *.json in that folder. I didn't actually do this step, but you may need to.
Now you can install the OneDrive client. Download the client from the install link and then go through the install process. Launch OneDrive when it’s complete. If you run into issues, there are a few troubleshooting tips about force closing Finder. I didn’t have to do that but you may need to on your machine.
If you have enabled the new macOS Mojave Dark Mode, the first thing you might notice is that the OneDrive client respects that and will also show using Dark Mode. Good job, OneDrive engineering team! That makes for a nice experience.
I had to setup one of my Office 365 accounts on this particular machine but that’s good because it gave me an idea for the new account setup experience. After you sign in, you’ll get this new dialog that explains the icons that you will see in Finder. Cloud = online only, checkbox = the file is on disk. This is helpful, because I’ve always had trouble remembering what the icons mean in FOD for Windows 10.
For existing accounts, you may need to turn on Files-On-Demand manually. I didn’t have to in my case, but it’s good to know where to go. Go to Preferences in OneDrive and then look for the Files-On-Demand section. You can see verify whether it has been turned on or not.
Now we can go find our OneDrive folder inside Finder and see how it all works. When I open one of my synced folders, you’ll notice that I am now seeing files that I have not downloaded yet indicated by the cloud icon next to each one. That’s right, I am seeing files that are online, but not yet downloaded.
Clicking on an online file will immediately download it and you can access it like you had it all along. This is what we have been waiting for. If you right click on a file, you now see the option to Always keep on this device. This is how you tell OneDrive to keep that file on your device for offline use.
Once you do that, you’ll notice the icon changes from a cloud to a check mark.
I’m looking forward to using this on a day-to-day basis. This should make working with OneDrive files online and offline much easier with macOS Mojave 10.14.
With React, sometimes the simplest of things are overly complicated. When it comes to creating a page anchor so your users can jump down to a specific point in the page, this one is no exception. From our old HTML4 days, you probably remember you create an anchor by doing something like the following:
When you look for the name attribute of an anchor in React though, it's nowhere to be found. Ultimately this has to do with React's routing system, but that doesn't really do you any good in your SPFx Web Part. How do you get around it? One way is to use the Link component from Fabric React. You'll notice it does have a name attribute but using it isn't quite straight forward. First, include Link on the page you are building.
Once you do that, add your Link to the page using the name attribute and a unique identifier. This will be the destination we are jumping to.
You might be wondering why I have the href tag there on the anchor tag. That is because the Link element renders a Link element as a button instead of an anchor tag if there isn't an href tag. You can include any value you want there, but a value is required.
Now to jump to our anchor tag, use the Link tag and include a hash tag and your unique identifier.
Again this seems like a simple topic, but if you are new to React because you just started SPFx development, this might take you a minute to figure out.
Contrary to popular belief, I still do development. In fact, I do quite a bit of development. In the last couple of years, I have built two mobile platforms as a service using Ionic and Angular. This node.js based development stack positioned me well to start working with SPFx. I'm starting up a string of blog posts that help cover the basics that I think that we often overlook in the bigger picture of how to do things with SPFx. Today's topic is simple: reading a value from the query string. When I recently looked at this simple scenario, I thought sure I could go back to my JavaScript roots and use location.href but there has to be a better way now right? The SPFx team thought of that and they included a nice helper class to get you going called UrlQueryParameterCollection.
Start by including a reference to UrlQueryParameterCollection.
import { UrlQueryParameterCollection } from '@microsoft/sp-core-library';
We use the getValue() Like ASP.NET or other languages, you'll usually want to check to see if it has a value before using it. I then cast it to an integer time after reading the value.
Again, this is a simple example, but hopefully it will keep you from going down the path with location.href. The sp-core-library has all sorts of useful utitlities for you to use such as Environment, Random Number Generators, and logging. Check it out the next time you start out a project. | http://dotnetmafia.com/blogs/dotnettipoftheday/archive/2018/09.aspx | CC-MAIN-2018-47 | refinedweb | 1,170 | 72.36 |
Something went wrong getting user information from Channel 9
Something went wrong getting user information from MSDN
Something went wrong getting the Visual Studio Achievements
TWC9: Visual Studio 2013 Pricing, RyuJIT, Learning Windows 8.1 and moreOct 04, 2013 at 11:30 PM
99$... it's a good news.
IWP 61 | Building for Windows Phone and Windows 8 - The BasicsAug 17, 2013 at 12:14 AM
This code sharing is not so perfect at present but I think that in this show are explained some good tips with the default namespace and shortcuts for class files. Thanks.
IWP 57 | Location and Mapping for Windows Phone 8Jun 17, 2013 at 11:04 AM PM
I love this show ! Very helpful and inspiring. I have questions:
Last step that You've made... Getting the token for MapServices is for free ? And there is no additional costs connected with developing and submitting apps with maps to the store ? This map app will work on every phone or only Nokias ? And the last thing... This is available for Windows 8 (tablets, pc's etc.) too ?
Developing an app with the Visual Studio 3D Starter KitApr 17, 2013 at 11:15 AM
I didn't watch this movie earlier:
This is the answer for my previous question.
But thanks for Your response Roberto.
Developing an app with the Visual Studio 3D Starter KitApr 14, 2013 at 2:10 AM ?
Developing an app with the Visual Studio 3D Starter KitApr 13, 2013 at 12:10 AM
Great job on this post. I'm wondering if when we want to make something different than a cube... I mean load our own model for example... this is something easy to do with 3D kit ? (easier than normally) | http://channel9.msdn.com/Niners/dzimiq | CC-MAIN-2013-48 | refinedweb | 289 | 74.29 |
HOUSTON (ICIS)--As ?xml:namespace>
The pipeline, a project of TransCanada, would cross the border between the
In January 2012, Obama rejected a permit for the pipeline, saying the deadline did not allow for enough time to fully weigh the project’s impact.
Then, on 22 January 2013,
Now the fate of the pipeline again lies with Obama, who is expected to decide on it by mid-year.
But Tillerson intimated on Wednesday during ExxonMobil’s annual analysts day that Canadians have been formulating other plans in case the
“The Canadian government is not going to sit still, either,” he said. “They are going to want to deal with this issue, too. All of those solutions aren’t necessarily south, and I think we all should just keep that in mind.”
At present, about 99% of | https://www.icis.com/resources/news/2013/03/13/9649511/canada-makes-plans-in-case-keystone-not-approved-exxonmobil-ceo/ | CC-MAIN-2018-30 | refinedweb | 136 | 57.91 |
Welcome to the discussion thread about this lecture section. Here you can feel free to discuss the topic at hand and ask questions.
I keep getting the errors below. Someone please help.
8 errors generated.
Error while processing /tmp/projects/5db7ea85efa97e003e055dab/src/helloworld.cpp.
abigen error
Warning, empty ricardian clause file
Warning, empty ricardian clause file
Warning, action does not have a ricardian contract
What’s the error in the red popup?
Hi mawa I have a similar issue . will post mine in the discussion.
in the meantime . did you manage to sort it out ?
JJ.
Hi Guys,
this is the error I have on the redbox.
Any help is welcome
thanks.
/project/src/helloworld.cpp:3:20: error: out-of-line definition of ‘hi’ does not match any declaration in ‘helloworld’
ACTION helloworld::hi(name user){
1 error generated.
Error while processing /project/src/helloworld.cpp.
abigen error
Warning, empty ricardian clause file
Warning, empty ricardian clause file
Warning, action does not have a ricardian contract
Warning, action does not have a ricardian contract
Warning, action does not have a ricardian contract
I assume this happens when you compile? Can you share your code here, both the cpp and the hpp file, please
Hi Filip,
this is sorted
I was using the latest EOS studio version and CDT 1.6.3 ( not 1.6.2 ) like in the course.
The file include/helloworld.hpp has changed between CDT 1.6.2 and 1.6.3.
I am using now exactly the same EOS studio as in the course
Hmm, so you had to rewrite the hpp file? I’m trying to figure out how we can avoid other students facing this issue.
UPDATE!
Watched your authority/authentication video, figured what the problem was
Great! What was the problem?
The Sample generated file has changed since your tutorials.
It comes with the
require_auth(user) by default, which was why the
given name had to be the account calling the function.
All the same, thanks for the quick response.
Hello.
The code that generates Eos Studio has changed. It’s not the same as the code at the video.
To be compatible with the video example, copy paste the code below:
In the file helloworld.cpp
#include <helloworld.hpp>
ACTION helloworld::hi(name user) {
require_auth(user);
print("Hello, ", name{user});
}
In the file helloworld.hpp
#include <eosio/eosio.hpp>
using namespace std;
using namespace eosio;
CONTRACT helloworld : public contract {
public:
using contract::contract;
ACTION hi(name user); private: TABLE messages { name user; string text; auto primary_key() const { return user.value; } }; typedef multi_index<name("messages"), messages> messages_table;
};
Hope I helped.
For the course: Hello World - Step by Step Walkthrough
The strange command:
helloworld(name receiver, name code, datastream<const char>ds):contract(receiver,code, ds)
{}
now is not required.
Is that the case even if you select the same eos cdt version as I had?
Yes.
I’m using cdt version 1.6.2 WEB studio.
@filip Each time I build and run in EOS Studio, on the next screen after clicking play the console: is blank each time.
@filip my helloworld.cpp looks like:
#include <hello.hpp> #include <eosio/eosio.hpp> ACTION hello::hi(name from, string message) { require_auth(from); // Init the _message table messages_table _messages(get_self(), get_self().value); // Find the record from _messages table auto msg_itr = _messages.find(from.value); if (msg_itr == _messages.end()) { // Create a message record if it does not exist _messages.emplace(from, [&](auto& msg) { msg.user = from; msg.text = message; }); } else { // Modify a message record if it exists _messages.modify(msg_itr, from, [&](auto& msg) { msg.text = message; }); } } ACTION hello::clear() { require_auth(get_self()); messages_table _messages(get_self(), get_self().value); // Delete all records in _messages table auto msg_itr = _messages.begin(); while (msg_itr != _messages.end()) { msg_itr = _messages.erase(msg_itr); } } EOSIO_DISPATCH(hello, (hi)(clear))
Hi
Is this causing the blank page you mention in your earlier post?
Ivo
No, after I created transaction and am on the “Transaction Details”, the console: is empty. It should be console: Hello Sonja
Hi,
I got it working now
| https://forum.ivanontech.com/t/basic-eos-programming-discussion/9008 | CC-MAIN-2020-24 | refinedweb | 674 | 61.53 |
Hello ! I’m Xavier Jouvenot and in this small post, I am going to explain how to bind a function to a button.
Self promotion: You can find other articles on Android development on my website 😉
Handling your buttons click in the activity
There are two ways to handle your buttons click in your activity java code.
Inheritance
The first method I want to talk to you about, can allow you to handle the clicks to all of the buttons of your activity in one function.To do so, you should make your activity implements
View.OnClickListener and override the method
onClick:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { // ... Button bt = findViewById(R.id.button); bt.setOnClickListener(this); // ... } @Override public void onClick(View v) { if (v.getId() == R.id.button) { // Do something } } }
In this code, you specify that your button listener is your activity during the creating of the activity.Then, when the user will click on the button, the method
onClick will be called.In that function, you will look at the id of the element to know which button has been clicked on, and react accordingly.
Personally, this is my least favorite method.I found that, the more buttons you have in your interface, the less readable becomes the function
onClick. 😢
Binding a function on the Activity creation
This second method allows you to specifies your button callbacks during the activity creation.It looks like that:
public class MainActivity extends AppCompatActivity implements View.OnClickListener{ @Override protected void onCreate(Bundle savedInstanceState) { // ... Button bt = findViewById(R.id.button); bt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Do something } }); // ... } }
The advantages of this method, compare to the first one, is that you don’t have to use you button id to check what to do.You know directly which button is concerned by your callback.
But the more buttons you have, the less readable your
onCreate method will be. 😢
Using the layout of the button
The last method I want to talk about consists of using the XML definition of the button to specify the callback of the button.Indeed, you can specity which method of your activity you want to be called by adding an attribute
android:onClick in the button XML definition.This can look like this:
<Button android: public class MainActivity extends AppCompatActivity implements View.OnClickListener{ // ... public void onMyButtonClick(View v) { // Do something } // ... }
Personally, I found this method to be the best one.It allows you to separate the place where the callback is implemented from the place where it is linked to the button.You don’t have to check which button is clicked on since you know it from your XML, and you can create one callback for each of your button without making another method unreadable.
I definitely recommend you to use this one 😉
Thank you all for reading this article,And until my next article, have an splendid day 😉
Discussion (0) | https://dev.to/10xlearner/quick-tip-how-to-bind-a-function-to-a-button-2g1e | CC-MAIN-2021-21 | refinedweb | 497 | 55.44 |
16 March 2010 07:40 [Source: ICIS news]
By Chow Bee Lin
SINGAPORE (ICIS news)--Polyethylene (PE) and polypropylene (PP) producers in South Korea are looking to make further inroads into the South American markets where sales can yield bigger margins compared to their traditional market in China, industry sources said on Tuesday.
Tight PE supply in South America had enabled ?xml:namespace>
Film grade HDPE and LLDPE could be sold at $1,400-1,410/tonne (€1,022-1,029/tonne) FOB (free on board)
But the same cargo could only fetch prices below $1,400/tonne FOB
A Korean PP producer said he could achieve FOB
South American buyers had been seeking block copolymer PP from alternative sources such as
Homopolymer PP was assessed on an FOB US Gulf basis at 70-72 US CTS/LB for the week ended 12 March, equivalent to around $1,540-1,584/tonne FOB US Gulf, according to global chemical market intelligence service ICIS pricing.
Despite their increased export to South America, most Korean producers said their main export market was still
South Korea was one of the top ten PE and PP exporters to China last year, having shipped out a total of 1.3m tonnes of PE and 1.1m tonnes of PP to that market.
Major PE and PP producers in
($1 = €0.73) | http://www.icis.com/Articles/2010/03/16/9342922/s-koreas-pepp-producers-eye-latin-american-markets.html | CC-MAIN-2014-42 | refinedweb | 226 | 58.86 |
tg-d 0.0 is available here.
Getting updates
Currently, only long polling is supported. Use
TelegramBot.pollUpdates which provides high-level abstraction over
TelegramBot.getUpdates.
import tg.d; void main() { while(true) { foreach(update; TelegramBot("token").pollUpdates) { // Do something with `update` } } }.1 released 4 years ago
- AntonMeep/tg.d
- MIT
- Copyright for portions of project tg.d are held by Pavel Chebotarev, 2018 as part of project telega (). All other copyright for project tg.d are held by Anton Fediushin, 2018.
- Authors:
-
- Dependencies:
- vibe-d:data, vibe-d:tls, vibe-core, vibe-d:http
- Versions:
- Show all 4 versions
- Download Stats:
0 downloads today
0 downloads this week
0 downloads this month
51 downloads total
- Score:
- 2.4
- Short URL:
- tg-d.dub.pm | https://code.dlang.org/packages/tg-d/0.0.1 | CC-MAIN-2022-05 | refinedweb | 125 | 63.05 |
#include <wx/panel.h>
A panel is a window on which controls are placed.
It is usually placed within a frame. Its main feature over its parent class wxWindow is code for handling child windows and TAB traversal. Since wxWidgets 2.9, there is support both for TAB traversal implemented by wxWidgets itself as well as native TAB traversal (such as for GTK 2.0).
wx/containr.hand
wx/panel.hto find out how this is achieved.
wxTAB_TRAVERSALstyle, which grabs some keypresses for use by child controls.
The following event handler macros redirect the events to member function handlers 'func' with prototypes like:
Event macros for events emitted by this class:
Default constructor.
Destructor.
Deletes any child windows before deleting the physical window.
This method is overridden from wxWindow::AcceptsFocus() and returns true only if there is no child window in the panel which can accept the focus.
This is reevaluated each time a child window is added or removed from the panel.
Reimplemented from wxWindow.
Sends a wxInitDialogEvent, which in turn transfers data to the dialog via validators.
Reimplemented from wxWindow.
See wxWindow::SetAutoLayout(): when auto layout is on, this function gets called automatically when the window is resized.
Reimplemented from wxWindow.
The default handler for
wxEVT_SYS_COLOUR_CHANGED.
Overrides wxWindow::SetFocus().
This method uses the (undocumented) mix-in class wxControlContainer which manages the focus and TAB logic for controls which usually have child controls.
In practice, if you call this method and the control has at least one child window, the focus will be given to the child window.
Reimplemented from wxWindow.
In contrast to SetFocus() (see above) this will set the focus to the panel even if there are child windows in the panel.
This is only rarely needed. | http://docs.wxwidgets.org/3.0.3/classwx_panel.html | CC-MAIN-2017-51 | refinedweb | 290 | 58.69 |
In the last couple of posts (1, 2) I described what needed to be done when migrating a Python web site running under Apache/mod_wsgi to running inside of a Docker container. This included the steps necessary to have the existing Apache instance proxy requests for the original site through to the appropriate port on the Docker host and deal with any fix ups necessary to ensure that the backend Python web site understood what the public facing URL was.
In changing to running the Python web site under Docker, I didn’t cover the issue of how the instance of the Docker container itself would be started up and managed. All I gave was an example command line for manually starting the container.
docker run --rm -p 8002:80 blog.example.com
The assumption here was that you already had the necessary infrastructure in place to start such Docker containers when the system started, and restart them automatically if for some reason they stopped running.
There are various ways one could manage service orchestration under Docker. These all come with their own infrastructure which has to be set up and managed.
If instead you are just after something simple to keep the Python web site you migrated into a Docker container running, and also manage it in conjunction with the front end Apache instance, then there is actually a trick one can do using mod_wsgi on the front end Apache instance.
Daemon process groups
When using mod_wsgi, by default any hosted WSGI application will run in what is called embedded mode. Although this is the default, if you are running on a UNIX system it is highly recommended you do not use embedded mode and instead use what is called daemon mode.
The difference is that with embedded mode, the WSGI application runs inside of the Apache child worker processes. These are the same processes which handle any requests received by Apache for serving up static files. Using embedded mode can result in various issues due to the way Apache manages those processes. The best solution is simply not to use embedded mode and use daemon mode instead.
For daemon mode, what happens is that a group of one or more separate daemon processes are created by mod_wsgi and the WSGI application is instead run within those. All that the Apache child worker processes do in this case is transparently proxy the requests through to the WSGI application running in those separate daemon processes. Being a separate set of processes, mod_wsgi is able to better control how those processes are managed.
In the initial post the example given was using daemon mode, but the aim was to move the WSGI application out of the front end Apache altogether and run it using a Docker container instead. This necessitated the manual configuration to proxy the requests through to that now entirely separate web application instance running under Docker.
Now.
Running the Docker image
In the prior posts, the basic configuration we ended up with for proxying the requests through to the Python web site running under Docker was:
# blog.example.com<VirtualHost *:80>
ServerName blog.example.comProxyPass /
ProxyPassReverse /
RequestHeader set X-Forwarded-Port 80
</VirtualHost>
This was after we had removed the configuration which had created a mod_wsgi daemon process group and delegated the WSGI application to run in it. We are now going to add back the daemon process group, but we will not set up any WSGI application to run in it. Instead we will setup a Python script to be loaded in the process when it starts using the ‘WSGIImportScript’ directive.
# blog.example.com<VirtualHost *:80>
ServerName blog.example.com
ProxyPass /
ProxyPassReverse /
RequestHeader set X-Forwarded-Port 80
WSGIDaemonProcess blog.example.com threads=1
WSGIImportScript /some/path/blog.example.com/docker-admin.py \
process-group=blog.example.com application-group=%{GLOBAL}
</VirtualHost>
In the ‘docker-admin.py’ file we now add:
import osos.execl('/usr/local/bin/docker', '(docker:blog.example.com)', 'run',
'--rm', '-p', '8002:80', ‘blog.example.com')
With this in place, when Apache is started, mod_wsgi will create a daemon process group with a single process. It will then immediately load and execute the ‘docker-admin.py’ script which in turn will execute the ‘docker' program to run up a Docker container using the image created for the backend WSGI application.
The resulting process tree would look like:
-+= 00001 root /sbin/launchd
\-+= 64263 root /usr/sbin/httpd -D FOREGROUND
|--- 64265 _www /usr/sbin/httpd -D FOREGROUND
\--- 64270 _www (docker:blog.example.com.au) run --rm -p 8002:80 blog.example.com
Of note, the ‘docker’ program was left running in foreground mode waiting for the Docker container to exit. Because it is running the Python web application, that will not occur unless explicitly shutdown.
If the container exited because the Apache instance run by mod_wsgi-express crashed for some reason, then being a managed daemon process created by mod_wsgi, it will be detected that the ‘docker’ program process had exited and a new mod_wsgi daemon process created to replace it, thereby executing the ‘docker-admin.py’ script again and so restarting the WSGI application running under Docker.
Killing the backend WSGI application explicitly by running ‘docker kill’ on the Docker instance will also cause it to exit, but again it will be replaced automatically.
The backend WSGI application would only be shutdown completely by shutting down the front end Apache itself.
Using this configuration, Apache with mod_wsgi, is therefore effectively being used as a simple process manager to startup and keep alive the backend WSGI application running under Docker. If the Docker instance exits it will be replaced. If Apache is shutdown, then so will the Docker instance.
Managing other services
Although the example here showed starting up of the WSGI application which was shifted out of the front end Apache, there is no reason that a similar thing couldn’t be done for other services being run under Docker. For example, you could create separate dummy mod_wsgi daemon process groups and corresponding scripts, to start up Redis or even a database.
Because the front end Apache is usually already going to be integrated into the operating system startup scripts, we have managed to get management of Docker containers without needing to setup a separate system to create and manage them. If you are only playing or do not have a complicated set of services running under Docker, then this could save a bit of effort and be just as effective.
With whatever the service is though, the one thing you may want to look at carefully is how a service is shutdown.
The issue here is how Apache signals the shutdown of any managed process and what happens if it doesn’t shutdown promptly.
Unfortunately how Apache does this cannot be overridden, so you do have to be mindful of it in case it would cause an issue.
Specifically, when Apache is shutdown or a restart triggered, Apache will send the ‘SIGINT’ signal to each managed child process. If that process has not shutdown after one second, it will send the signal again. The same will occur if after a total of two seconds the process hasn't shutdown. Finally, if three seconds elapsed in total, then Apache will send a ‘SIGKILL’ signal.
Realistically any service should be tolerant of being killed abruptly, but if you have a service which can take a long time to shutdown and is susceptible to problems if forcibly killed, that could be an issue and this may not be a suitable way of managing them. | http://blog.dscpl.com.au/2015/07/using-apache-to-start-and-manage-docker.html | CC-MAIN-2017-30 | refinedweb | 1,268 | 50.06 |
could someone help me with this im trying to make a program that displays five dice rolls of two dice where each die is a number from 1 to 6, and shows the total. when run, the program should look like this:
2 4= 6
1 1= 2
6 6= 12
4 3= 7
5 2= 7
Ok i got the first part i think but when i run it, it comes up with the same output everytime. also it has to be in some kind of loop. I dont want it to be the same output every time its like the randomizer isnt working. hears what i have so far:
/*Random Numbers
3/25/03 */
#include <iostream.h>
#include <math.h> //Randomizer
int main()
{
int die
for (int roll= 1; roll<= 5; roll++)
double die=1+random(6)
cout<<die<<endl;
return(0);
} | http://cboard.cprogramming.com/cplusplus-programming/36703-cplusplus-asignment-printable-thread.html | CC-MAIN-2015-18 | refinedweb | 144 | 85.93 |
Properties and Fields
Declaring Properties
Classes in Kotlin can have properties. These can be declared as mutable, using the var keyword or read-only using the val keyword.
class Address { var name: String = ... var street: String = ... var city: String = ... var state: String? = ... var zip: String = ... }
To use a property, we simply refer to it by name, as if it were a field in Java:
fun copyAddress(address: Address): Address { val result = Address() // there's no 'new' keyword in Kotlin result.name = address.name // accessors are called result.street = address.street // ... return result }
Getters and Setters
The full syntax for declaring a property is
var <propertyName>[: <PropertyType>] [= <property_initializer>] [<getter>] [<setter>]
The initializer, getter and setter are optional. Property type is optional if it can be inferred from the initializer (or from the getter return type, as shown below).
Examples:
var allByDefault: Int? // error: explicit initializer required, default getter and setter implied var initialized = 1 // has type Int, default getter and setter
The full syntax of a read-only property declaration differs from a mutable one in two ways: it starts with
val instead of
var and does not allow a setter:
val simple: Int? // has type Int, default getter, must be initialized in constructor val inferredType = 1 // has type Int and a default getter
We can write custom accessors, very much like ordinary functions, right inside a property declaration. Here's an example of a custom getter:
val isEmpty: Boolean get() = this.size == 0
A custom setter looks like this:
var stringRepresentation: String get() = this.toString() set(value) { setDataFromString(value) // parses the string and assigns values to other properties }
By convention, the name of the setter parameter is
value, but you can choose a different name if you prefer.
Since Kotlin 1.1, you can omit the property type if it can be inferred from the getter:
val isEmpty get() = this.size == 0 // has type Boolean
If you need to change the visibility of an accessor or to annotate it, but don't need to change the default implementation, you can define the accessor without defining its body:
var setterVisibility: String = "abc" private set // the setter is private and has the default implementation var setterWithAnnotation: Any? = null @Inject set // annotate the setter with Inject
Backing Fields
Classes in Kotlin cannot have fields. However, sometimes it is necessary to have a backing field when using custom accessors. For these purposes, Kotlin provides
an automatic backing field which can be accessed using the
field identifier:
var counter = 0 // the initializer value is written directly to the backing field set(value) { if (value >= 0) field = value }
The
field identifier can only be used in the accessors of the property.
A backing field will be generated for a property if it uses the default implementation of at least one of the accessors, or if a custom accessor references it through the
field identifier.
For example, in the following case there will be no backing field:
val isEmpty: Boolean get() = this.size == 0
Backing Properties
If you want to do something that does not fit into this "implicit backing field" scheme, you can always fall back to having a backing property:
private var _table: Map<String, Int>? = null public val table: Map<String, Int> get() { if (_table == null) { _table = HashMap() // Type parameters are inferred } return _table ?: throw AssertionError("Set to null by another thread") }
In all respects, this is just the same as in Java since access to private properties with default getters and setters is optimized so that no function call overhead is introduced.
Compile-Time Constants
Properties the value of which is known at compile time can be marked as compile time constants using the
const modifier.
Such properties need to fulfil the following requirements:
- Top-level or member of an
object
- Initialized with a value of type
Stringor a primitive type
- No custom getter
Such properties can be used in annotations:
const val SUBSYSTEM_DEPRECATED: String = "This subsystem is deprecated" @Deprecated(SUBSYSTEM_DEPRECATED) fun foo() { ... }
Late-Initialized Properties:
public class MyTest { lateinit var subject: TestSubject @SetUp fun setup() { subject = TestSubject() } @Test fun test() { subject.method() // dereference directly } }.
Accessing a
lateinit property before it has been initialized throws a special exception that clearly identifies the property
being accessed and the fact that it hasn't been initialized.
Overriding Properties
See Overriding Properties
Delegated Properties
The most common kind of properties simply reads from (and maybe writes to) a backing field. On the other hand, with custom getters and setters one can implement any behaviour of a property. Somewhere in between, there are certain common patterns of how a property may work. A few examples: lazy values, reading from a map by a given key, accessing a database, notifying listener on access, etc.
Such common behaviours can be implemented as libraries using delegated properties. | https://kotlinlang.org/docs/reference/properties.html | CC-MAIN-2017-13 | refinedweb | 797 | 50.87 |
#include <storagedrive.h>
Detailed Description
This device interface is available on storage devices.
A storage is anything that can contain a set of volumes (card reader, hard disk, cdrom drive...). It's a particular kind of block device.
Definition at line 37 of file ifaces/storagedrive.h.
Constructor & Destructor Documentation
Destroys a StorageDrive object.
Definition at line 23 of file ifaces/storagedrive.cpp.
Member Function Documentation
Retrieves the type of physical interface this storage device is connected to.
- Returns
- the bus type
- See also
- Solid::StorageDrive::Bus
Retrieves the type of this storage drive.
- Returns
- the drive type
- See also
- Solid::StorageDrive::DriveType
Indicates if this storage device can be plugged or unplugged while the computer is running.
- Returns
- true if this storage supports hotplug, false otherwise
Indicates if the media contained by this drive can be removed.
For example memory card can be removed from the drive by the user, while partitions can't be removed from hard disks.
- Returns
- true if media can be removed, false otherwise.
Retrieves this drives size in bytes.
- Returns
- the size of this drive
The documentation for this class was generated from the following files:
Documentation copyright © 1996-2020 The KDE developers.
Generated on Sun Feb 16 2020 04:43:47 by doxygen 1.8.11 written by Dimitri van Heesch, © 1997-2006
KDE's Doxygen guidelines are available online. | https://api.kde.org/frameworks/solid/html/classSolid_1_1Ifaces_1_1StorageDrive.html | CC-MAIN-2020-10 | refinedweb | 227 | 58.18 |
Consider I have one dataset with 40000 samples and another with 10000 samples.
And I want 80 and 20 samples per each mini-batch respectively so that in one epoch, all samples can be iterated.
What is the best way to implement?
I understand how to use my own data so I tried to use two different data loader. But I’m not sure how to iterate over two different data loader.
Consider I have one dataset with 40000 samples and another with 10000 samples.
This should help : my old answer
Would that work for you??
Thanks for the reply. I don’t understand completely yet, but is it possible to restrict the number of samples from each dataset in a mini-batch with your solution? For example, 80 from dataset 1 and 20 from dataset 2.
Elaborating : Create two
torch.utils.Dataset classes of the two different data you have. Then create a third dataset class that has it’s element instances of those 2 classes. The
__getitem__ method of this third fusion dataset class would call the 2 datasets with probability 4:1.
Or you could do something like :
def __init__(torch.utils.data.Dataset) : self.data1 = #call first instance self.data2 = #call second instance self.size1 = 80 self.size2 = 20 def __getitem__(self,index): if (index<self.size1): return self.data1[index] else: return self.data2[index-self.size1]
That’s just a rough outline, you can add more elements to the class | https://discuss.pytorch.org/t/two-different-datasets-with-different-sizes/18815 | CC-MAIN-2022-21 | refinedweb | 246 | 78.25 |
Search results
Create the page "Class" on this wiki!
Page title matches
- Timer timerRef=new(Timer); // <--creates instance of the timer class338 B (45 words) - 17:57, 7 December 2012
Page text matches
- ... the [[ToggleButton]] snippet for an example on how to subclass the Button class. public class ButtonTextures {8 KB (829 words) - 20:52, 10 January 2012
- public class GuiRatioFixer : MonoBehaviour class GuiRatioFixer (MonoBehaviour):2 KB (298 words) - 20:57, 10 January 2012
- public class MessageDisplayer : MonoBehaviour3 KB (264 words) - 20:52, 10 January 2012
- public class ShipControls : MonoBehaviour class ShipControls (MonoBehaviour):12 KB (1,056 words) - 20:57, 10 January 2012
- public class StopEmittingAfterDelay : MonoBehaviour839 B (99 words) - 20:47, 10 January 2012
- ...his script is incomplete and outdated. Use the superior [[Singleton]] base class instead.''' public class AManager : MonoBehaviour1 KB (152 words) - 06:50, 14 November 2018
- ...other common operations dealing with floating point numbers, see the Mathf class. It contains Lerp, Min, Max, Abs, Sin, and all sorts of handy math functio == I keep getting errors about my script/class types not being valid types ==4 KB (592 words) - 20:52, 10 January 2012
- public class TexturePlayback : MonoBehaviour {6 KB (764 words) - 15:39, 25 February 2013
- ...amespaces.''' A namespace is a group of classes (or 'files'). Similarly, a class is a group of methods (code). '''It's just a neat way to keep everything or ...s called "HelperClass", but there is also a "GetInfo()" method inside of a class called "Notifications"? Which one would we use?14 KB (2,338 words) - 20:12, 12 April 2016
- public class PlaceSelectionOnSurface : ScriptableObject2 KB (194 words) - 20:45, 10 January 2012
- public class Force2D:MonoBehaviour{4 KB (570 words) - 20:52, 10 January 2012
- public class LookAtCameraYonly : MonoBehaviour893 B (115 words) - 17:27, 2 February 2015
- The ToggleButton is created by extending the [[Button#C# - Button.cs|Button]] class. You'll need to have both files present in your project for this snippet to public class ToggleButton : Button {2 KB (264 words) - 20:47, 10 January 2012
- class VariableSpeedFPSWalker : MonoBehaviour4 KB (500 words) - 08:42, 9 April 2014
- * Class for handling multi-line, multi-color debugging messages. public class DebugConsole : MonoBehaviour13 KB (1,602 words) - 03:38, 1 December 2015
- public sealed class Mathfx12 KB (1,582 words) - 17:10, 18 June 2016
- * To make the class more editable, The Layout of the file is: public class SoftBodyMP : MonoBehaviour {28 KB (3,732 words) - 20:47, 10 January 2012
- public class CameraFacingBillboard : MonoBehaviour public class CameraFacingBillboard : MonoBehaviour4 KB (581 words) - 17:30, 15 September 2018
- ...d have them played/mixed on the fly. The intent was to gradually grow this class into something that would easilly allow crossfades, ducking, etc. ...lives remaining, etc. All of this state would be kept in a main controller class. This controller might also hold a reference to a JukeboxController object2 KB (264 words) - 20:45, 10 January 2012
- public class PhysicsFPSWalker : MonoBehaviour {4 KB (592 words) - 21:48, 24 October 2012
View (previous 20 | next 20) (20 | 50 | 100 | 250 | 500) | https://wiki.unity3d.com/index.php/Special:Search/Class | CC-MAIN-2021-39 | refinedweb | 509 | 58.42 |
The.
Defined tags for this resource. Each key is predefined and scoped to a namespace.
For more information, see Resource Tags.
Example:
{\"Operations\": {\"CostCenter\": \"42\"}}
A user-friendly name for the key. It does not have to be unique, and it is changeable. Avoid entering confidential information.
Free-form tags for this resource. Each tag is a simple key-value pair with no predefined name, type, or namespace.
For more information, see Resource Tags.
Example:
{\"Department\": \"Finance\"}
The OCID of the key.
The key's current lifecycle state.
Example: `ENABLED`.
The OCID of the key from which this key was restored.
The OCID of the vault that contains this key.
The OCID of the compartment that contains this master encryption key. | https://docs.oracle.com/en-us/iaas/tools/typescript/1.20.2/modules/_keymanagement_lib_model_key_.key.html | CC-MAIN-2021-25 | refinedweb | 121 | 71.41 |
ReactJS authentication gets easy if you understand just a few basic concepts. Because, let’s face it. React is the new cool kid on the block.
TL;DR: You can check out a React Flux app with authentication implemented in this Github repository
Let’s face it. React is the new cool kid on the block. Everybody is working on creating React components because it entails understanding just 2 basic concepts:
- A component is just a function
- Single-direction data flow
However, once you start creating a bigger app, you realize that just using React isn’t enough. So you start looking at Flux, which is the architecture Facebook uses to create React apps.
As we learned in a previous blog post, learning how to conduct authentication in a Single Page App can get super complex. We had to learn about tokens, JWTs and how to integrate them with SPAs. Learning how to do it with Flux is even harder! That’s why in this blogpost we’ll learn how to add authentication to a React Flux app.
"Learning how to conduct authentication in a Single Page App can get super complex"
TWEET THIS
Before we start
We’ll be coding our React app using ES6 thanks to Browserify and Babelify, and we’ll be using npm for build tools and installing dependencies. If you want to start a project with the same architecture, just clone this seed project.
Coding ReactJS Authentication!
Login page
The Login component
First, let’s create our
Login component. Its main function is rendering an input for the username and password and calling the
AuthService when the user clicks on the login button.
// ... imports export default class Login extends React.Component { constructor() { this.state = { user: ‘’, password: ‘’ }; } // This will be called when the user clicks on the login button login(e) { e.preventDefault(); // Here, we call an external AuthService. We’ll create it in the next step Auth.login(this.state.user, this.state.password) .catch(function(err) { console.log(“Error logging in”, err); }); } render() { return ( <form role=“form”> <div className=“form-group”> <input type=“text” valueLink={this.linkState(‘user’)}placeholder=“Username” /> <input type=“password” valueLink={this.linkState(‘password’)} placeholder=“Password” /> </div> <button type=“submit” onClick={this.login.bind(this)}>Submit</button> </form> </div> ); } } // We’re using the mixin `LinkStateMixin` to have two-way databinding between our component and the HTML. reactMixin(Login.prototype, React.addons.LinkedStateMixin);
The AuthService & the LoginAction
Our AuthService is in charge of calling our login API. The server will validate the username and password and return a token (JWT) back to our app. Once we get it, we’ll create a LoginAction and send it to all the Stores using the Dispatcher from Flux.
// AuthService.js // ... imports class AuthService { login(username, password) { // We call the server to log the user in. return when(request({ url: ‘', method: ‘POST’, crossOrigin: true, type: ‘json’, data: { username, password } })) .then(function(response) { // We get a JWT back. let jwt = response.id_token; // We trigger the LoginAction with that JWT. LoginActions.loginUser(jwt); return true; }); } } export default new AuthService()
// LoginAction.js // ... imports export default { loginUser: (jwt) => { // Go to the Home page once the user is logged in RouterContainer.get().transitionTo(‘/‘); // We save the JWT in localStorage to keep the user authenticated. We’ll learn more about this later. localStorage.setItem(‘jwt’, jwt); // Send the action to all stores through the Dispatcher AppDispatcher.dispatch({ actionType: LOGIN_USER, jwt: jwt }); } }
You can take a look at the router configuration on Github, but it’s important to note that once the
LoginAction is triggered, the user is successfully authenticated. Therefore, we need to redirect him or her from the Login page to the Home. That’s why we’re adding the URL transition in here.
The LoginStore
The Login.
// ... imports class LoginStore extends BaseStore { constructor() { // First we register to the Dispatcher to listen for actions. this.dispatchToken = AppDispatcher.register(this._registerToActions.bind(this)); this._user = null; this._jwt = null; } _registerToActions(action) { switch(action.actionType) { case USER_LOGGED_IN: // We get the JWT from the action and save it locally. this._jwt = action.jwt; // Then we decode it to get the user information. this._user = jwt_decode(this._jwt); // And we emit a change to all components that are listening. // This method is implemented in the `BaseStore`. this.emitChange(); break; default: break; }; } // Just getters for the properties it got from the action. get user() { return this._user; } get jwt() { return this._jwt; } isLoggedIn() { return !!this._user; } } export default new LoginStore();
You can take a look at the
BaseStorein Github. It includes some utility methods that all stores will have.
Displaying the user information
Creating an Authenticated component
Now, we can start creating components that require authentication. For that, we’ll create a wrapper (or decorator) component called
AuthenticatedComponent. It’ll make sure the user is authenticated before displaying its content. If the user isn’t authenticated, it’ll redirect him or her to the Login page. Otherwise, it’ll send the user information to the component it’s wrapping:
// ... imports export default (ComposedComponent) => { return class AuthenticatedComponent extends React.Component { static willTransitionTo(transition) { // This method is called before transitioning to this component. If the user is not logged in, we’ll send him or her to the Login page. if (!LoginStore.isLoggedIn()) { transition.redirect(‘/login’); } } constructor() { this.state = this._getLoginState(); } _getLoginState() { return { userLoggedIn: LoginStore.isLoggedIn(), user: LoginStore.user, jwt: LoginStore.jwt }; } // Here, we’re subscribing to changes in the LoginStore we created before. Remember that the LoginStore is an EventEmmiter. componentDidMount() { LoginStore.addChangeListener(this._onChange.bind(this)); } // After any change, we update the component’s state so that it’s rendered again. _onChange() { this.setState(this._getLoginState()); } componentWillUnmount() { LoginStore.removeChangeListener(this._onChange.bind(this)); } render() { return ( <ComposedComponent {...this.props} user={this.state.user} jwt={this.state.jwt} userLoggedIn={this.state.userLoggedIn} /> ); } } };
An interesting pattern is used here.
First, take a look at what we’re exporting. We’re exporting a function that receives a Component as a parameter and then returns a new Component that wraps the one that was sent as an argument.
Next, take a look at the
render method. There, we’re rendering the Component we received as a parameter. Besides the
props it should receive, we’re also sending it all the user information so it can use those properties.
Now, let’s create the Home component which will be wrapped by the
AuthenticatedComponent we’ve just created.
The
Home will display user information. As it’s wrapped by the
AuthenticatedComponent, we can be sure of 2 things:
- Once the
rendermethod is called on the
Homecomponent, we know the user is authenticated. Otherwise, the app would have redirected him to the
Loginpage.
- We know we’ll have the user information under
propsbecause we’ve received them from the
AuthenticatedComponent
// ... imports // We’re wrapping the home with the AuthenticatedComponent export default AuthenticatedComponent(class Home extends React.Component { render() { // Here, we display the user information return (<h1>Hello {this.props.user.username}</h1>); } });
Let’s call an API!
Now, you should be able to call an API. In order to call an API that requires authentication, you must send the JWT we received on Login in the
Authorization header. Any
AuthenticatedComponent has access to this JWT so you can do something as follows:
// Home.jsx // It must be on an AuthenticatedComponent callApi() { fetch(‘', { method: ‘GET’, headers: { Authorization: ‘Bearer ‘ + this.props.jwt } }
Keeping the user authenticated
Now that the user is authenticated, we want to keep him or her authenticated instead of showing the login page every time he refreshes the website.
Due to the fact we’re saving the JWT on
localStorage after a successful authentication, we can manually trigger the
LoginAction and everything will work. That’s the beauty of using Flux.
// app.jsx ==> Bootstrap file let jwt = localStorage.getItem(‘jwt’); if (jwt) { LoginActions.loginUser(jwt); }
Aside: Using React React. You can read the documentation here or you can checkout the Github example
Closing remarks
We’ve finished implementing the Login for a React Flux app. If you want to know how to implement a signup or if you want to see the full example at work, you can grab the code from Github.
Happy Hacking! :). | https://auth0.com/blog/adding-authentication-to-your-react-flux-app/ | CC-MAIN-2017-04 | refinedweb | 1,362 | 50.63 |
I was thinking about how you'd get Silverlight to drive interaction with a Windows Workflow and thought I'd make a stab at that here.
Keeping it very simple, imagine that I have 5 images on my web server image1 to image5 and I want a Silverlight client to display them in order, one after another and I want to control this with my Workflow.
The Workflow instance will be activated by Silverlight and it'll return the first image name and then Silverlight will call back into the Workflow instance and the instance will move the client through image 2,3,4,5 and then the instance will end.
Whilst this isn't a very complicated scenario, it does model the idea that we have a web client that we cannot contact (i.e. it's pull only from the client end) and so the client is going to have to poll and we want to make sure that the client is directed back into the same Workflow instance that it started originally.
First off, I built a WCF interface to model this. This looks like;
namespace ImageWorkflowLibrary
{
[ServiceContract(Namespace="")]
public interface ISelectPicture
{
[OperationContract]
[WebInvoke(
Method = "POST", // For the moment - not sure if I can make "GET" work
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
string GetNextPicture();
}
}
And then I can go and build a simple Workflow around that which looks like this;
Now, let me explain some things about this Workflow. It's just a loop. So, that first activity is a Receive activity. It receives a GetNextPicture message and it responds with a string (I have bound this to a property called ReturnImageName of type string in the Workflow). In the workflow, this is just an array;
private static string[] images = new string[]
"image1.jpg",
"image2.jpg",
"image3.jpg",
"image4.jpg",
"image5.jpg"
};
and the Workflow has a member of type int called currentIndex and all it's doing is returning the items from that array one by one as it gets called. That loop on the right hand side will loop up to 4 times to index into that array and the parallel delay on the left hand side will kill the Workflow after 2 minutes elapse.
So, that's all fine and dandy.
I now want to deploy this Workflow inside of IIS so I add a new WCF web service project to my solution (remembering to run VS as administrator) and I add a reference to my Workflow library from there and I edit the file Service.svc to point at my Workflow and the WorkflowServiceHostFactory.
<%@ ServiceHost Factory="System.ServiceModel.Activation.WorkflowServiceHostFactory" Language="C#" Debug="true" Service="ImageWorkflowLibrary.Workflow" %>
<%@ ServiceHost Factory="System.ServiceModel.Activation.WorkflowServiceHostFactory" Language="C#" Debug="true" Service="ImageWorkflowLibrary.Workflow" %>
I start to hit a few "problems". I want to use the context stuff inside of Workflow which will automatically route WCF messages to the correct Workflow instance based on either a SOAP header or an HTTP cookie. In trying to put this together with the webHttpBinding that I'm using which makes WCF speak "JSON" I find that, whilst there is a netTcpContextBinding and a wsHttpContextBinding, there isn't a webHttpContextBinding so there's nothing that puts together the "HTTP-ness" along with the "contextual-ness" :-)
I figure that I'll try and make my own custom binding which does this and I do ultimately come up with a configuration that seems to work;
<system.serviceModel>
<services>
<service name="ImageWorkflowLibrary.Workflow" behaviorConfiguration="ServiceBehavior">
<endpoint address=""
binding="customBinding"
contract="ImageWorkflowLibrary.ISelectPicture"
bindingConfiguration="myBinding"
behaviorConfiguration="myBehaviour"/>
</service>
</services>
<bindings>
<customBinding>
<binding name="myBinding">
<context contextExchangeMechanism="HttpCookie"/>
<webMessageEncoding/>
<httpTransport manualAddressing="true"/>
</binding>
</
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
So, you can see that I've tried to make a custom binding which does http + webMessageEncoding + context and that context is trying to use an HttpCookie to exchange the context token (i.e. identifying the workflow instance and the particular receive activity) and I've also added the webHttp behaviour.
With that in place, I managed to get a WSDL out of the service so I go and build a Silverlight client for it.
I add a new Silverlight project, make a link from the web site to the Silverlight project and move the .html and .js files from the Silverlight project to the web one to ensure that I'm always running the web site rather than the Silverlight project (to avoid all those "cross-site" hiccups).
I then go and do an Add Web Reference from my Silverlight project to my web service and........."it works". I was kind of amazed by that but there you go. Especially because VS raised a lot of scary dialogs doing it.
However, with that web reference in place I realise I have two problems with the proxy I've got;
At this point, I decide to ditch "Add Web Reference" and go for my own version using BrowserHttpWebRequest.
Having moved to BrowserHttpWebRequest, it doesn't look like it deals with Cookies either. There's a CookieContainer property on BrowserHttpWebRequest but that looks to be of type object so I'm not sure what to do with it - turns out that this is not implemented at this point.
The response that you get back from a BrowserHttpWebRequest, the HttpWebResponse, does not seem to have a cookies collection at all so it's not clear how to use that either.
In the end I spent quite a bit of time on cookie handling here. As far as I know;
So, in the end it works out ok with a bit of stress-and-strain along the way. The client bits ended up looking like this;
And I've dropped the projects that I use onto the website here for download. Bear in mind, this is nearer to hacking than it is to "best practise" but there are perhaps some Alpha things that needed to be worked around. There are 3 projects - Workflow, Silverlight and the Web Site itself which I was using from IIS. | http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2007/08/13/9583.aspx | crawl-002 | refinedweb | 1,009 | 58.82 |
-- Michael Hartle wrote:
>
> Stefano Mazzocchi wrote:
>
> >>large CWAs are going to happen (they will, right ?), the sheer length of
> >>the list of "parameters" for customizing them could well justify this
> >>approach.
> >>
> >Well, I don't think the number of parameters depend on the size of the
> >CWA being deployed and I don't think I get your point.
> >
> With "large" CWAs I meant possibly as complex systems as project
> management, groupware or financial/commercial components. The interest
> in developing off-the-shelf drop-in CWAs that can be composed and
> interconnected will more likely lead to more configuration options
> (parameters) than not. Maybe you have another estimation on that.
To be honest, I think it will depend, but generally, I'd tend to assume
that rather than passing tons of parameters, one might pass the name of
the directory server (or other type of repository) that contains them.
But I might well be wrong.
> If those configuration options/parameters are not being passed or
> maintained by defined means of Cocoon, each CWA will solve this problem
> on their own by web forms or seperate configuration files, unnecessarily
> duplicating work of developers and maybe hinder the use of CWAs.
Here I completely agree.
We'll see: if a small number of configurations are required for each
CWA, then a 'lookup' on a configuration registry is, IMO, the way to go.
If, on the other hand, a massive flow of highly structured and possibly
namespaced configurations will be required (but I'd suggest against it
unless we want to deal with broken contracts between CWAs), then a IoC
mechanism will be better suited.
> >>This would even allow passing on an instance of configuration source to
> >>the CWA, this instance implementing some ConfigurationSource-interface -
> >>be aware that I am not sure whether such an interface or class with this
> >>name is already existing, and I am not knowingly referring to anything
> >>here as I just made a wild guess how this could be named. This might be
> >>an LDAPConfigurationSource or a FileConfigurationSource, being able to
> >>deliver arbitrary configuration information to the CWA as a stream of
> >>SAX events.
> >>
> >
> >Normally, configurations are strings or numbers. Do you really want to
> >receive a stream of SAX events that you have to write your own code to
> >interpret, instead of being able to simply *ask* a configuration
> >repository for the configuration you want?
> >
> I think we basically misunderstood each other in respect to the amount
> of information that may be required as configuration for a CWA; I so far
> am thinking that this might not be done with passing 2 or 3 name/value
> pairs to any app. I consider the term configuration to be a potentially
> hierarchical collection of one or more key/value combinations.
>
> Ok, I agree with you on the part that many small and simple applications
> will be satisfied with just asking for one or two strings or numbers.
> Why not basically use SAX events, giving small applications some utility
> classes at hand that helps doing exactly and solely this while
> developers of more complex apps might decide for themselves what they need ?
I'm not against using SAX 'per se'. I'm more against passing a high
number of parameters and making it easier for the CWA developer to
receive a load of them... but this is unless talking without real-life
examples.
Anyway, I think of CWA as the web equivalent of avalon blocks and blocks
receive a configuration instance that incapsulates the conf structure
they need and the block queries the configuration it needs.
I fail to see why such a system cannot scale with the amount of
configurations required by CWA. In fact, directory servers was created
exactly to allow tree-like structures to scale (given the difficulty of
providing a fast relational view of a tree).
Also, as a developer, I would not find it easier to have to intercept a
bunch of SAX events, store them someplace, retrieve them later and
manage their caching/lookup-strategy, etc...
I'd rather receive a configuration repository with a solid hierarchical
structure and pruned for my own configurations, then ask for what I need
when I need it without caring about how to get it.
Admittedly, this is not IoC since you are calling directly an API, but
there are situations where normal flow of control is preferrable and
this is, IMO, one of such places.
> >>And those ConfigurationSource's could be defined in the
> >>sitemap and being configured with parameters when needed. Hey, why not
> >>simply consider different configuration sources as sources for SAX
> >>events directly ?
> >>
> >Because this is exactly what flexiblity syndrome looks like: when you
> >have a hammer in your hand, everything looks like a nail.
> >
> I rather like to open-mindedly check everything in advance before
> stepping into nails; this does not necessarily mean that this
> flexibility needs to be exercised all the way through, but left as a
> possible way to go in case it is needed.
Absolutely.
> >>>each CWA indicates
> >>> o its role as a URI ()
> >>>
> What about putting the version in major.minor format into the URI, like
> it is being done with namespace URIs like
> "" or
> "" ?
Yes, this is another alternative and might appear more coherent with our
use of namespace URIs if we all start using them correctly: means that
we *must* make sure that version numbers maintain their semantic meaning
that if major numbers are equal, namespaces are compatible, otherwise
they are not.
> >>I am always fearful of prompts that do something for me that I may not
> >>have understood completely.
> >>
> >This is why the CWA will also contain a description of the configuration
> >that you are being asked to provide.
> >
> I will correct my sentence: I am always fearful of automated processes
> and prompts that do something for me that I should at least once have
> done for myself manually in order to understand it completely.
Ok, got your feeling and I think you raise a good cognitive point: who
should we address this mechanism? people used to install and configurre
software with point and click installers and GUI tools (admittedly, I'm
one of those) or people used to install software from the command line
and configure it thru text editing?
I think we should target both, mostly because that will make it easier
for people coming on the server market from non-unix backgrounds
(admittedly, I'm one of those, again) to install, configure and create
their own complex website using our lego-like CWA components.
And, BTW, MacOSX shows that having two choices (GUIs and CLIs) gives you
such a great feeling of ease-of-use without sacrificing the power to
control the system at the very granular level of single configurations.
> >>Do we speak of a solely installer-based
> >>approach here or might this allow the admin to just drop-in the .cwa
> >>file and add an entry to the sitemap without anything able to directly
> >>prompt at all ?
> >>
> >As you guys wish, I don't see any reason to force one behavior or the
> >other.
> >
> I think the installer-based approach with prompting the user is
> something to be left for a seperate deployment tool.
It might be, but it has to connect directly to the system and people
will trust less a package that you have to install afterwords and has to
connect to cocoon core to operate.
If we had such a tool, I'd rather ship it with cocoon while letting you
turn it off (for whatever reason).
> >>We should give the administrator a way to explicitly name a certain
> >>instance, leaving the administrator the choice between automatic
> >>GUI-driven and good-old vi-driven approaches, as the admin can partially
> >>or completely override the naming scheme and refer CWA dependencies to
> >>their targets manually. Whenever people would use the dynamic naming
> >>scheme to ensure multiple installations do not collide, they show a
> >>certain lack of interest to make sure they connect CWA dependencies
> >>correctly.
> >>
> >You got the wrong perception here, since I'm trying to help
> >administrators instead of doing stuff for them behind their backs. But
> >if you don't like that, fine, you'll always have the good old
> >configuration files to modify by hand.
> >
> Helping administrators is a good thing and will certainly be rewarded; I
> am by no means having a vi fetish, but I think that being able to modify
> the configurations by hand has its advantages such as speed.
Agreed.
Believe me: even if I was raised on GUIs and still know only a few basic
VI commands, I do appreciate the power of being able to reconfigure a
server by simply editing a few lines you know very well and without
going to a nightmare of clicks.
But on the other hand, newbies or people not really "deep" into that,
might just want a nice and simple visual interface to do their stuff and
start learning.
Don't worry, we won't sacrifice one for the | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200110.mbox/%3C3BC1D759.7B9080C8@apache.org%3E | CC-MAIN-2015-18 | refinedweb | 1,504 | 53.95 |
To skip this tutorial, feel free to download the source code from my Github repo here.
I’ve been asked by a few friends to develop a feature for a WhatsApp chatbot of mine, that summarizes articles based on URL inputs. So when a friend sends an article to a WhatsApp group, the bot will reply with a summary of the given URL article. I like this feature because from my personal research, 65% of group users don’t even click the shared URLs, but 97% of them will read a few lines of the articles summary.
As part of being a Fullstack developer, it is important to know how to choose the right stack for each product you develop, depending on the requirements and limitations. For web crawling, I love using Python. The Python community is filled with efficient, easy to implement open source libraries both for web crawling and text summarization. Once you’re done with this tutorial, you won’t believe how simple it is to implement the task.
GETTING STARTED
For this tutorial, we’ll be using two Python libraries:
- Web crawling - Beautiful Soup. Beautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree. It commonly saves programmers hours or days of work.
- Text summarization -.
Go ahead and get familiar with the libraries before continuing, and also make sure to install them locally. If you’re having trouble installing the libraries, follow this commands in your Terminal:
pip install beautifulsoup4 pip install -U nltk pip install -U numpy pip install -U setuptools pip install -U sumy
After that, open Python command line and enter:
import nltk nltk.download(“stopwords”)
THE ALGORITHM
Lets describe the algorithm:
- Get URL from user input
- Web crawl to extract the natural language from the URL html (by paragraphs <p>).
- Execute the summarize class algorithm (implemented using NLTK) on the extracted sentences.
- The algorithm ranks sentences according to the frequency of the words they contain, and the top sentences are selected for the final summary.
- Return the highest ranked sentences (I prefer 5) as a final summary.
For section 2 (1 is self explanatory), we’ll develop a method called getTextFromURL as shown below:
def getTextFromURL(url): r = requests.get(url) soup = BeautifulSoup(r.text, "html.parser") text = ' '.join(map(lambda p: p.text, soup.find_all('p'))) return text
The method initiates a get request to the given URL, and returns the extracted natural language from the URL html page.
For sections 3-4, we’ll develop a method called summarizeURL as shown below:
def summarizeURL(url, total_pars): url_text = getTextFromURL(url).replace(u"Â", u"").replace(u"â", u"") fs = FrequencySummarizer() final_summary = fs.summarize(url_text.replace("\n"," "), total_pars) return " ".join(final_summary)
The method calls the method above to retrieve the text, and clean it from html characters and trailing new lines (\n). Secondly, execute the Summarize algorithm (inspired by this post) on the given text, which then returns a list with the highest ranked sentences which is our final summary.
SUMMARY
That’s it! Try it out with any URL and you’ll get a pretty decent summary. The algorithm proposed in this article as as stated, inspired by this post, which implements a simple text summarizer using the NLTK library. There are many summarization algorithms which have been proposed in recent years, and there’s no doubt there are even better solutions. If you have any suggestions, recommendations I’de love to hear about them so comment below!
Feel free to download directly the source code via my Github account. | http://www.assafelovic.com/blog/2016/10/26/url-text-summarizer-using-web-crawling-and-nlp-python | CC-MAIN-2018-47 | refinedweb | 612 | 53.81 |
OData.
Introduction
OData.
What is OData?
OData stands for Open Data Protocol. OData allows you to create REST based data services by exposing HTTP end points. In other words, you use standard URL syntax to query data residing on the server. OData queries consist of one or more Query Options. A query option is a sort of keyword that begins with $. For example, $top query option is used to indicate that top n records are to be fetched from the server. Just to show how an OData query looks, check out the following query:
The above OData query consists of two query options namely $top and $orderby. The query options are passed in the query string to a resource just like any other URL. Their use is quite obvious. The above query will return the top 10 records from a given result set and the results will be sorted by country in ascending order.
Web API Support for OData Queries
ASP.NET Web API supports OData queries with certain limitations. Note that OData support in Web API is still evolving and the supported feature set may change by the time the final version is released. The following OData query options are commonly used and are supported by Web API:
- $top : Can be used to retrieve top n records from a data store.
- $orderby : Can be used to sort the data in ascending or descending order.
- $filter : Can be used to filter the data based on some condition.
- $skip : Can be used along with $orderby to skip certain number of records.
In order to use OData queries in ASP.NET Web API you need to install Microsoft ASP.NET Web API OData NuGet package in an ASP.NET MVC 4 Web API project. So, first of all create a new ASP.NET MVC 4 Web API project in Visual Studio. Then select Project > Manage NuGet Packages menu option and search for Microsoft.AspNet.WebApi.OData. The following figure shows the said NuGet package ready to be installed.
Manage NuGet Package
This will install all the necessary assemblies that you need.
Creating a Sample Web API
Now let's create a simple Web API that exposes data from the Customers table of the Northwind database. Begin by adding a new Entity Framework Data Model for the Customers table in the Models folder of the project (see below).
Add a New Entity Framework Data Model
Next, open the Web API controller class (ValuesController) and change its name as CustomersController. Notice that the CustomersController class inherits from ApiController base class. Modify the CustomersController class as shown below:
public class CustomersController : ApiController { [Queryable] public IQueryable<Customer> Get() { NorthwindDbEntities db=new NorthwindDbEntities(); return db.Customers; } }
As you can see the CustomersController class contains a single method Get() that returns IQueryable collection of Customer objects. More importantly the Get() method is marked with the [Queriable] attribute. The [Queryable] attribute enables the OData support in Web API so that you can issue OData queries.
That's all you need to do in your Web API to enable OData query support.
Issuing OData Queries from jQuery
Now let's issue some OData queries to the Web API you just developed. Run the Web API project so that a browser window is opened and the default Web API page is shown. Enter the following queries in the browser address bar and observe the output returned in the browser for each query.
1.
2.
3. desc&$top=3
4. eq 'USA'
5.
You will find that each of the queries returns results in XML format as shown in the following figure.
Each of the Queries Returns Results in XML Format
If you issue the same queries via jQuery code the data is returned as JSON and you can access the individual Customer objects just like any other JSON object.
The following view shows how OData queries can be issued using jQuery.
OData Queries can be Issued Using jQuery
The main functionality of the view goes in the click event handler of the Select button. This event handler is shown below:
$("#Button1").click(function () { var url = "api/customers?"; if ($("#Text1").val() != '') { url += "$top=" + $("#Text1").val() + "&"; } if ($("#Text2").val() != '') { url += "$filter=Country%20eq%20'" + $("#Text2").val() + "'&"; } if ($("#Select1").val() != '') { url += "$orderby=" + $("#Select1").val(); } $.getJSON(url, LoadCustomers); });
As you can see the click event handler of the Select button essentially forms the same OData queries as before but this time the queries are issued using the $.getJSON() method of jQuery. If you wish you can also use $.ajax() instead of $.getJSON() method. The $.getJSON() method accepts the URL that is supposed to be requested (OData end point in this case) and a callback function to handle the returned data.
The callback function LoadCustomers looks as follows:
function LoadCustomers(data) { $("#customerTable").find("tr:gt(0)").remove(); $.each(data, function (key, val) { var tableRow = '<tr>' + '<td>' + val.CustomerID + '</td>' + '<td>' + val.CompanyName + '</td>' + '<td>' + val.ContactName + '</td>' + '<td>' + val.Country + '</td>' + '</tr>'; $('#customerTable').append(tableRow); }); }
The LoadCustomers() function receives the Customer JSON objects as the data parameter. The function essentially fills the data in a table with ID customerTable.
Summary
ASP.NET Web API offers support to OData queries. OData query support in Web API comes from the [Queryable] attribute. Currently the OData support is still in an evolving state and many more features may be added before the final release. OData queries are a part of the supported features that allows you to query data using URIs.. | https://mobile.codeguru.com/csharp/.net/working-with-odata-queries-in-asp.net-web-api.htm | CC-MAIN-2019-09 | refinedweb | 912 | 66.94 |
In the last post, I talked about imaginary numbers, complex numbers, and how to use them to rotate vectors in 2d.
In this post, I want to share another interesting type of number called a “Dual Number” that uses the symbol ε (epsilon) and has a neat trick of automatically calculating the derivative of a function while you calculate the value of the function at the same time.
Dual numbers are pretty similar to imaginary numbers but there is one important difference. With imaginary numbers, i^2 = -1, but with dual numbers, ε^2 = 0 (and ε is not 0!). That may seem like a small difference, but oddly, that opens up a whole interesting world of mathematical usefulness.
Before we dig into automatic differentiation, I want to go over the mathematical basics for how dual numbers behave.
Basic Dual Number Math
Adding dual numbers is the same as adding complex numbers; you just add the real and dual parts separately:
(3 + 4ε) + (1 + 2ε) = 4 + 6ε
Subtraction works the same way as well:
(3 + 4ε) – (1 + 2ε) = 2 + 2ε
To multiply dual numbers, you use F.O.I.L. just like you do with complex numbers:
(3 + 4ε) * (1 + 2ε) =
3 + 6ε + 4ε + 8ε^2 =
3 + 10ε + 8ε^2
However, since ε^2 is zero, the last term 8ε^2 disappears:
3 + 10ε
It’s interesting to note that with complex numbers, the i^2 became -1, so the last term changed from imaginary to real, meaning that the imaginary numbers fed back into the real numbers during multiplication. With dual numbers, that isn’t the case, the dual numbers don’t feed back into the real numbers during multiplication.
In both complex and dual numbers the real terms do affect the non real terms during multiplication.
The division operator relates to the conjugate. I have source code for it below, and some of the links at the end of the post go into the details of that and other operations.
Quick Review: Derivatives (Slope)
If you know the line formula y=mx+b, but you don’t know what a derivative is you are in luck. Remember how “m” is the slope of the line, specifying how steep it is? That is what the derivative is too, it’s just the slope.
Below is a graph of y=2x+1. At every point on that line, the derivative (or slope) is 2. That means that for every step we make on the x axis to the right (positive direction), we make 2 steps up on the y axis (positive direction).
Now, check out this graph of y=x^2-0.2
The derivative (or slope) at every point on this graph is 2x. That means that the slope changes depending on where the x coordinate is!
So, when x=0, the slope is 0. You can see that in the graph where x=0, that it is horizontal, meaning that a step on the x axis becomes no steps on the y axis (only at that point where x is 0, and only if you take an infinitely small step).
When x is 1, the slope is 2, when x is 2, the slope is 4, when x is 3, the slope is 6. Since the numbers increase as we increase x from 0, that tells us that the graph gets steeper as we go to the right, which you can see in the graph.
Alternately, when x is -1, the slope is -2, when x is -2, the slope is -4, and when x is -3, the slope is -6. This shows us that as we decrease x from 0, the graph gets steeper in the opposite direction, which you can see in the graph as well.
What is Automatic Differentiation?
Let’s say you have a function (possibly a curve) describing the path of a rocket, and you want to make the rocket point down the path that it’s traveling.
One way you might do this is to evaluate your function f(T) to get the current location of your rocket (where T is how long the rocket has been flying), and then calculate the derivative f'(T) to find the slope of the graph at that point so that you can orient the rocket in that direction.
You could calculate the value and slope of the function at time T independently easily enough if you know how to get the derivative of a function (a calculus topic), or use wolframalpha.com.
However, if you have a complex equation, or maybe if the equation is controlled by user input, or game data, it might not be so easy to figure out what the derivative is at run time.
For instance… imagine having a function that rolled random numbers to figure out what mathematical operation it should preform on a number next (if we roll a 0, add 3, if we roll a 1 multiply by 2, if we roll a 2, square the number… etc). It isn’t going to be simple to take the derivative of the same mathematical function.
Here enters automatic differentiation (or AD). AD lets you calculate the derivative WHILE you are calculating the value of the function.
That way, you can do whatever math operations you want on your number, and in the end you will have both the value of f(T) as well as the derivative f'(T).
Using ε for Automatic Differentiation
You can use dual number operations on numbers to calculate the value of f(x) while also calculating f'(x) at the same time. I’ll show you how with a simple example using addition and multiplication like we went over above.
We’ll start with the function f(x)=3x+2, and calculate f(4) and f'(4).
the first thing we do is convert our 4 into a dual number, using 1 for the dual component, since we are plugging it in for the value of x, which has a derivative of 1.
4+1ε
Next, we want to multiply that by the constant 3, using 0 for the dual component since it is just a constant (and the derivative of a constant is 0)
(4+1ε) * (3 + 0ε) =
12 + 0ε + 3ε + 0ε^2 =
12 + 3e
Lastly, we need to add the constant 2, using 0 again for the dual component since it’s just a constant.
(12 + 3ε) + (2 + 0ε) =
14 + 3ε
In our result, the real number component (14) is the value of f(4) and the dual component (3) is the derivative f'(4), which is correct if you work it out!
Let’s try f(5). First we convert 5 to a dual number, with the dual component being 1.
5 + 1ε
Next we need to multiply it by the constant 3 (which has a dual component of 0)
(5 + 1ε) * (3 + 0e) =
15 + 0ε + 3ε + 0ε^2 =
15 + 3ε
Now, we add the constant 2 (which has a dual component of 0 again since it’s just a constant)
(15 + 3ε) + (2 + 0ε) =
17 + 3ε
So, our answer says that f(5) = 17, and f'(5) = 3, which again you can verify is true!
Quadratic Example
The example above worked well but it was a linear function. What if we want to do a function like f(x) = 5x^2 + 4x + 1?
Let’s calculate f(2). We are going to first calculate the 5x^2 term, so we need to start by making a dual number for the function parameter x:
(2 + 1ε)
Next, we need to multiply it by itself to make x^2:
(2 + 1ε) * (2 + 1ε) =
4 + 2ε + 2ε + 1ε^2 =
4 + 4ε
(remember that ε^2 is 0, so the last term disappears)
next, we multiply that by the constant 5 to finish making the 5x^2 term:
(4 + 4ε) * (5 + 0ε) =
20 + 0ε + 20ε + 0ε^2 =
20 + 20ε
Now, putting that number aside for a second we need to calculate the “4x” term by multiplying the value we plugged in for x by the constant 4
(2 + 1ε) * (4 + 0ε) =
8 + 0ε + 4ε + 0ε^2 =
8 + 4ε
Next, we need to add the last 2 values together (the 5x^2 term and the 4x term):
(20 + 20ε) + (8 + 4ε) =
28 + 24ε
Lastly, we need to add in the last term, the constant 1
(28 + 24ε) + (1 + 0ε) =
29 + 24e
There is our answer! For the equation y = 5x^2 + 4x + 1, f(2) = 29 and f'(2) = 24. Check it, it’s correct (:
As one last example let’s calculate f(10) and f'(10) with the same function above y = 5x^2 + 4x + 1.
First, to start calculating the 5x^2 term, we need to make 10 into a dual number and multiply it by itself to make x^2:
(10 + 1ε) * (10 + 1ε) =
100 + 10ε + 10ε + 1ε^2 =
100 + 20ε
Next, we multiply by the constant 5 to finish making the 5x^2 term:
(100 + 20ε) * (5 + 0ε) =
500 + 0ε + 100ε + 0ε^2 =
500 + 100ε
Putting that aside, let’s calculate the 4x term by multiplying our x value by the constant 4:
(10 + 1ε) * (4 + 0ε) =
40 + 0ε + 4ε + 0ε^2 =
40 + 4ε
Lastly, let’s add our terms: 5x^2, 4x and the constant 1
(500 + 100ε) + (40 + 4ε) + (1 + 0ε) =
541 + 104ε
The answer tells us that for the equation y = 5x^2 + 4x + 1, f(10) = 541 and f'(10) = 104.
Sample Code
There are lots of other mathematical operations that you can do with dual numbers. I’ve collected as many as I was able to find and made up some sample code that uses them. The sample code is below, as well as the program output.
#include <stdio.h> #include <math.h> #define PI 3.14159265359f // In production code, this class should probably take a template parameter for // it's scalar type instead of hard coding to float class CDualNumber { public: CDualNumber (float real = 0.0f, float dual = 0.0f) : m_real(real) , m_dual(dual) { } float Real () const { return m_real; } float Dual () const { return m_dual; } private: float m_real; float m_dual; }; //---------------------------------------------------------------------- // Math Operations //----------------------------------------------------------------------.Real() * b.Dual() + a.Dual() * b.Real() ); } inline CDualNumber operator / (const CDualNumber &a, const CDualNumber &b) { return CDualNumber( a.Real() / b.Real(), (a.Dual() * b.Real() - a.Real() * b.Dual()) / (b.Real() * b.Real()) ); } inline CDualNumber sqrt (const CDualNumber &a) { float sqrtReal = ::sqrt(a.Real()); return CDualNumber( sqrtReal, 0.5f * a.Dual() / sqrtReal ); } inline CDualNumber pow (const CDualNumber &a, float y) { return CDualNumber( ::pow(a.Real(), y), y * a.Dual() * ::pow(a.Real(), y - 1.0f) ); } inline CDualNumber sin (const CDualNumber &a) { return CDualNumber( ::sin(a.Real()), a.Dual() * ::cos(a.Real()) ); } inline CDualNumber cos (const CDualNumber &a) { return CDualNumber( ::cos(a.Real()), -a.Dual() * ::sin(a.Real()) ); } inline CDualNumber tan (const CDualNumber &a) { return CDualNumber( ::tan(a.Real()), a.Dual() / (::cos(a.Real()) * ::cos(a.Real())) ); } inline CDualNumber atan (const CDualNumber &a) { return CDualNumber( ::atan(a.Real()), a.Dual() / (1.0f + a.Real() * a.Real()) ); } inline CDualNumber SmoothStep (CDualNumber x) { // f(x) = 3x^2 - 2x^3 // f'(x) = 6x - 6x^2 return x * x * (CDualNumber(3) - CDualNumber(2) * x); } //---------------------------------------------------------------------- // Test Functions //---------------------------------------------------------------------- void TestSmoothStep (float x) { CDualNumber y = SmoothStep(CDualNumber(x, 1.0f)); printf("smoothstep 3x^2-2x^3(%0.4f) = %0.4f\n", x, y.Real()); printf("smoothstep 3x^2-2x^3'(%0.4f) = %0.4f\n\n", x, y.Dual()); } void TestTrig (float x) { CDualNumber y = sin(CDualNumber(x, 1.0f)); printf("sin(%0.4f) = %0.4f\n", x, y.Real()); printf("sin'(%0.4f) = %0.4f\n\n", x, y.Dual()); y = cos(CDualNumber(x, 1.0f)); printf("cos(%0.4f) = %0.4f\n", x, y.Real()); printf("cos'(%0.4f) = %0.4f\n\n", x, y.Dual()); y = tan(CDualNumber(x, 1.0f)); printf("tan(%0.4f) = %0.4f\n", x, y.Real()); printf("tan'(%0.4f) = %0.4f\n\n", x, y.Dual()); y = atan(CDualNumber(x, 1.0f)); printf("atan(%0.4f) = %0.4f\n", x, y.Real()); printf("atan'(%0.4f) = %0.4f\n\n", x, y.Dual()); } void TestSimple (float x) { CDualNumber y = CDualNumber(3.0f) / sqrt(CDualNumber(x, 1.0f)); printf("3/sqrt(%0.4f) = %0.4f\n", x, y.Real()); printf("3/sqrt(%0.4f)' = %0.4f\n\n", x, y.Dual()); y = pow(CDualNumber(x, 1.0f) + CDualNumber(1.0f), 1.337f); printf("(%0.4f+1)^1.337 = %0.4f\n", x, y.Real()); printf("(%0.4f+1)^1.337' = %0.4f\n\n", x, y.Dual()); } int main (int argc, char **argv) { TestSmoothStep(0.5f); TestSmoothStep(0.75f); TestTrig(PI * 0.25f); TestSimple(3.0f); return 0; }
Here is the program output:
Closing Info
When you are thinking what number ε has to be so that ε^2 is 0 but ε is not 0, you may be tempted to think that it is an imaginary number, just like i (the square root of -1) that doesn’t actually exist. This is actually not how it is… I’ve seen ε described in two ways.
One way I’ve seen it described is that it’s an infinitesimal number. That sort of makes sense to me, but not in a concrete and tangible way.
The way that makes more sense to me is to describe it as a matrix like this:
[0, 1]
[0, 0]
If you multiply that matrix by itself, you will get zero(s) as a result.
In fact, an alternate way to implement the dual numbers is to treat them like a matrix like that.
I also wanted to mention that it’s possible to modify this technique to get the 2nd derivative of a function or the 3rd, or the Nth. It isn’t only limited to the 1st derivative. Check the links at the bottom of this post for more info, but essentially, if you want 1st and 2nd derivative, you need to make it so that ε^3 = 0 instead of ε^2 = 0. There is a way to do that with matrices.
Another neat thing is that you can also extend this into multiple dimensions. This is useful for situations like if you have some terrain described by mathematical functions, when you are walking the grid of terrain to make vertex information, you can get the slope / gradient / surface normal at the same time.
Lastly, I wanted to mention a different kind of number called a hyperbolic number.
The imaginary number i^2 = -1 and we can use it to do 2d rotations.
The dual number ε^2 is 0 (and ε is not 0) and we can use it to do automatic differentiation.
Hyperbolic numbers have j, and j^2 = 1 (and j is not 1). I’m not sure, but I bet they have some interesting usefulness to them too. It would be interesting to research that more sometime. If you know anything about them, please post a comment!
Links
This shadertoy is what got me started looking into dual numbers. It’s a mandelbrot viewer done by iq using dual numbers to estimate a distance from a point to the mandelbrot set (as far as I understand it anyhow, ha!). He uses that estimated distance to color the pixels.
Shadertoy: Dual Complex Numbers
I didn’t get very much into the reasons of why this works (has to do with taylor series terms disappearing if ε^2 is 0), or the rigorous math behind deriving the operators, but here are some great links I found researching this stuff and putting this blog post together.
Wikipedia: Dual Number
[Book] Dual-Number Methods in Kinematics, Statics and Dynamics By Ian Fischer
[GDC2012] Math for Game Programmers: Dual Numbers by Gino van den Bergen
Stackexchange: Implementing trig functions for dual numbers
Exact numeric nth derivatives
Automatic Differentiation with Dual numbers
Wikipedia: Automatic Differentiation | http://blog.demofox.org/2014/12/30/dual-numbers-automatic-differentiation/ | CC-MAIN-2017-22 | refinedweb | 2,650 | 60.24 |
pyinstrument 0.13.2
A call stack profiler for Python. Inspired by Apple's Instruments.apppyinstrument
============
A Python profiler that records the call stack of the executing code, instead
of just the final function in it.
[]()
It uses a **statistical profiler**, meaning the code samples the stack
periodically (every 1 ms). This is lower overhead than event-
based profiling (as done by `profile` and `cProfile`).
Documentation
-------------
* [Installation](#installation)
* [Usage](#usage)
* [Command-line](#command-line)
* [Django](#django)
* [Python](#python)
* [Signal or setprofile mode?](#signal-or-setprofile-mode)
* [Known issues](#known-issues)
* [Changelog](#changelog)
* [What's new in v0.13](#whats-new-in-v013)
* [What's new in v0.12](#whats-new-in-v012)
* [Further information](#further-information)
* [Call stack profiling?](#call-stack-profiling)
Installation
------------
pip install pyinstrument
pyinstrument supports Python 2.7 and 3.3+.
Usage
-----
#### Command-line ####
You can call pyinstrument directly from the command line.
python -m pyinstrument [options] myscript.py [args...]
Options:
-h, --help show this help message and exit
--setprofile run in setprofile mode, instead of signal mode
--html output HTML instead of text
-o OUTFILE, --outfile=OUTFILE
save report to <outfile>
--unicode force unicode text output
--no-unicode force ascii text output
--color force ansi color text output
--no-color force no color text output
This will run `myscript.py` to completion or until you interrupt it, and
then output the call tree.
#### Django ####
Add `pyinstrument.middleware.ProfilerMiddleware` to `MIDDLEWARE_CLASSES`.
If you want to profile your middleware as well as your view (you probably
do) then put it at the start of the list.
##### Per-request profiling #####
Add `?profile` to the end of the request URL to activate the profiler.
Instead of seeing the output of your view, pyinstrument renders an HTML
call tree for the view (as in the screenshot above).
##### Using `PYINSTRUMENT_PROFILE_DIR` #####
If you're writing an API, it's not easy to change the URL when you want
to profile something. In this case, add
`PYINSTRUMENT_PROFILE_DIR = 'profiles'` to your settings.py.
pyinstrument will profile every request and save the HTML output to the
folder `profiles` in your working directory.
#### Python ####
```python
from pyinstrument import Profiler
profiler = Profiler() # or Profiler(use_signal=False), see below
profiler.start()
# code you want to profile
profiler.stop()
print(profiler.output_text(unicode=True, color=True))
```
You can omit the `unicode` and `color` flags if your output/terminal does
not support them.
Signal or setprofile mode?
--------------------------
On Mac/Linux/Unix, pyinstrument can run in 'signal' mode. This uses
OS-provided signals to interrupt the process every 1ms and record the stack.
It gives much lower overhead (and thus accurate) readings than the standard
Python [`sys.setprofile`][setprofile] style profilers. However, this can
only profile the main thread.
On Windows and on multi-threaded applications, a `setprofile` mode is
available by passing `use_signal=False` to the Profiler constructor. It works
exactly the same as the signal mode, but has higher overhead. See the below
table for an example of the amount of overhead.
[setprofile]:
This overhead is important because code that makes a lot of Python function
calls will appear to take longer than code that does not.
| Django template render × 4000 | Overhead
---------------------------|------------------------------:|---------:
Base | 1.46s |
| |
pyinstrument (signal) | 1.84s | 26%
cProfile | 2.18s | 49%
pyinstrument (setprofile) | 5.33s | 365%
profile | 25.39s | 1739%
To run in setprofile mode:
* Use flag `--setprofile` if using the command-line interface
* Use setting `PYINSTRUMENT_USE_SIGNAL = False` in Django
* Use argument `use_signal=False` in the constructor for the Python API
Known issues
------------
- When profiling Django, I'd recommend disabling django-debug-toolbar,
django-devserver etc., as their instrumentation distort timings.
- In signal mode, any calls to [`time.sleep`][pysleep] will return
immediately. This is because of an implementation detail of `time.sleep`,
but matches the behaviour of the C function [`sleep`][csleep].
- Some system calls can fail with `IOError` when being profiled in signal
mode. If this happens to you, your only option is to run in setprofile
mode.
[pysleep]:
[csleep]:
Changelog
---------
### What's new in v0.13 ###
- `pyinstrument` command. You can now profile python scripts from the shell
by running `$ pyinstrument script.py`. This is now equivalent to
`python -m pyinstrument`. Thanks @asmeurer!
### What's new in v0.12 ###
- Application code is highlighted in HTML traces to make it easier to spot
- Added `PYINSTRUMENT_PROFILE_DIR` option to the Django interface, which
will log profiles of all requests to a file the specified folder. Useful
for profiling API calls.
- Added `PYINSTRUMENT_USE_SIGNAL` option to the Django interface, for use
when signal mode presents problems.
Further information
===================
Call stack profiling?
---------------------
The standard Python profilers [`profile`][1] and [`cProfile`][2] produce
output where time is totalled according to the time spent in each function.
This is great, but it falls down when you profile code where most time is
spent in framework code that you're not familiar with.
[1]:
[2]:
Here's an example of profile output when using Django.
151940 function calls (147672 primitive calls) in 1.696 seconds
Ordered by: cumulative time
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 1.696 1.696 profile:0(<code object="" < at 0x1053d6a30, file "./manage.py", line 2>)
1 0.001 0.001 1.693 1.693 manage.py:2(<module>)
1 0.000 0.000 1.586 1.586 __init__.py:394(execute_from_command_line)
1 0.000 0.000 1.586 1.586 __init__.py:350(execute)
1 0.000 0.000 1.142 1.142 __init__.py:254(fetch_command)
43 0.013 0.000 1.124 0.026 __init__.py:1(<module>)
388 0.008 0.000 1.062 0.003 re.py:226(_compile)
158 0.005 0.000 1.048 0.007 sre_compile.py:496(compile)
1 0.001 0.001 1.042 1.042 __init__.py:78(get_commands)
153 0.001 0.000 1.036 0.007 re.py:188(compile)
106/102 0.001 0.000 1.030 0.010 __init__.py:52(__getattr__)
1 0.000 0.000 1.029 1.029 __init__.py:31(_setup)
1 0.000 0.000 1.021 1.021 __init__.py:57(_configure_logging)
2 0.002 0.001 1.011 0.505 log.py:1(<module>)
When you're using big frameworks like Django, it's very hard to understand how
your own code relates to these traces.
Pyinstrument records the entire stack, so tracking expensive calls is much
easier.
- Author: Joe Rickerby
- Keywords: profiling,profile,profiler,cpu,time
- Categories
- Development Status :: 4 - Beta
- Environment :: Console
- Environment :: Web Environment
- Intended Audience :: Developers
- License :: OSI Approved :: BSD License
- Operating System :: MacOS
- Operating System :: Microsoft :: Windows
- Operating System :: POSIX
- Programming Language :: Python :: 2.7
- Programming Language :: Python :: 3.3
- Topic :: Software Development :: Debuggers
- Topic :: Software Development :: Testing
- Package Index Owner: joerick
- DOAP record: pyinstrument-0.13.2.xml | https://pypi.python.org/pypi/pyinstrument | CC-MAIN-2017-30 | refinedweb | 1,123 | 51.75 |
Developing software is great, but… I think we can all agree it can be a bit of an emotional rollercoaster. At the beginning, everything is great. You add new features one after another in a matters of days if not hours. You’re on a roll!
Fast forward a few months, and your development speed decreases. Is it because you are not working as hard as before? Not really. Let’s fast forward a few more months, and your development speed drops further. Working on this project is not fun anymore and has become a drag.
It gets worse. You start discovering multiple bugs in your application. Often, solving one bug creates two new ones. At this point, you can start singing:
99 little bugs in the code. 99 little bugs. Take one down, patch it around,
…127 little bugs in the code.
How do you feel about working on this project now? If you are like me, you probably start losing your motivation. It’s just a pain to develop this application, since every change to existing code can have unpredictable consequences.
This experience is common in the software world and can explain why so many programmers want to throw their source code away and rewrite everything.
Reasons Why Software Development Slows Down over Time
So what’s the reason for this problem?
The main cause is rising complexity. From my experience the biggest contributor to overall complexity is the fact that, in the vast majority of software projects, everything is connected. Because of the dependencies that each class has, if you change some code in the class that send emails, your users suddenly can’t register. Why is that? Because your registration code depends on the code that sends emails. Now you can’t change anything without introducing bugs. It’s simply not possible to trace all dependencies.
So there you have it; the real cause of our problems is raising complexity coming from all the dependencies that our code has.
Big Ball of Mud and How to Reduce It
Funny thing is, this issue has been known for years now. It’s a common anti-pattern called the “big ball of mud.” I’ve seen that type of architecture in almost all projects I worked on over the years in multiple different companies.
So what is this anti-pattern exactly? Simply speaking, you get a big ball of mud when each element has a dependency with other elements. Below, you can see a graph of the dependencies from well-known open-source project Apache Hadoop. In order to visualize the big ball of mud (or rather, the big ball of yarn), you draw a circle and place classes from the project evenly on it. Just draw a line between each pair of classes that depend on each other. Now you can see the source of your problems.
A Solution with Modular Code
So I asked myself a question: Would it be possible to reduce the complexity and still have fun like at the beginning of the project? Truth be told, you can’t eliminate all of the complexity. If you want to add new features, you will always have to raise the code complexity. Nevertheless, complexity can be moved and separated.
How Other Industries Are Solving This Problem
Think about the mechanical industry. When some small mechanical shop is creating machines, they buy a set of standard elements, create a few custom ones, and put them together. They can make those components completely separately and assemble everything at the end, making just a few tweaks. How is this possible? They know how each element will fit together by set industry standards like bolts sizes, and up-front decisions like the size of mounting holes and the distance between them.
Each element in the assembly above can be provided by a separate company that has no knowledge whatsoever about the final product or its other pieces. As long as each modular element is manufactured according to specifications, you will be able to create the final device as planned.
Can we replicate that in the software industry?
Sure we can! By using interfaces and inversion of control principle; the best part is the fact that this approach can be used in any object-oriented language: Java, C#, Swift, TypeScript, JavaScript, PHP—the list goes on and on. You don’t need any fancy framework to apply this method. You just need to stick to a few simple rules and stay disciplined.
Inversion of Control Is Your Friend
When I first heard about inversion of control, I immediately realized that I had found a solution. It’s a concept of taking existing dependencies and inverting them by using interfaces. Interfaces are simple declarations of methods. They don’t provide any concrete implementation. As a result, they can be used as an agreement between two elements on how to connect them. They can be used as a modular connectors, if you will. As long as one element provides the interface and another element provides the implementation for it, they can work together without knowing anything about each other. It’s brilliant.
Let’s see on a simple example how can we decouple our system to create modular code. The diagrams below have been implemented as simple Java applications. You can find them on this GitHub repository.
Problem
Let’s assume that we have a very simple application consisting only of a
Main class, three services, and a single
Util class. Those elements depend on each other in multiple ways. Below, you can see an implementation using the “big ball of mud” approach. Classes simply call each other. They are tightly coupled, and you can’t simply take out one element without touching others. Applications created using this style allow you to initially grow rapidly. I believe this style is appropriate for proof-of-concept projects since you can play around with things easily. Nevertheless, it’s not appropriate for production-ready solutions because even maintenance can be dangerous and any single change can create unpredictable bugs. The diagram below shows this big ball of mud architecture.
Why Dependency Injection Got It All Wrong
In a search for a better approach, we can use a technique called dependency injection. This method assumes that all components should be used through interfaces. I’ve read claims that it decouples elements, but does it really, though? No. Have a look at the diagram below.
The only difference between the current situation and a big ball of mud is the fact that now, instead of calling classes directly, we call them through their interfaces. It slightly improves separating elements from each other. If, for example, you would like to reuse
Service A in a different project, you could do that by taking out
Service A itself, along with
Interface A, as well as
Interface B and
Interface Util. As you can see,
Service A still depends on other elements. As a result, we still get problems with changing code in one place and messing up behavior in another. It still creates the issue that if you modify
Service B and
Interface B, you will need to change all elements that depend on it. This approach doesn’t solve anything; in my opinion, it just adds a layer of interface on top of elements. You should never inject any dependencies, but instead you should get rid of them once and for all. Hurray for independence!
The Solution for Modular Code
The approach I believe solves all the main headaches of dependencies does it by not using dependencies at all. You create a component and its listener. A listener is a simple interface. Whenever you need to call a method from outside the current element, you simply add a method to the listener and call it instead. The element is only allowed to use files, call methods within its package, and use classes provided by main framework or other used libraries. Below, you can see a diagram of the application modified to use element architecture.
Please note that, in this architecture, only the
Main class has multiple dependencies. It wires all elements together and encapsulates the application’s business logic.
Services, on the other hand, are completely independent elements. Now, you can take out each service out of this application and reuse them somewhere else. They don’t depend on anything else. But wait, it gets better: You don’t need to modify those services ever again, as long as you don’t change their behavior. As long as those services do what they supposed to do, they can be left untouched until the end of time. They can be created by a professional software engineer, or a first time coder compromised of the worst spaghetti code anyone ever cooked with
goto statements mixed in. It doesn’t matter, because their logic is encapsulated. As horrible as it might be, it will never spill out to other classes. That also gives you the power to split work in a project between multiple developers, where each developer can work on their own component independently without the need to interrupt another or even knowing about the existence of other developers.
Finally, you can start writing independant code one more time, just like at the beginning of your last project.
Element Pattern
Let’s define the structural element pattern so that we will be able to create it in a repeatable manner.
The simplest version of the element consists of two things: A main element class and a listener. If you want to use an element, then you need to implement the listener and make calls to the main class. Here is a diagram of the simplest configuration:
Obviously, you will need to add more complexity into the element eventually but you can do so easily. Just make sure that none of your logic classes depend on other files in the project. They can only use the main framework, imported libraries, and other files in this element. When it comes to asset files like images, views, sounds, etc., they also should be encapsulated within elements so that in the future they will be easy to reuse. You can simply copy the entire folder to another project and there it is!
Below, you can see an example graph showing a more advanced element. Notice that it consists of a view that it’s using and it doesn’t depend on any other application files. If you want to know a simple method of checking dependencies, just look at the import section. Are there any files from outside the current element? If so, then you need to remove those dependencies by either moving them into the element or by adding an appropriate call to the listener.
Let’s also have a look at a simple “Hello World” example created in Java.
public class Main { interface ElementListener { void printOutput(String message); } static class Element { private ElementListener listener; public Element(ElementListener listener) { this.listener = listener; } public void sayHello() { String message = "Hello World of Elements!"; this.listener.printOutput(message); } } static class App { public App() { } public void start() { // Build listener ElementListener elementListener = message -> System.out.println(message); // Assemble element Element element = new Element(elementListener); element.sayHello(); } } public static void main(String[] args) { App app = new App(); app.start(); } }
Initially, we define
ElementListener to specify the method that prints output. The element itself is defined below. On calling
sayHello on the element, it simply prints a message using
ElementListener. Notice that the element is completely independent from the implementation of
printOutput method. It can be printed into the console, a physical printer, or a fancy UI. The element doesn’t depend on that implementation. Because of this abstraction, this element can be reused in different applications easily.
Now have a look at the main
App class. It implements the listener and assembles the element together with concrete implementation. Now we can start using it.
You can also run this example in JavaScript here
Element Architecture
Let’s have a look at using the element pattern in a large-scale applications. It’s one thing to show it in a small project—it’s another to apply it to the real world.
The structure of a full-stack web application that I like to use looks as follows:
src ├── client │ ├── app │ └── elements │ └── server ├── app └── elements
In a source code folder, we initially split the client and server files. It’s a reasonable thing to do, since they run in two different environments: the browser and the back-end server.
Then we split the code in each layer into folders called app and elements. Elements consists of folders with independent components, while the app folder wires all the elements together and stores all the business logic.
That way, elements can be reused between different projects, while all application-specific complexity is encapsulated in a single folder and quite often reduced to simple calls to elements.
Hands-on Example
Believing that practice always trump theory, let’s have a look at a real-life example created in Node.js and TypeScript.
It’s a very simple web application that can be used as a starting point for more advanced solutions. It does follow the element architecture as well as it uses an extensively structural element pattern.
From highlights, you can see that the main page has been distinguished as an element. This page includes its own view. So when, for instance, you want to reuse it, you can simply copy the whole folder and drop it into a different project. Just wire everything together and you are set.
It’s a basic example that demonstrates that you can start introducing elements in your own application today. You can start distinguishing independent components and separate their logic. It doesn’t matter how messy the code that you are currently working on is.
Develop Faster, Reuse More Often!
I hope that, with this new set of tools, you will be able to more easily develop code that is more maintainable. Before you jump into using the element pattern in practice, let’s quickly recap all the main points:
A lot of problems in software happen because of dependencies between multiple components.
By making a change in one place, you can introduce unpredictable behavior somewhere else.
Three common architectural approaches are:
The big ball of mud. It’s great for rapid development, but not so great for stable production purposes.
Dependency injection. It’s a half-baked solution that you should avoid.
Element architecture. This solution allows you to create independent components and reuse them in other projects. It’s maintainable and brilliant for stable production releases.
The basic element pattern consists of a main class that has all the major methods as well as a listener that is a simple interface that allows for communication with the external world.
In order to achieve full-stack element architecture, first you separate your front-end from the back-end code. Then you create a folder in each for an app and elements. The elements folder consists of all independent elements, while the app folder wires everything together.
Now you can go and start creating and sharing your own elements. In the long run, it will help you create easily maintainable products. Good luck and let me know what you created!
Also, if you find yourself prematurely optimizing your code, read How to Avoid the Curse of Premature Optimization by fellow Toptaler Kevin Bloch.
Understanding the basics
What makes unplanned code difficult to maintain and prone to bugs?
Code can be hard to maintain due to dependencies between multiple components. As a result, making changes in one place can introduce unpredictable behaviour somewhere else.
What is modular architecture?
Modular architecture means dividing an application into independent elements. We recognize all inter-project dependencies as the cause of hard to find and fix problems. Total independence makes those components extremely easy to test, maintain, share, and reuse in the future.
What are different types of code architectures developers employ?
Common architectural approaches are: 1) The big ball of mud: Great for rapid development, but not so appropriate for stable production purposes. 2) Dependency injection: A half-baked solution that you should avoid. 3) Element architecture: It’s maintainable and brilliant for stable production releases. | https://www.toptal.com/software/creating-modular-code-with-no-dependencies | CC-MAIN-2019-26 | refinedweb | 2,727 | 56.35 |
Modules in JavaScript are much more straightforward since ES Modules were added to the specification. Modules are separated by file and loaded asynchronously. Exports are defined using the
export keyword; values can be imported with the
import keyword.
While the basics of importing and exporting individual values is pretty easy to grasp and use, there are many other ways to work with ES Modules to make your imports and exports work the way you need them to. In this lesson, we'll go over all of the ways you can export and import within your modules.
One thing to remember is that exports and static imports can only happen at the top level of the module. You cannot export or statically import from within a function, if statement, or any other block. Dynamic imports, on the other hand, can be done from within a function; we'll talk about those at the end of the lesson.
Exports
Default Export
Every module has a single "default" export, which represents the main value which is exported from the module. There might be more things exported, but the default export is what defines the module. You can only have one default export in a module.
const fruitBasket = new FruitBasket();export default fruitBasket;
Notice that I have to first define the value before adding it to my default export. If I wanted to, I could export my value immediately, without assigning it to a variable. But I cannot assign it to a variable at the same time as exporting it.
We can export a function declaration and a class declaration by default without first assigning it to a variable.
export default function addToFruitBasket(fruit) {// ... implementation goes here}
We can even export literal values as the default export.
export default 123;
Named Export
Any variable declaration can be exported when it is created. This creates a "Named Export" using the variable name as the export name.
export const fruitBasket = new FruitBasket();
We can also immediately export function and class declarations.
export function addToFruitBasket(fruit) {// ... implementation goes here}export class FruitBasket {// ... implementation goes here}
If we wanted to export a variable which was already defined, we could do that by wrapping the variable in curly brackets around our variable name.
const fruitBasket = new FruitBasket();export { fruitBasket };
We can even use the
as keyword to rename our export to be different from the variable name. We can export other variables at the same time, if we wanted.
const fruitBasket = new FruitBasket();class Apple {}export { fruitBasket as basketOfFruit, Apple };
Aggregate Exports
One thing that is common is importing modules from one module and then immediately exporting those values. It looks something like this.
import fruitBasket from "./fruitBasket.js";export { fruitBasket };
This can get tedious when you are importing and exporting lots of things at the same time. ES Modules allows us to import and export multiple values at the same time.
export * from "./fruitBasket.js";
This will take all of the named exports of
./fruitBasket.js and re-export them. It won't re-export default exports though, since a module can only have one default export. If we were to import and export multiple modules with default exports, which value would become the default export for the exporting module?
We can specifically export default modules from other files, or name the default export when we re-export it.
export { default } from "./fruitBasket.js";// orexport { default as fruitBasket } from "./fruitBasket.js";
We can selectively export different items from another module as well, instead of re-exporting everything. We use curly brackets in this case as well.
export { fruitBasket as basketOfFruit, Apple } from "./fruitBasket.js";
Finally, we can wrap up an entire module into a single named export using the
as keyword. Suppose we have the following file.
// fruits.jsexport class Apple {}export class Banana {}
We can now pack this into a single export which is an object containing all of the named and default exports.
export * as fruits from "./fruits.js"; // { Apple: class Apple, Banana: class Banana }
Imports
Default Imports
When importing a default value, we need to assign a name to it. Since it is the default, it doesn't matter what we name it.
import fruitBasketList from "./fruitBasket.js";
We can also import all of the exports, including named and default exports, at the same time. This will put all of them exports into an object, and the default export will be given the property name "default".
import * as fruitBasket from "./fruitBasket.js"; // { default: fruitBasket }
Named Imports
We can import any named export by wrapping the exported name in curly brackets.
import { fruitBasket, Apple } from "./fruitBasket.js";
We can also rename the import as we import it using the
as keyword.
import {fruitBasket as basketOfFruit, Apple} from './fruitBasket.js`
We can also mix named and default exports in the same import statement. The default export is listed first, followed by the named exports in curly brackets.
import fruitBasket, { Apple } from "./fruitBasket.js";
Finally, we can import a module without listing any of the exports we want to use in our file. This is called a 'side-effect' import, and will execute the code in the module without providing us any exported values.
import "./fruitBasket.js";
Dynamic Imports
Sometimes we don't know the name of a file before we import it. Or we don't need to import a file until we are partway through executing code. We can use a dynamic import to import modules anywhere in our code. It's called "dynamic" because we could use any string value as the path to the import, not just a string literal.
Since ES Modules are asynchronous, the module won't immediately be available. We have to wait for it to be loaded before we can do anything with it. Because of this, dynamic imports return a promise which resolves to our module.
If our module can't be found, the dynamic import will throw an error.
async function createFruit(fruitName) {try {const FruitClass = await import(`./${fruitName}.js`);} catch {console.error("Error getting fruit class module:", fruitName);}return new FruitClass();}
Before you leave. 105,313 subscribers and an almost 50% weekly open rate later, it looks like we did it.
Delivered to 105,313.
. | https://ui.dev/esmodules | CC-MAIN-2022-27 | refinedweb | 1,038 | 57.47 |
Java provides selection statements that allow the program to choose between alternative actions during execution. The choice is based on criteria specified in the selection statement. These selection statements are
simple if Statement
if-else Statement
switch Statement
The simple if statement has the following syntax:
if (<conditional expression>)
<statement>
It is used to decide whether an action is to be performed or not, based on a condition. The condition is specified by <conditional expression> and the action to be performed is specified by <statement>.
The semantics of the simple if statement are straightforward. The <conditional expression> is evaluated first. If its value is true, then <statement> (called the if block) is executed and execution continues with the rest of the program. If the value is false, then the if block is skipped and execution continues with the rest of the program. The semantics are illustrated by the activity diagram in Figure 5.1a.
In the following examples of the if statement, it is assumed that the variables and the methods have been defined appropriately:
if (emergency) // emergency is a boolean variable operate(); if (temperature > critical) soundAlarm(); if (isLeapYear() && endOfCentury()) celebrate(); if (catIsAway()) { // Block getFishingRod(); goFishing(); }
Note that <statement> can be a block, and the block notation is necessary if more that one statement is to be executed when the <conditional expression> is true.
Since the <conditional expression> must be a boolean expression, it avoids a common programming error: using an expression of the form (a=b) as the condition, where inadvertently an assignment operator is used instead of a relational operator. The compiler will flag this as an error, unless both a and b are boolean.
Note that the if block can be any valid statement. In particular, it can be the empty statement (;) or the empty block ({}). A common programming error is an inadvertent use of the empty statement.
if (emergency); // Empty if block operate(); // Executed regardless of whether it was an emergency or not.
The if-else statement has the following syntax:
if (<conditional expression>)
<statement1>
else
<statement2>
It is used to decide between two actions, based on a condition.
The <conditional expression> is evaluated first. If its value is true, then <statement1> (the if block) is executed and execution continues with the rest of the program. If the value is false, then <statement2> (the else block) is executed and execution continues with the rest of the program. In other words, one of two mutually exclusive actions is performed. The else clause is optional; if omitted, the construct reduces to the simple if statement. The semantics are illustrated by the activity diagram in Figure 5.1b.
In the following examples of the if-else statement, it is assumed that all variables and methods have been defined appropriately:
if (emergency) operate(); else joinQueue(); if (temperature > critical) soundAlarm(); else businessAsUsual(); if (catIsAway()) { getFishingRod(); goFishing(); } else playWithCat();
Since actions can be arbitrary statements, the if statements can be nested.
if (temperature >= upperLimit) { // (1) if (danger) // (2) Simple if. soundAlarm(); if (critical) // (3) evacuate(); else // Goes with if at (3). turnHeaterOff(); } else // Goes with if at (1). turnHeaterOn();
The use of the block notation, {}, can be critical to the execution of if statements. The if statements (A) and (B) in the following examples do not have the same meaning. The if statements (B) and (C) are the same, with extra indentation used in (C) to make the meaning evident. Leaving out the block notation in this case could have catastrophic consequences: the heater could be turned on when the temperature is above the upper limit.
// (A) if (temperature > upperLimit) { // (1) Block notation. if (danger) soundAlarm(); // (2) } else // Goes with if at (1). turnHeaterOn(); // (B) if (temperature > upperLimit) // (1) Without block notation. if (danger) soundAlarm(); // (2) else turnHeaterOn(); // Goes with if at (2). // (C) if (temperature > upperLimit) // (1) if (danger) // (2) soundAlarm(); else // Goes with if at (2). turnHeaterOn();
The rule for matching an else clause is that an else clause always refers to the nearest if that is not already associated with another else clause. Block notation and proper indentation can be used to make the meaning obvious.
Cascading if-else statements are a sequence of nested if-else statements where the if of the next if-else statement is joined to the else clause of the previous one. The decision to execute a block is then based on all the conditions evaluated so far.
if (temperature >= upperLimit) { // (1) soundAlarm(); turnHeaterOff(); } else if (temperature < lowerLimit) { // (2) soundAlarm(); turnHeaterOn(); } else if (temperature == (upperLimit-lowerLimit)/2) { // (3) doingFine(); } else // (4) noCauseToWorry();
The block corresponding to the first if condition that evaluates to true is executed, and the remaining ifs are skipped. In the example given above, the block at (3) will execute only if the conditions at (1) and (2) are false and the condition at (3) is true. If none of the conditions are true, the block associated with the last else clause is executed. If there is no last else clause, no actions are performed.
Conceptually the switch statement can be used to choose one among many alternative actions, based on the value of an expression. Its general form is as follows:
switch (<non-long integral expression>) {
case label1: <statement1>
case label2: <statement2>
...
case labeln: <statementn>
default: <statement>
} // end switch
The syntax of the switch statement comprises a switch expression followed by the switch body, which is a block of statements. The type of the switch expression is non-long integral (i.e., char, byte, short, or int). The statements in the switch body can be labeled, defining entry points in the switch body where control can be transferred depending on the value of the switch expression. The semantics of the switch statement are as follows:
The switch expression is evaluated first.
The value of the switch expression is compared with the case labels. Control is transferred to the <statementi> associated with the case label that is equal to the value of the switch expression. After execution of the associated statement, control falls through to the next statement unless appropriate action is taken.
If no case label is equal to the value of the switch expression, the statement associated with the default label is executed.
Figure 5.2 illustrates the flow of control through a switch statement.
All labels (including the default label) are optional and can be defined in any order in the switch body. There can be at most one default label in a switch statement. If it is left out and no valid case labels are found, the whole switch statement is skipped.
The case labels are constant expressions whose values must be unique, meaning no duplicate values are allowed. The case label values must be assignable to the type of the switch expression (see Section 3.4, p. 48). In particular, the case label values must be in the range of the type of the switch expression. Note that the type of the case label cannot be boolean, long, or floating-point.
public class Advice { public final static int LITTLE_ADVICE = 0; public final static int MORE_ADVICE = 1; public final static int LOTS_OF_ADVICE = 2; public static void main(String[] args) { dispenseAdvice(LOTS_OF_ADVICE); } public static void dispenseAdvice(int howMuchAdvice) { switch(howMuchAdvice) { // (1) case LOTS_OF_ADVICE: System.out.println("See no evil."); // (2) case MORE_ADVICE: System.out.println("Speak no evil."); // (3) case LITTLE_ADVICE: System.out.println("Hear no evil."); // (4) break; // (5) default: System.out.println("No advice."); // (6) } } }
Output from the program:
See no evil. Speak no evil. Hear no evil.
In Example 5.1, depending on the value of the howMuchAdvice parameter, different advice is printed in the switch statement at (1) in the method dispenseAdvice(). The example shows the output when the value of the howMuchAdvice parameter is LOTS_OF_ADVICE. In the switch statement, the associated statement at (2) is executed, giving one advice. Control then falls through to the statement at (3), giving the second advice. Control falls through to (4), dispensing the third advice, and finally executing the break statement at (5) causes control to exit the switch statement. Without the break statement at (5), control would continue to fall through the remaining statements if there were any. Execution of the break statement in a switch body transfers control out of the switch statement (see Section 5.4, p. 172). If the parameter howMuchAdvice has the value MORE_ADVICE, then the advice at (3) and (4) is given. The value LITTLE_ADVICE results in only one advice at (4) being given. Any other value results in the default action, which announces that there is no advice.
The associated statement of a case label can be a list of statements (which need not be a statement block). The case label is prefixed to the first statement in each case. This is illustrated by the associated statement for the case label LITTLE_ADVICE in Example 5.1, which comprises statements (4) and (5).
Example 5.2 makes use of a break statement inside a switch statement to convert a char value representing a digit to its corresponding word in English. Note that the break statement is the last statement in the list of statements associated with each case label. It is easy to think that the break statement is a part of the switch statement syntax, but technically it is not.
public class Digits { public static void main(String[] args) { System.out.println(digitToString('7') + " " + digitToString('8') + " " + digitToString('6')); } public static String digitToString(char digit) { String str = ""; switch(digit) { case '1': str = "one"; break; case '2': str = "two"; break; case '3': str = "three"; break; case '4': str = "four"; break; case '5': str = "five"; break; case '6': str = "six"; break; case '7': str = "seven"; break; case '8': str = "eight"; break; case '9': str = "nine"; break; case '0': str = "zero"; break; default: System.out.println(digit + " is not a digit!"); } return str; } }
Output from the program:
seven eight six
Several case labels can prefix the same statement. They will all result in the associated statement being executed. This is illustrated in Example 5.3 for the switch statement at (1).
The first statement in the switch body must have a case label, or it is unreachable. This statement will never be executed since control can never be transferred to it. The compiler will flag this as an error.
Since each action associated with a case label can be an arbitrary statement, it can be another switch statement. In other words, switch statements can be nested. Since a switch statement defines its own local block, the case labels in an inner block do not conflict with any case labels in an outer block. Labels can be redefined in nested blocks, unlike variables which cannot be redeclared in nested blocks (see Section 4.5, p. 123). In Example 5.3, an inner switch statement is defined at (2). This allows further refinement of the action to take on the value of the switch expression, in cases where multiple labels are used in the outer switch statement. A break statement terminates the innermost switch statement in which it is executed.
public class Seasons { public static void main(String[] args) { int monthNumber = 11; switch(monthNumber) { // (1) Outer case 12: case 1: case 2: System.out.println("Snow in the winter."); break; case 3: case 4: case 5: System.out.println("Green grass in spring."); break; case 6: case 7: case 8: System.out.println("Sunshine in the summer."); break; case 9: case 10: case 11: // (2) switch(monthNumber) { // Nested switch (3) Inner case 10: System.out.println("Halloween."); break; case 11: System.out.println("Thanksgiving."); break; } // end nested switch // Always printed for case labels 9, 10, 11 System.out.println("Yellow leaves in the fall."); // (4) break; default: System.out.println(monthNumber + " is not a valid month."); } } }
Output from the program:
Thanksgiving. Yellow leaves in the fall. | https://etutorials.org/cert/java+certification/Chapter+5.+Control+Flow+Exception+Handling+and+Assertions/5.2+Selection+Statements/ | CC-MAIN-2021-21 | refinedweb | 1,970 | 55.84 |
Bitcoin’s Financial Returns (Full Calculations)
As a supplement to my recent piece at the American Institute for Economic Research, I here report all sources and calculations used.
Investigating bitcoin’s returns over the 2010s is far from easy, particularly so in the early years when bitcoin still wasn’t more than a playing toy on a mailing list. Despite growing up in the digital age, few people cared about bitcoin or its dollar-price exchanges in 2010 — meaning almost nobody took care to preserve those crucial early trades.
“Tell me about it,” a financial historian might say. “Welcome to the prime issue facing financial economists digging through the rubble of past financial markets.”
Total Return Calculations
None of the financial instruments and assets considered below pay dividends or in other ways throw off interest payments. That simplifies calculations greatly as we’re only looking at capital appreciation. For Bitcoin, that’s actually not true as owning bitcoin at the time of its several forks have entitled the owner to coins in Bitcoin Cash (BCH), Bitcoin Gold (BTG) and Bitcoin SV (BSV). Together these coins are priced at ~$360, adding a few hundred dollars to the bitcoin prices beginning in 2017 and 2018.
Throughout this comparison we’re also concerned with one-period calculations; even though the periods I discuss in the piece range up to 22 years with various trades and different prices in between, we are only using them to compare two points in time, t and t-1, where t varies across the financial investment spectrum I’m considering (roughly 1995 to 2020).
The standard formula for capital appreciation is given by
where Pt is the current price (or end-price) and Pt-1 is the historical price (or initial price). To avoid confusing myself, I tend to use the following simplified and more intuitive version of the same formula when I assess percentage returns:
When not otherwise stated, I use the end-of-year bitcoin-to-dollar price (BTCUSD) of $7,180. This is always the end-price we’re concerned with, Pt in the formulas.
For return calculations, we also need an initial price, Pt-1. I begin the piece by citing three early estimates of the the first bitcoin trades of the last decade, $0.5, $0.07 or even $0.0036:
- 100*(7,180/0.5 –1) = 1,435,900% return
- 100*(7,180/0.07 –1) = 10,257,043% return
- 100*(7,180/0,0036 –1) =199,444,344% return
We’re already starting to see the immense power that a lower base produces.
Lyanchev’s Numbers
I mention Jordan Lyanchev’s piece where he simultaneously claims an 8,900,000% return, a $0.07 initial dollar price and an exchange rate to USD of about $7,300 at the time of his posting. That’s not possible:
- 100*($7,300/0.07 –1) = 10,428,471%,
(which I rounded to “almost 10,500,000%)
Alternatively, if we run the formula in reverse, plugging in the 8,900,000% return and the (known) current price of $7,300, we get an initial bitcoin price of $0.082:
8,900,000 = (7,300/x -1) *100
89,001 = 7,300/x
x=7,300/89,001
x= 0.08202.
If we plug some other December 2019 prices into the formula, replacing $7,300 with $7,200 or $7,500, we see that Lyanchev’s initial price still doesn’t make sense. We’d have to plug in prices of below $6,675 for $0.07 to be within rounding, given a return of 8,900,000% (prices only seen for a brief twenty-four hours on Dec 17–18).
More likely, he miscalculated the statement in the CNN article (“$1 turned into $90,000") to mean “8,900,000%” when it should have been 8,999,900% — and actually, 9,002,500% given later information. But what’s a few thousand (or almost a hundred thousand) percent among friends?
This latter figure is what I referred to as “just north of nine million percent.”
Further displacing a few hundred thousand (or million?) percent return is Jamie Redman at Bitcoin.com. First his title reports 8.9 million percent. Then his text cites the 8,999,900% return implied by the supposed Bank of America report ($1 in bitcoin 2010 turned into $90,000 at the end of 2019). And finally his first price data cites a bitcoin for $0.003 in March 2010.
Quickly plugging in that initial price to our formula combined with the price at Redman’s publication (~$7,200), we get — hold on now — a return of almost two-hundred-and-forty million percent:
- 100*($7,200/0.003 –1) = 239,999,900%
I wonder, if the purpose of measuring bitcoin’s magnificence by its dollar-return figures, wouldn’t you wanna go with the higher ones? If you can substantiate the $0.003 price, the calculation is not wrong; why not say “240 million percent” instead of various numbers around 9 million percent?
Hajric’s Numbers
Without much details, Hajric at Bloomberg vaguely states that bitcoin returned “more than 9,000,000%,” which we have seem is roughly accurate given an initial price of a little more than $0.07.
Early price data
Uncertainty prevails regarding bitcoin’s early dollar-values. Clarification: the differences between these very small numbers are huge, which the initial calculations above show; normally, we might switch fund manager when they underperform by 1–2 percentage points — whereas here we’re throwing around millions of percent like they’re nothing.
That is, 0.082 is eleven times bigger than 0.0067, but for the final Total Return calculations that difference amounts to a roughly hundred million percent return. The numbers from low bases quickly become staggering:
A few pennies there becomes unfathomable returns — millions, tens of millions and hundreds of millions of percent— there.
That infamous pizza
The pizza story holds that in May, Laszlo Hanyecz paid 10,000 bitcoins to a third party who, in turn, ordered him two Papa John’s pizza. If priced at $25, implied BTCUSD exchange rate implied $0.0025 (25/10,000); if including the tip that Hanyecz claims were involved, that’s 0.003 (30/10,000).
Netflix’s returns
I write that NFLX closed the decade with a 4,135% return. According to Yahoo Finance, Netflix’s first price of the decade was $7.64, and its closing price on Dec 31, 2019 was $323.55. Plugging it into our formula gets us:
TR = (323.55/7.64 -1)*100 = 4,134,95%
Shifting the decade back a little bit so that I can capture NFLX’s all-time-high (intra-day trading) of $423.21 on June 21, 2018, I get almost 11,000% return based on an initial price from June 23rd, 2008 ($3.82):
TR = (423.21/3.82 -1)*100 = 10,979%
When I cherry-pick the to inflate NFLX stock return even more, I used the following dates and numbers:
- ATH of $423.21 on June 21, 2018
- Starting price of $0.37 on Oct 7, 2002
TR = (423.21/0.37 -1) *100 = 114,281%
which I quoted as almost 115,000% return.
Amazon’s returns
For Amazon, I use compare its IPO price of $1.50 in May 1997 to its peak close ($2012.71) on Aug 27, 2018. While intentionally measured bottom-to-peak to maximize return, I still only get little over hundred thousand percent over 21 years:
TR = (2012.71/1.5 -1)*100 = 134,080%
Gateway Industries
From $0.02 to $3 in a single day:
TR = (3/0.02 -1)*100 = 14,900%
Multiplied by 253 trading days — imagining that Gateway could keep this growth throughout the year, which of course is a ridiculous assumption — yields me 3,769,700% return (14,900*253 days).
Pier 1 Imports and Medifast
Using Pier 1 Imports journey from 11 cents on March 13, 2009 to its peak at $504 on May 13, 2013, we can construct pretty unfathomable returns:
TR = (504/0.01 -1) *100 = 458,081%
which I rounded to 460,000% return in four years.
For Medifast, the diet management company that still exist and is included in the S&P600 small cap index, I can generate 284,00% over 19 years by carefully selecting the starting date at December 1999 when the stock traded at $0.09. It closed on September 12, 2018 at $255,94:
TR = (255.94/0.09 –1) *100 = 284,278%
More well-known examples: Monster and Tesla
The shares for beverage company Monster’s predecessor (Hansen’s Natural) traded on Nasdaq for as low as 6 cents during May 2001 — and we can find share prices of $0.01 as recent as April 1996.
Its all-time-high from January 2018 (which is it currently approaching again) is of $68.91. Measured from the dot-com crash:
TR = (68.91/0.06 -1)*100 =114,750%
from the low-point in April 1996:
TR = (68.91/0.01 -1)*100 = 689,000%
For MNST to approach lifetime bitcoin-esque returns, say the 8,755,000% return cited above, Monster “only” needs to reach $877.51, which I obtained from running the formula in reverse:
8,775,000 = (x/0.01 -1) * 100
87,750 = (x/0.01–1)
87,751 = x/0.01
x=877.51
A share price for MNST of $877.51 might be outrageous and definitely unreachable in the next few years, but it’s “only” 1,276% return up from current levels:
(877.51/63.75–1)*100 = 1,276.49
Despite Tesla’s noticeable returns over the last few years, they simply cannot keep up in the total return-league for one simple reason: they IPOed at $17 dollars, and the stock price has never fallen low enough (the lowest I found was $14.98). That pretty much means that Tesla will never reach the never-never land of hundred thousand (or millions) of percent. Why?
The denominator is always going to be too big.
Tesla was an opportune contender for the 2010–2020 decadal trophy, as its IPO took place in May 2010. In the last eight months alone (on June 3rd, the stock bottomed out at $179.01) the stock has boomed some 158% after hitting a recent ATH of $462.06:
TR(eight months) = (462.06/179.01–1)*100=158.12%
TR (since IPO) = (462.06/17–1)*100 =2,618%
TR (since all-time-low) = (462.06/14.98–1)*100 =2,984.51%
Not bad, but nowhere near
Fairer Comparison: Bitcoin 2013–2015
Using a span to calculate more “fair” comparable numbers for bitcoin — where people could really access them over well-established exchange — is tedious as we’re dealing with a huge range.
The lowest price quote I find during this time period is from lala, and the highest yyy. Calculating returns based on current prices at around $7,800 yields the following percentage returns:
TR(2013-bottom) = (7,800/108.58 -1)*100 = 7,083%
TR(2015-top) = (7,800/1,154.93 -1)*100 = 575.3%
Now, we’re in definitely in the same league as the tech and biotech successes of the last decade.
I will fly you to the moon and back
Bitcoin’s returns are one-off. That is, they cannot repeat themselves.
Not even excessive claims about prices going “to the moon” will see bitcoin repeat its million-percent returns. Why? Because bitcoin no longer has a low base to start from.
Using today’s $7,885, a run to $100,000, $250,000 or a $1,000,000 amounts to returns of:
TR(100k) = (100,000/7,885 -1)*100 =1,168%
TR(250k) = (250,000/7,885 -1)*100 =3,070%
TR(1m) = (1,000,000/7,885 -1)*100 =12,582%
We may confidently state that bitcoin’s return dominance is over. | https://joakimbook57.medium.com/bitcoins-financial-returns-full-calculations-9c0b5f2a7c59 | CC-MAIN-2021-04 | refinedweb | 2,004 | 71.85 |
an NIS+ service.
In an NIS+ environment running in NIS-compatibility mode (also known as YP)..
NIS+ security is an integral part of the NIS+ namespace. You cannot set up security and the namespace independently. For this reason, instructions for setting up security are woven through the steps used to set up the other components of the namespace. Once an NIS+ security environment has been set up, you can add and remove users, change permissions, reassign group members, and all other routine administrative tasks needed to manage an evolving network.
The security features of NIS+ protect the information in the namespace, as well as the structure of the namespace itself, from unauthorized access. Without these security features, any NIS+ client could obtain and change information stored in the namespace or even damage it.
NIS+ security does two things:
Authentication. Authentication is used to identify NIS+ principals. Every time a principal (user or machine) tries to access an NIS+ object, the user's identity and Secure RPC password is confirmed and validated.
Authorization. Authorization is used to specify access rights. Every time NIS+ principals try to access NIS+ objects, they are placed in one of four authorization classes (owner, group, world, nobody). The NIS+ security system allows NIS+ administrators to specify different read, modify, create, or destroy rights to NIS+ objects for each class. Thus, for example, a given class could be permitted to modify a particular column in the passwd table but not read that column, or a different class could be allowed to read some entries of a table but not others.
In essence, then, NIS+ security is a two-step process:
Authentication. NIS+ uses credentials to confirm that you are who you claim to be.
Authorization. Once your identity is established by the authentication process, NIS+ determines your class. What you can do with a given NIS+ object or service depends on which class you belong to. This is similar in concept to the standard UNIX file and directory permissions system. (See "Authorization Classes" for more information on classes.)
This process, for example, prevents someone with root privileges on machine A from using the su command to assume the identity of a second user.
Figure 6-2 details this process:
NIS+ principals are the entities (clients) that submit requests for NIS+ services. An NIS+ principal may be someone who is logged in to a client machine as a regular user, someone who is logged in as superuser, or any process that runs with superuser permission on an NIS+ client machine. Thus, an NIS+ principal can be a client user or a client workstation.
An NIS+ principal can also be the entity that supplies an NIS+ service from an NIS+ server. Since all NIS+ servers are also NIS+ clients, much of this discussion also applies to servers.
NIS+ servers operate at one of two security levels. These levels determine the type of credential principals that must submit for their requests to be authenticated. NIS+ is designed to run at the most secure level, which is security level 2. Level 0 is provided only for testing, setup, and debugging purposes. These security levels are summarized in Table 6-1.Table 6-1 NIS+ Security Levels
In Solaris releases 2.0 through 2.4, you used the nispasswd command to change your password. However, nispasswd could not function without credentials. (In other words, it could not function under security level 0 unless there were credentials existing from some previous higher level.) Starting with Solaris Release 2.5, the passwd command should now be used to change your own password regardless of security level or credential status.
The
The basic purpose of NIS+ authorization is to specify the access rights that each NIS+ principal has for each NIS+ object and service.
Once the principal making an NIS+ request is authenticated, NIS+ places them in an authorization class. The access rights (permissions) that specify which activities a principal may do with a given NIS+ object are assigned on a class basis. In other words, one authorization class may have certain access rights while a different class has different rights.
Authorization classes. There are four authorization classes: owner, group, world, and nobody. (See "Authorization Classes" below for details.)
Access rights. There are four types of access rights (permissions): create, destroy, modify, and read. (See " NIS+ Access Rights" for details.)
NIS+ objects do not grant access rights directly to NIS+ principals. Instead, they grant access rights to four classes of principal:
Owner. The principal who happens to be the object's owner gets the rights granted to the owner class.
Group. Each NIS+ object has one group associated with it. The members of an object's group are specified by the NIS+ administrator. The principals who belong to the object's group class get the rights granted to the group class. (In this context, group refers to NIS+ groups, not UNIX or net groups.)
World. The world class encompasses all NIS+ principals that a server has been able to authenticate. (That is, everyone who has been authenticated but who is not in either the owner or group classes.)
Nobody. Everyone belongs to the nobody class even those who are not authenticated.
For any NIS+ request, the system determines which class the requesting principal belongs to and the principal then can use whatever access rights belonging to that class.
An object can grant any combination of access rights to each of these classes. Normally, however, a higher class is assigned the same rights as all the lower classes, plus possible additional rights.
For instance, an object could grant read access to the nobody and world classes; both read and modify access to the group class; and read, modify, create, and destroy access to the owner class.
The four classes are described in detail below.")., not UNIX it may be assigned a default group. A nondefault group can be specified for an object when it is created or later. An object's group may be changed at any time.
Information about NIS+ groups is not stored in the NIS+ group table. The group table stores information about UNIX groups. Information about NIS+ groups is stored in the appropriate groups_dir directory object.
Information about NIS+ groups is stored in NIS+ group objects, under the groups_dir subdirectory of every NIS+ domain:
Instructions for administering NIS+ groups are provided in Chapter 12, Administering NIS+ Groups.
The world class contains all NIS+ principals that are authenticated by NIS+. In other words, the world class includes everyone in the owner and group class, plus everyone else who presents a valid DES credential.
Access rights granted to the world class apply to all authenticated principals.
The nobody class is composed of anyone who is not properly authenticated. In other words, the nobody class includes everyone who does not present a valid DES credential.
There is a hierarchy of NIS+ objects and authorization classes that can apply independently to each level. The standard default NIS+ directory hierarchy is:
Directory level. In each NIS+ domain there are two NIS+ directory objects: groups_dir and org_dir. Each groups_dir directory object contains various groups. Each org_dir directory object contains various tables.
Group level or table level. Groups contain individual entries and possibly other groups. Tables contain both columns and individual entries.
Column level. A given table will have one or more columns.
Entry (row) level. A given group or table will have one or more entries.
The four authorization classes apply at each level. Thus, a directory object will have its own owner and group. The individual tables within a directory object will have their own individual owners and groups which may be different than the owner and group of the directory object. Within a table, an entry (row) may have its own individual owner or group which may be different than the owner and group of the table as a whole or the directory object as a whole. Within a table, individual columns have the same owner and group as the table as a whole.
NIS+ objects specify their access rights as part of their object definitions. (You can examine these by using the niscat -o command, described on page 172.)
NIS+ objects specify access rights for NIS+ principals in the same way that UNIX files specify permissions for UNIX users. Access rights specify the types of operations that NIS+ principals are allowed to perform on NIS+ objects.
NIS+ operations vary among different types of objects, but they all fall into one of the four access rights categories: read, modify, create, and destroy.
Read A principal with read rights to an object can view the contents of that object.
Modify. A principal with modify rights to an object can change the contents of that object.
Destroy. A principal with destroy rights to an object can destroy or delete the object.
Create. A principal with create rights to a higher level object can create new objects within that level. In other words, if you have create rights to an NIS+ directory object, you can create new tables within that directory. If you have create rights to an NIS+ table, you can create new columns and entries within that table.
Every communication from an NIS+ client to an NIS+ server is, in effect,.
Keep in mind. | http://docs.oracle.com/cd/E19455-01/806-1387/6jam6927m/index.html | CC-MAIN-2015-11 | refinedweb | 1,547 | 56.35 |
Course #:10550 Programming in Visual Basic with Microsoft Visual Studio 2010 Training 09/21/2020 - 09/25/2020 USD$2,895.00 Instructor Led Virtual. At Course Completion. Duration 5 Days Outline of Programming in Visual Basic with Microsoft Visual Studio 2010 Training. After completing this module, students will be able to: Explain how to declare variables and assign values. Use operators to construct expressions. Create and use arrays. Use decision statements. Use iteration statements. create and invoke methods. Define and call methods that can take optional parameters and ByRef parameters. After completing this module, students will be able to: Describe how to catch and handle exceptions. Describe how to create and raise exceptions. After completing this module, students will be able to: Describe how to access the file system by using the classes that the .NET Framework provides. Describe how to read and write files by using streams. Describe how to use the My namespace for reading and writing files. After completing this module, students will be able to: Describe how to create and use modules. Describe how to create and use enumerations. Describe how to create and use classes. Describe how to create and use structures. Explain the differences between reference and value types. After completing this module, students will be able to: Describe how to control the visibility of type members. Describe how to share methods and data. After completing this module, students will be able to: Use inheritance to define new reference types. Define and implement interfaces. Define abstract classes. After completing this module, students will be able to: Describe how garbage collection works in the .NET Framework. Manage resources effectively in an application.. After completing this module, students will be able to: After completing this module, students will be able to: Use collection classes. Define and use generic types. Define generic interfaces and explain the concepts of covariance and contravariance. Define and use generic methods and delegates. After completing this module, students will be able to: Implement a custom collection class. Define an enumerator in a custom collection class After completing this module, students will be able to: Integrate Ruby and Python code into a Visual Basic application. Invoke COM components and services from a Visual Basic | https://www.webagesolutions.com/courses/10550-programming-in-visual-basic-with-microsoft-visual-studio-2010 | CC-MAIN-2020-34 | refinedweb | 372 | 52.76 |
[
]
Florian Holeczek commented on JSPWIKI-731:
------------------------------------------
Hi all,
bq. I was thinking of making jspwiki.org read-only for now anyway, so stuff could be moved
fairly trivially.
@Janne: That's a good idea! Regarding redirection, domain/server movement etc., could that
wait a bit, until graduation is through? Can't be that long anymore.
Regarding the domain name references, here's my proposal. I'm thinking of three sorts of references:
a) technical references, like XML namespace references
b) project-administration-specific references, like links to the project page, references
to mailing list etc.
c) content-specific references. These are mainly references to online documentation
I'd like to change a) to Apache _now_, b) to Apache _now_ and leave c) at jspwiki.org, reorganizing
it later on.
Regarding Apache (a and b), the question is which link to choose:
Can incubator.apache.org/jspwiki be forwarded to the tlp address later on? Regarding a), does
it make sense to first choose i.a.o/j and later j.a.o? I guess not.
Regarding c), I think it makes sense to discuss and define the structure of (doc.)jspwiki.org,
and only afterwards adapt the links to it. I for one don't really get the concept behind the
current doc.jspwiki.org, which doesn't mean it's bad - I just think it should be made explicit.
Regards
Florian
> reference in 6 files
> --------------------------------------------
>
> Key: JSPWIKI-731
> URL:
> Project: JSPWiki
> Issue Type: Bug
> Affects Versions: Graduating, 2.9
> Reporter: fpientka
> Priority: Minor
> Fix For: 2.9
>
>
>: | http://mail-archives.apache.org/mod_mbox/incubator-jspwiki-dev/201207.mbox/%3C405533906.83720.1342815694658.JavaMail.jiratomcat@issues-vm%3E | CC-MAIN-2015-22 | refinedweb | 258 | 61.43 |
A simple implementation of Mustache for the Dart language, which passes happily all the mustache specs. If you want to have a look at how it works, just check the tests. For more info, just read further.
In order to use the library, just add it to your
pubspec.yaml as a dependency
dependencies: mustache4dart: '>= 1.0.0 < 2.0.0'
and then import the package
import 'package:mustache4dart/mustache4dart.dart';
and you are good to go. You can use the render toplevel function to render your template. For example:
var salutation = render('Hello {{name}}!', {'name': 'Bob'}); print(salutation); //shoud print Hello Bob!
mustache4dart will look at your given object for operators, fields or methods. For example,
if you give the template
{{firstname}} for rendering, mustache4dart will try the followings
[]operator with
firstnameas the parameter
getFirstname
in each case the first valid value will be used.
In order to do the stuff described above the mirror library is being used which could lead to big js files when compiling the library with dartjs. The implementation does use the
@MirrorsUsed annotation it will be the only check made against them (from the ones described above) in order to define a value.]'));
If you have a template that you are going to reuse with different contextes you can compile it to a function using the toplevel function compile:
var salut = compile('Hello {{name}}!'); print(salut({'name': 'Alice'})); //should print Hello Alice! install
If you are with Linux, a script is provided to run all the test:
test/run.sh
Alternatively, if you have Dart Test Runner installed you can just do
pub global run test_runner
If you found a bug, just create a new issue or even better fork and issue a pull request with you fix.
The library will follow a semantic versioning
Add this to your package's pubspec.yaml file:
dependencies: mustache4dart: "^1.0.10"
You can install packages from the command line:
$ pub get
Alternatively, your editor might support pub. Check the docs for your editor to learn more.
Now in your Dart code, you can use:
import 'package:mustache4dart/
mustache4dart.dart';mustache4dart.dart'; | https://pub.dartlang.org/packages/mustache4dart | CC-MAIN-2016-07 | refinedweb | 356 | 65.22 |
Important: Please read the Qt Code of Conduct -
Problem with OpenCV on Ubuntu
- Creatorczyk last edited by
Hi,
I want to add library Open CV to my qt project so in the pro file I added:
QT += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = ClientApp TEMPLATE = app DEFINES += QT_DEPRECATED_WARNINGS CONFIG += c++11 \ opencv INCLUDEPATH += -I/usr/local/include/opencv4 LIBS += -L/usr/local/lib -lopencv_core -lopencv_imgcodecs -lopencv_highgui SOURCES += \ main.cpp \ mainwindow.cpp HEADERS += \ mainwindow.h FORMS += \ mainwindow.ui # Default rules for deployment. qnx: target.path = /tmp/$${TARGET}/bin else: unix:!android: target.path = /opt/$${TARGET}/bin !isEmpty(target.path): INSTALLS += target
But when I try to include in mainwindow.h:
#include <opencv4/opencv2/core/core.hpp>
I get error :
/usr/local/include/opencv4/opencv2/core/core.hpp:48: error: opencv2/core.hpp: No such file or directory #include "opencv2/core.hpp" ^~~~~~~~~~~~~~~~~~
I checked the core.hpp file in this path and it is. What could I do?
@Creatorczyk said in Problem with OpenCV on Ubuntu:
#include <opencv4/opencv2/core/core.hpp>
Remove
opencv4and try just
#include <opencv2/core/core.hpp>
Your
*.profile looks correct.
What version of OCV do you have installed?
- SGaist Lifetime Qt Champion last edited by
Hi,
@Creatorczyk said in Problem with OpenCV on Ubuntu:
INCLUDEPATH += -I/usr/local/include/opencv4
You are providing the include path up to opencv4. Either remove it here, or as @Pl45m4 remove it from your includes.
Note that you do not need to add the -I with INCLUDEPATH.
- Creatorczyk last edited by | https://forum.qt.io/topic/117544/problem-with-opencv-on-ubuntu | CC-MAIN-2020-40 | refinedweb | 252 | 61.73 |
Red Hat Bugzilla – Bug 886644
python-ethtool 0.6.2 - ipv4_address shows None
Last modified: 2013-02-21 05:48:23 EST
Description of problem:
Cannot collect ipv4 address:
python-ethtool 0.6.2
== Demo ==
import ethtool
devs = ethtool.get_interfaces_info(ethtool.get_devices())
for d in devs:
print "*** Device: %s:" % d.device
print "MAC Addr: %s" % d.mac_address
print "IPv4: %s/%s Brd: %s" % (d.ipv4_address, d.ipv4_netmask, d.ipv4_broadcast)
# python pethtool.py
*** Device: breth0:
MAC Addr: 52:54:00:9C:72:7C
IPv4: None/0 Brd: None <---------------- None
# rpm -Uvh --oldpackage python-ethtool-0.6-1.el6.x86_64.rpm
Now the IPv4 appears:
# python pethtool.py
*** Device: breth0:
MAC Addr: 52:54:00:9C:72:7C
IPv4: 192.168.122.156/24 Brd: 192.168.122.255
This bug is affect RHEV-H 6.4.. | https://bugzilla.redhat.com/show_bug.cgi?id=886644 | CC-MAIN-2016-30 | refinedweb | 135 | 72.53 |
How do I return 3 separate data values of the same type(Int) from a function in swift?
I'm attempting to return the time of day, I need to return the Hour, Minute and Second as separate integers, but all in one go from the same function, is this possible?
I think I just don't understand the syntax for returning multiple values. This is the code I'm using, I'm having trouble with the last(return) line.
Any help would be greatly appreciated!
func getTime() -> Int
{
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond, fromDate: date)
let hour = components.hour
let minute = components.minute
let second = components.second
let times:String = ("\(hour):\(minute):\(second)")
return hour, minute, second
}
Return a tuple:
func getTime() -> (Int, Int, Int) { ... return ( hour, minute, second) }
Then it's invoked as:
let (hour, minute, second) = getTime()
or:
let time = getTime() println("hour: \(time.0)") | https://codedump.io/share/Fomzll6T3rzr/1/return-multiple-values-from-a-function-in-swift | CC-MAIN-2017-04 | refinedweb | 157 | 59.7 |
- NAME
- VERSION
- TUTORIAL
- AUTHOR
NAME
Meerkat::Tutorial - Getting started with Meerkat
VERSION
version 0.015
TUTORIAL
Prerequisites
If you don't already have MongoDB installed and running, see the installation guide.
Check that you can connect to the
test database from the
mongo shell:
$ mongo test
Creating Your Document Model
A Meerkat document is just a Moose class with the Meerkat::Role::Document role applied. This tutorial uses a simplified version of the
My::Model::Person class used for testing. It has a required
name attribute, and also attributes for
likes and
_id,
_collection and
_removed attributes.
Note that all attributes are read-only. You don't want to modify these directly or you'll be out of sync with the database and bad things will happen. You will update attributes using the
update methods, shown later.
Connecting to the Database
Once the document class is written, using it requires a Meerkat object to manage the connection to the database:
use Meerkat; my $meerkat = Meerkat->new( model_namespace => "My::Model", database_name => "test", );
By specifying a
model_namespace of "My::Model", the object will return collections for classes underneath that namespace. The example above will connect to the default MongoDB on localhost. If your MongoDB is running on a different host or port, you could pass
client_options which will be passed through to the MongoDB::MongoClient constructor.
Actually working with the document class requires getting. Always create objects from a Meerkat::Collection.
sync method:
$obj->sync
And should you need to get rid of a document, the
remove method will take care of it.
$obj->remove
Afterwards,
is_removed will be true and
update and
sync calls will do nothing and return a false value.
Errors
Generally, Meerkat methods return true if they executed successfully and false if they could not.
For example, if a document was removed in the database by another process and an
update or
sync is called, it will return false. (It will flag the object as having been removed from the database, but will not otherwise modify its data.)
Should any major error occur, an exception will get thrown.
Searching the Database
To retrieve a document from the database, the collection provides search methods similar to MongoDB::Collection, but which return objects from your model class.
For single objects, there are the
find_id and
find_one methods:
# find a single object my $obj1 = $person->find_id( $id ); my $obj2 = $person->find_one( { name => 'John' } );
If you have a MongoDB query for multiple objects, you pass it to
find and get a Meerkat::Cursor object back. It proxies for MongoDB::Cursor but returns objects when iterated.
my $cursor = $person->find( $query_hashref ); while ( my $obj = $cursor->next ) { ... }
Next steps
Try out the example class above using the 'test' database on your machine.
Afterwards, check out the Meerkat::Cookbook for more on working with Meerkat.
AUTHOR
David Golden <dagolden@cpan.org>
This software is Copyright (c) 2013 by David Golden.
This is free software, licensed under:
The Apache License, Version 2.0, January 2004 | https://metacpan.org/pod/Meerkat::Tutorial | CC-MAIN-2019-04 | refinedweb | 499 | 55.03 |
Asked by:
Windows Mobile slow sync
Question
Hi All,
I've finally (after 3 days) gotten my Windows Mobile 6.0 Pro app to have built in syncing. This is back to a SQL 2008 server via a WCF web service. Sync Services and WCF were both new to me so it's been a long few days.
When it finally started working (BTW anyone using CFClientBase needs to remember that your root namespace can really screw this one up!) I found it to be very slow. Initial sync I thought. On subsequent syncs it seems just as slow (even with 0 downloads and 0 updates).
I hooked into the SyncProgress event for the SqlCeClientSyncProvider and experience some really odd stuff. Essentially it seems that the same amount of data is coming down to the client from the server on secondary updates as per the initial sync.
Once the sync has finished the first time 6900ish downloads were reported by way of TotalChangesDownloaded. On secondary sync this and the TotalChangesUploaded both report 0. It seems really weird to me and after battling for so long with this and now having it working only to be so slow I need a second opinion.
Is Sync Services really meant to be this slow or have I done something stupid. BTW, when running from a desktop app the download goes really fast.
Last Q, I don't want to have to use Merge Replication and want to replace that on another of my apps. Is Sync Services (when it's working properly) faster than merge replication?
Thanks in advance for any help,
JonFriday, August 20, 2010 2:55 PM
All replies
- have you tried applying this fix?, August 20, 2010 3:25 PM
Hi,
Thanks for that. I've installed it (removing the old one from the emulator first) but it doesn't seem to be any faster. Do I have to change the app at all to use the SQLCEResultSet or is that an internal thing?
Edit: Actually the resync does seem to be faster now although it takes quite a while even with no changes. Should it be near instant if there are no changes?
Regards,
JonSaturday, August 21, 2010 8:40 AM
i guess it depends on the number of tables and sync direction.
for each table you're synchronizing, Sync Fx has to fire a query each for Inserts, Updates and Deletes. If it's BiDirectional, the same happens on both sides(client and server), add to this the queries to retrieve the current anchor values, retrieve a new anchor value and set the new anchor values.Monday, August 23, 2010 8:09 AM
Hi,
I agree that it should take a while but for the number of tables that I'm using (15 down only and 2 up only) I'm finding that a secondary sync takes on average 1 minute 40 seconds (sometimes 1 min 20 seconds). A first sync takes 3 minutes 15 seconds with 6660 inserts.
I'm now having a play with the SyncTracer to see if anything weird is going on -- I'm sure that something odd must be happening. That would be great if I could just get the logfile to output but using the trace.config.text file just doesn't seem to work. Oh well, another few days of hair pulling!
Regards,
JonMonday, August 23, 2010 9:57 AM
I'm having problems getting the SyncTracer to work - I've added in the config file for it set it up - even saving as UTF8 to ensure that it's correct but not output. I have noticed one thing, in the output window it seems that there is an exception raised just after a pause. I'm wondering if that is what is slowing the sync down. From some other posts I've seen that the SLQCE queries take a matter of 1-2 seconds max and as such I think that there is something else going on. Below is a copy of some of the Output
The thread 0xd68dad12 has exited with code 0 (0x0).
A first chance exception of type 'System.UriFormatException' occurred in System.dll
The thread 0xd68dad12 has exited with code 0 (0x0).
The thread 0xd68dad12 has exited with code 0 (0x0).
The thread 0x96ce730e has exited with code 0 (0x0).
The thread 0x3366dfe has exited with code 0 (0x0).
A first chance exception of type 'System.UriFormatException' occurred in System.dll
The thread 0x96ce730e has exited with code 0 (0x0).
The thread 0x2272d31a has exited with code 0 (0x0).
I've seen that the exception is caused by something to do with the proxy and am trying to track it down - if anyone has any pointers I'd be very grateful!
Regards,
JonMonday, August 23, 2010 12:15 PM
try enabling WCF Tracing or modify your service configuration to include exception details.Monday, August 23, 2010 4:15 PM
The exception occurs when starting a sync and the reason for the large number of them was that I had a lot of sync groups enabled. I've combined all into one sync group and the sync still takes forever but I get less of the errors and they do seem to be unrelated to the speed issue.
I'm back onto trying to get the sync trace working. I have the following in a file called trace.config.txt
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<traceSettings>
<add key="FileLocation" value="\My Documents\WorkWillYou.txt" />
<add key="LogLevel" value="4" />
</traceSettings>
</configuration>
I get nothing back and when looking at the SyncTracer.IsVerboseEnabled() status in the application it and all the others show as false. The only thing that I can come up with is that either the file isn't being read properly OR that the functionality to load the file isn't enables in the version that I'm using.
I've been refering to this thread and that tells me that I'm doing the right stuff but to no avail.
Any ideas?
Regards,
JonTuesday, August 24, 2010 9:37 AM | https://social.microsoft.com/Forums/en-US/b65822f5-a46c-44d6-9069-5b9d0297be32/windows-mobile-slow-sync?forum=syncdevdiscussions | CC-MAIN-2021-31 | refinedweb | 1,019 | 71.85 |
SOAP UI is an excellent tool to test the web services.
Though there are many tools available in the market to test the web service, I
would prefer SOAP UI for its flexibility, ease of use and vast number of
features. We have been using the SOAP UI to test various secure services, test
the connectivity between SOA servers, Load testing and performance testing etc.
I am not a full time tester and not an expert in SOAP UI tool, but this is an
attempt to unleash the SOAP UI as a developer. To be honest, many features are
learnt through trial and error. In this article, the following points are
covered:
While developing B2B application, web services plays a vital part since most of the services are exposed as web service. This enables a wide range of clients access the web service. It is really important that the web services adhere to the standard non-funtional requirements like minimum response time, no fault etc. as well as any rules imposed by the client. SOAP UI plays a major role in testing the fitness of a web service.
Right, let us start with the first SOAP UI project. This
SOAP UI project will test a simple interest calculator which is exposed as web
service. I have chosen this, because, I don’t want to spend too much time
explaining the business logic of the web service and that is also not the scope
of this article. So, our simple interest calculator will "simply" calculate the
simple interest using the formula,
Simple Interest SI = (Principal amount (P) x Number of years
(N) x rate of interest (R)) / 100,
For example, If P = 10000, N = 2 yrs and R = 20% (which no banks will give nowadays), the simple
interest would be,
SO = (P*N*R)/100 = 4000
In web service terms, the service will accept three parameters principal, number of years and rate of interest and return the interest as output. The sample code is given below;
public class SimpleInterest : System.Web.Services.WebService
{
//Default constructor
public SimpleInterest()
{
}
/// <summary>
/// This method will calculate the simple interest
/// </summary>
/// <param name="principalAmount">Principal amount</param>
/// <param name="rateofInterest">Rate</param>
/// <param name="loanPeriod">Number of years</param>
/// <returns>Simple interest</returns>
[WebMethod]
public double SimpleInterestcal(int principalAmount, float rateofInterest, int loanPeriod)
{
double interest = 0;
return interest = (principalAmount * rateofInterest * loanPeriod) / 100;
}
}
The sample request / response is given below.
Request
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope
xmlns:xsi=""
xmlns:xsd=""
xmlns:
<soap12:Body>
<SimpleInterestcal xmlns="">
<principalAmount>10000</principalAmount>
<rateofInterest>20</rateofInterest>
<loanPeriod>2</loanPeriod>
</SimpleInterestcal>
</soap12:Body>
</soap12:Envelope>
Response
<?xml
version="1.0" encoding="utf-8"?>
<soap12:Envelope
xmlns:xsi="" xmlns:xsd=""
xmlns:
<soap12:Body>
<SimpleInterestcalResponse
xmlns="">
<SimpleInterestcalResult>4000</SimpleInterestcalResult>
</SimpleInterestcalResponse>
</soap12:Body>
</soap12:Envelope>
Ok, so the web service is working fine. Now, lets go to the
SOAP UI Part.
The end point of this service is;
Picture 1: Create a new SOAP UI Project. Using file menu, create a new SOAP UI Project.
alt="Image 2" data-src="/KB/Tools-IDE/407880/Pic2.gif" class="lazyload" data-sizes="auto" data->
Picture 3: sample request / response
Edit the request tab and fill the values. Press the green
button to get the response.
alt="Image 3" data-src="/KB/Tools-IDE/407880/Pic3.gif" class="lazyload" data-sizes="auto" data->
So, the SOAP UI project to test the simple interest
calculator is working. One can edit the service to test with various values. If
there is a schema violation, the SOAP UI client will throw error. For example,
if the principal value which by definition is an integer field will throw error
if a double or alphabet is sent.
For example, if the principal amount field was sent as
100ABCD, the response would be a SOAP fault thrown by client. Similarly for any
violation in schema if the input field was enum will be handled by SOAP client
and error will be thrown back. It is a good practice to define the most precise
datatypes for the fields since it will avoid unnecessary validations at the
server end.
Similarly, if there is a fault handler available at the
service end, then the SOA fault sent by service will be caught and sent back.
Again it is a very good practice to send back valid readable error message like
"invalid principal amount" etc., rather than sending the stack trace.
Assertions are more important because, the SOAP UI is used
for testing the web service performance and therefore the fitness of a service
can be established only by having some metrics to measure the performance.
Assertions can be added to the load test as well as against
the request. The load test assertions are:
The assertions that can be added on the test step are:
A load testing of a web service must have as many assertions
as required which tests various parameters of the service. In the follow up
article, I will run a load test, which will have the following assertions.
in this article we went through a brief introduction of SOAP UI tool. More on the load testing will be added in the follow up article.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
type Status report
description Access to the specified resource () has been forbidden.
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://www.codeproject.com/Articles/407880/SOAP-UI-Part-1-Introduction?PageFlow=FixedWidth | CC-MAIN-2020-16 | refinedweb | 926 | 51.48 |
Consuming a C++ DLL in C#
July 10, 2009
While working on my current project, I had to use some low level I/O operations, but it was difficult using C#, and I got some C++ implementations. Then I thought of creating a DLL in C++ and use it in C#, but I didn’t get any code for the implementation. So I done some searching and I found a solution. It is not a complete solution, but it works
Creating a DLL using C++
For creating a DLL in C++, I was used cl.exe, which comes with .net framework. For the implementation I just wrote simple C++ file.(Simple.cpp)
#include <iostream> extern "C" __declspec(dllexport) char* Hello(); char* Hello() { return "Hello world"; }
I think this is pretty much clear.The extern “C” __declspec(dllexport) allows generate export names automatically. For more details :Exporting from a DLL Using __declspec(dllexport)(MSDN)
After creating this Simple.cpp file, go to Visual Studio Tools > Visual Studio 2008 Command Prompt. Go to the location where you have stored the Simple.cpp file and for compiling and linking C++ file you can use “cl.exe /LD Simple.cpp”.(For more details about cl.exe options checkout : Compiler Options Listed Alphabetically(MSDN) It will compile and Link, and gives a DLL as output.
Consuming a C++ library in C#
When I try to add the DLL by Add Reference, Visual Studio will not allows to add C++ library as Reference. So I tried it with Interop option, by using DLLImportAttribute.
[DllImport(@"D:\Simple.dll", EntryPoint = "Hello")] public extern static string Hello();
Then you can call this function in C# like the following
private void button1_Click(object sender, EventArgs e) { MessageBox.Show(Hello()); }
It will display a Messagebox with “Hello World”. Thats it you consumed a C++ DLL in C#.
Issue in the implementation
- I can’t use the DllImport function without the full location. To avoid this I tried to Register the DLL using RegSvr32.But I got some error from RegSvr like this.
The module “D:\Simple.dll” was loaded but the entry-point DllRegisterServer was not found.
Make sure that “D:\Simple.dll” is a valid DLL or OCX file and then try again.
I still exploring the things, I will update once I got the solution for this. Happy Coding
FILESTREAM in SQL Server 2008
July 6, 2009
SQL Server 2008 comes with lots of new features compared to the previous versions of SQL Server. One of the new feature is FileStream, which allows storage of and efficient access to BLOB data using a combination of SQL Server 2008 and the NTFS file system.
You can get more details about this in MSDN : FILESTREAM Storage in SQL Server 2008
Enable Filestream in SQL Server
By default the Filestream feature will be disabled. You can enable the filestream using SQL Server Configuration Manager under SQL Server 2008 > Configuration Tools. In this you will get all the SQL Server services. Select the Properties of the instance and select the Tab “FileStream”, from that you can enable the FileStream, you can also specifiy the instance name also.
You can also do it via T-SQL statement also
EXEC sys.sp_configure N'filestream access level', N'2' RECONFIGURE
After doing this SQL Server will create a shared folder in your machine(or in Server) with the instance name specified. (Or it will create the Windows Share name we are specifying in the textbox) Only SQL Server can access the contents.
You can check this via command prompt, using “Net Share”, you will get an output like this.
Using Filestream in the Database.
For using Filestream in your database you have to add file group in New Database screen.
Or you can do this via TSQL like this
CREATE DATABASE FileStreamDemo ON PRIMARY (NAME = FileStreamDemo, FILENAME = N'D:\DB\FileStreamDemo_data.mdf'), FILEGROUP FileStreamFileGroup CONTAINS FILESTREAM (NAME = FileStreamDemo, FILENAME = N'D:\DB\FileStreamDemo') LOG ON (NAME = 'FileStreamDemo_log', FILENAME = N'D:\DB\FileStreamDemo_log.ldf'); go
After doing this, SQL Server will create Folder in “D” drive, with name FileStreamDemo under DB directory. This FileStreamDemo folder will contains two files
- filestream.hdr – This is the FILESTREAM metadata for the data container.
- The directory $FSLOG. This is the FILESTREAM equivalent of a database’s transaction log.
Creating a Table with FILESTREAM Data
You can create a Table for consuming FileStream like this.
CREATE TABLE SQLFileSystem ( FileId UNIQUEIDENTIFIER ROWGUIDCOL UNIQUE DEFAULT NEWID() PRIMARY KEY, FileName VARCHAR(255), FileContents VARBINARY(MAX) FILESTREAM NULL default (0x) )
Thats it, you have created SQL Server Database and Table with Filestream.
Drag and Drop files from Windows to your application
July 4, 2009
While working around an Script Editor application, I found that in almost all the editors we can drag and drop files from Windows.(Even MS Notepad supports it.) Then I searched for an implementation, but unfortunately I can’t find a perfect one. Then I thought of implementing the same. I am not sure this one is a perfect implementation or not, but it works fine for me.
Here is the code. Seems like it is self explanatory
Imports System.IO Public Class frmMain Private Sub txtEditor_MouseDown(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.MouseEventArgs) _ Handles txtEditor.MouseDown 'Initiating the Drag and Drop txtEditor.DoDragDrop("", DragDropEffects.Copy) End Sub Private Sub txtEditor_DragEnter(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.DragEventArgs) _ Handles txtEditor.DragEnter 'Ensures the dragging data is valid type. 'Then only setting the drop effect. 'Otherwise you will see no drop cursor, instead of Copy If (e.Data.GetDataPresent(DataFormats.FileDrop)) Then e.Effect = DragDropEffects.Copy Else e.Effect = DragDropEffects.None End If End Sub Private Sub txtEditor_DragDrop(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.DragEventArgs) _ Handles txtEditor.DragDrop 'Getting the filename. 'The length of files array will be based on the number of files dragging. Dim files As String() = e.Data.GetData(DataFormats.FileDrop) 'Checking the files(0) is Sql File. If Path.GetExtension(files(0)).Equals(".sql", _ StringComparison.CurrentCultureIgnoreCase) Then 'Reading it using Stream reader Me.Text = String.Format("Drag Drop demo - {0}", _ Path.GetFileNameWithoutExtension(files(0))) Using sr As New StreamReader(files(0)) Me.txtEditor.Text = sr.ReadToEnd End Using Else 'Otherwise displaying message box MessageBox.Show("Only supports SQL files") End If End Sub End Class
Here is the screen shot
If some one know a better implementation please let me know.
More details from MSDN :Performing Drag-and-Drop Operations in Windows Forms
Debugging Windows Services
June 18, 2009
In the current project, I have to develop some windows services to sending out notification mails.
The first challenge I faced is I can’t directly run and debug the Windows service.
For that I need to install the service (using installutil –I ServiceName) and attach the process to Visual studio, and then only I can debug it.
It works fine for me.
Then the next challenge was, debugging the code in the onStart event. Because once the service started, then only we can able to attach it to Visual Studio. So I put some code to write to text file, and/or event log. But I feel like it’s not a good method. After searching in the net I got a nice workaround.
protected override void OnStart(string[] args) { System.Diagnostics.Debugger.Launch(); //Rest of the code }
While starting the Service, it will display a dialog like this
After selecting Yes, Visual Studio will open up and you can start debugging. You can get more information from these links
A Simple Splash screen in C#
June 12, 2009
I started my .net career in VB.Net. While developing a windows application in VB.Net it is pretty easy to put a Splash screen. There is Project property called Splash screen and you can put any form there, after that the specified form will act as a Splash screen. But when I started an windows application in C#, there is no project property called Splash screen. While doing some searching, I found lot of ways, like putting a timer and closing the splash etc. But I feel like it is not the right way of doing a splash screen, then I started my own implementation and found one. I am not sure it is good one or not, but it is working for me.
Here is the steps:
- Added one Form with an Image, as Splashscreen.cs, and my main UI is Welcome.cs
- In the Program.cs I modified the code like the following
- And in the Welcome.cs, added one parameterized constructor, with SplashScreen as the Parameter
- And in the Form_Load() event I added code to close the splash screen if exists.
- Run the application, see the splash is coming and after that Main UI is coming
static void Main() { Application.ApplicationExit += new EventHandler(Application_ApplicationExit); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); SplashScreen s = new SplashScreen(); s.Show(); Welcome welcome = new Welcome(s); Application.Run(welcome); }
SplashScreen _s = null; public Welcome(SplashScreen s) { InitializeComponent(); this._s = s; }
if (this._s != null) { this._s.Close(); } | http://anuraj.wordpress.com/ | crawl-002 | refinedweb | 1,528 | 58.89 |
Marc Chung 2009-02-24T13:04:08-07:00 Marc Chung mchung@gmail.com How Closures Behave In Ruby 2009-02-18T00:00:00-07:00 <p>Closures are commonly used to abstract over an expression or a statement.</p> <p>Ruby gives you–not one–but three ways of creating closures from a block: Using <code>Proc.new</code>, the <code>Kernel#proc</code> method, or the <code>Kernel#lambda</code> method. So what’s the difference between these three techniques?</p> <p>In Ruby 1.8<sup id='fnref:1'><a href='#fn:1' rel='footnote'>1</a></sup>, <code>Kernel#lambda</code> is an alias for <code>Kernel#proc</code>, so they actually behave identically. <code>Proc.new</code>, on the other hand, has slightly different semantics.</p> <pre><code</code></pre> <p>With Ruby 1.8:</p> <pre><code>stargate$ ruby a.rb return from kernel_proc return from within Proc.new return from kernel_lambda</code></pre> <!-- Another way of thinking about the difference in semantics, is that `Kernel#proc` (and it's alias `Kernel#lambda`) observe [Tennent's Correspondence Principle][1], while `Proc.new` violates it. The Correspondence Principle states that an expression or statement, when wrapped in a closure and immediately invoked, ought to produce the same behavior as the same expression or statement without being wrapped in a closure. As Neal Gafter [writes][2]: >. Gafter is one of the principals on the JSR to bring [Closures to the Java Programming Language][3]. Speaking of Java, --> <p>JRuby 1.1.5<sup id='fnref:2'><a href='#fn:2' rel='footnote'>2</a></sup> also observes the same semantics:</p> <pre><code>stargate$ jruby a.rb return from kernel_proc return from within Proc.new return from kernel_lambda</code></pre> <p>Ruby 1.9<sup id='fnref:3'><a href='#fn:3' rel='footnote'>3</a></sup> has a different story.</p> <p>In Ruby 1.9, <code>Kernel#proc</code> will behave identically to <code>Proc.new</code>. The reason behind this is described by David A. Black in <a href=''>this post to ruby-talk</a>:</p> <blockquote> <p>Matz agreed that it was confusing to have <code>proc</code> and <code>Proc.new</code> return different things, and said he would deprecate <code>proc</code>.</p> </blockquote> <p>Eigenclass.org also confirms that <a href=''><code>proc</code> is now a synonym of <code>Proc.new</code></a> further describing that both receive their arguments with multiple-assignment (block) semantics.</p> <p>With Ruby 1.9:</p> <pre><code>proc{|a,b|}.arity # => 2 proc{|a,b| "bacon"}.call(1) # => "bacon" Proc.new{|a,b|}.arity # => 2 Proc.new{|a,b| "bacon"}.call(1) # => "bacon"</code></pre> <p>With Ruby 1.8:</p> <pre><code>proc{|a,b|}.arity # => 2 proc{|a,b| "bits"}.call(1) # => wrong number of arguments Proc.new{|a,b|}.arity # => 2 Proc.new{|a,b| "bits"}.call(1) # => "bits"</code></pre> <p>Unfortunately, this change means that <code>Kernel#proc</code> <!-- now violates the Correspondence Principle and --> may lead to undesirable side-effects in your code:</p> <p>With Ruby 1.9</p> <pre><code>stargate$ ruby1.9 a.rb return from within proc return from within Proc.new return from kernel_lambda</code></pre> <p>With MacRuby 0.3<sup id='fnref:4'><a href='#fn:4' rel='footnote'>4</a></sup></p> <pre><code>stargate$ macruby a.rb return from within proc return from within Proc.new return from kernel_lambda</code></pre> <p>When in doubt, go with <code>Kernel#lambda</code>. It’s a safe bet.</p> <p><strong>Updated</strong>: Pending further review, I’ve omitted the bit about <code>Proc.new</code> violating Tennent’s Correspondence Principle.</p> <div class='footnotes'><hr /><ol><li id='fn:1'> <p>ruby 1.8.7 (2008-06-20 patchlevel 22) [i686-darwin9]</p> <a href='#fnref:1' rev='footnote'>↩</a></li><li id='fn:2'> <p>jruby 1.1.5 (ruby 1.8.6 patchlevel 114) (2009-01-22 rev 6586) [i386-java]</p> <a href='#fnref:2' rev='footnote'>↩</a></li><li id='fn:3'> <p>ruby 1.9.1p0 (2009-01-30 revision 21907) [i386-darwin9]</p> <a href='#fnref:3' rev='footnote'>↩</a></li><li id='fn:4'> <p>MacRuby version 0.3 (ruby 1.9.0 2008-06-03) [universal-darwin9.0]</p> <a href='#fnref:4' rev='footnote'>↩</a></li></ol></div> Why We Test Software 2009-02-16T00:00:00-07:00 <h2 id='my_first_unit_test'>My first unit test</h2> <p>I remember my first passing unit test well.</p> <p>It was written for a lab assignment for an undergraduate computer science course I took during Spring 2000 at Arizona State University, CSE200, an Introduction to Object-Oriented Programming, or something like that. Back then, though, it wasn’t called a unit test.</p> <p>CSE200 had close to a hundred students every semester with each student responsible for writing about a dozen lab assignments.</p> <p>As part of your assignment, you had to write a <code>main</code> function which read input from <code>cin</code> (or <code>System.in</code>) and passed along any arguments to the rest of your program for processing. When your program was done processing, it would write the results to <code>cout</code> (or <code>System.out</code>). To test your lab assignment, the tester (aka the QA TA) would run <code>main</code>.</p> <p>For fun, I’m told, you could ask the professor to run your assignment against the extra credit data set which basically threw all sorts of data (good <em>and</em> bad) at your program.</p> <p>Students taking this class were forced to make a decision: either they rose to the challenges of writing code to spec, or they dropped the class before the first lab assignment was due.</p> <h2 id='all_code_starts_out_as_exploratory'>All code starts out as exploratory</h2> <p>I’d be lying if I said that I could sit down at a computer and write a program that ran perfectly, without making a <em>single</em> mistake. Most engineers can’t do this, nor should they.</p> <p>When writing new code, most of my time is spent exploring ideas and intentionally proving to myself that the computer is doing what I’m telling it to. Programmers like to call this hacking, as in “I have a cool idea, give me a couple of hours to <em>hack</em> something out.”</p> <p>A programming language geared towards this kind of exploratory hacking always come with an interactive console sometimes referred to as the REPL<sup id='fnref:1'><a href='#fn:1' rel='footnote'>1</a></sup>. Languages like Ruby, Python, JavaScript, Erlang, Groovy, and Lisp ship out of the box with a REPL, while languages like C++ and the Java programming languages don’t<sup id='fnref:2'><a href='#fn:2' rel='footnote'>2</a></sup>.</p> <p.</p> <p.</p> <p>You can think of exploratory hacking as the first step to writing solid code.</p> <h2 id='writing_solid_code'>Writing solid code</h2> <p>In the <code><insert your industry here></code> industry, the most important thing you need to learn is how to communicate ideas effectively. To a software engineer, this means learning how to communicate ideas with your code which–depending on the collective professional experience of <em>you and your team</em>–ultimately means writing tests which communicate and enforce design.</p> <p>There’s a ridiculously large body of knowledge on the topic of testing, addressing important questions such as:</p> <ul> <li>Whether you should strive for 100% test coverage</li> <li>Which testing framework you should use</li> <li>Would Danica Keller code first, or test first</li> </ul> <p>My personal philosophy on testing is simple:</p> <blockquote> <p>We test software to <em>drive communication</em> between team members, to <em>define and enforce</em> the behavior of software, and to share <em>mental assertions</em> against what might one day eventually be an extremely large body of code.</p> </blockquote> <p>This means that a team sometimes needs to write a lot of tests, and sometimes it doesn’t. It also means you can get away without tests if you’re single person working on a prototype.</p> <p>At <a href=''>OpenRain</a>, when a new engineer joins our team, before they start building features, they’re assigned the task of writing tests for an existing project. Periodically, this catches them by surprise and the reaction isn’t always positive. I reassure them that this is not the case:</p> <blockquote> <p <strong>work for us</strong>, we hired you to <strong>work with us</strong>.</p> </blockquote> <div class='footnotes'><hr /><ol><li id='fn:1'> <p>A Read-Eval-Print-Loop is the coolest toy ever. If your programming language doesn’t ship with one, run!</p> <a href='#fnref:1' rev='footnote'>↩</a></li><li id='fn:2'> <p>Yes, I know about BeanShell, but I did say “ship out of the box.”</p> <a href='#fnref:2' rev='footnote'>↩</a></li></ol></div> Build mobile applications for mobility 2009-01-06T00:00:00-07:00 <p>From a talk I gave at RefreshPhoenix on January 5th, 2009.</p> <p>From 1999 to 2004, the number of mobile subscribers in Africa jumped from 7.5 to 76.8 million<sup id='fnref:1'><a href='#fn:1' rel='footnote'>1</a></sup>, an average annual increase of 58 percent. Asia, the next fastest-expanding market, grew by an annual average of 34 percent in that period.</p> <p>In the first half of 2006, Nokia delivered 153 million mobile devices<sup id='fnref:2'><a href='#fn:2' rel='footnote'>2</a></sup> to consumers, out-shipping the entire PC industry by a factor of close to three.</p> <p>By the end of 2006, there were almost 50 device makers churning out Windows Mobile devices<sup id='fnref:3'><a href='#fn:3' rel='footnote'>3</a></sup>. The really small and compact ones ones with full QWERTY keyboards.</p> <p>Apple launched the iPhone on June 29th, 2007 and sold 270,000 iPhones in the first 30 hours<sup id='fnref:4'><a href='#fn:4' rel='footnote'>4</a></sup> alone. By the end of Q4 2007, they sold 1,389,000 iPhones<sup id='fnref:5'><a href='#fn:5' rel='footnote'>5</a></sup>. In 2008, they sold over 10 million<sup id='fnref:6'><a href='#fn:6' rel='footnote'>6</a></sup>.</p> <p>Google launched the G1 on October 22nd, 2008. As of this writing, neither Google nor T-Mobile have released any official numbers, but I wouldn’t be surprised if they’ve activated close to a million devices.</p> <p>Both Apple and Google phones ship with browsers based on Webkit, which is the popular rendering engine used by all the cool kids these days<sup id='fnref:7'><a href='#fn:7' rel='footnote'>7</a></sup>. According to Android’s <a href=''>roadmap</a>, they’ve added support for an optimized JavaScript engine (Squirrelfish–also used in Safari) and synced up with a Nov 2008 Webkit release, which likely means better support for the <a href=''><code>-webkit-transition</code></a> family of properties.</p> <p>So it looks like your mobile device will run the same stack of web technologies as your personal computer.</p> <p>This is great news, right? There’s just one small problem.</p> <p>Just because there are 900 gajillion Internet-powered mobile devices running around, doesn’t mean that people are using it to surf the web, especially the JavaScript-intense, round-corner powered, 2.0 web.</p> <p>M-Metrics, mobile research firm, released a report on mobile content consumption. 85% of iPhone users browse the web on their phones vs. 58% of Smartphone (Windows, Symbian, Blackberry) vs. 13% of the overall US mobile market. <a href=''>Download</a>.</p> <p.</p> <p.</p> <p>A user behind a personal computer with 24 tabs open on their browser behaves differently than a user on a hot date. Your users are hard real-time systems that need information extracted with surgical precision.</p> <p>When designing for mobility, design for users on the move. Design for their context. That’s the key to building a successful mobile application.</p> <p>The W3C has a Mobile web best practice document which suggests that the <a href=''>mobile experience</a> should be specifically designed in mind for your end users.</p> <div class='footnotes'><hr /><ol><li id='fn:1'> <p><a href=''>Cell phone frenzy in Africa, world’s top growth market</a></p> <a href='#fnref:1' rev='footnote'>↩</a></li><li id='fn:2'> <p><a href=''>Future of Mobile Java</a></p> <a href='#fnref:2' rev='footnote'>↩</a></li><li id='fn:3'> <p><a href=''>Revenge of Windows Mobile</a></p> <a href='#fnref:3' rev='footnote'>↩</a></li><li id='fn:4'> <p><a href=''>Apple sold 270,000 iPhones in the first 30 hours</a></p> <a href='#fnref:4' rev='footnote'>↩</a></li><li id='fn:5'> <p><a href=''>Apple shipped 1,119,000 iPhones in Q4 2007</a></p> <a href='#fnref:5' rev='footnote'>↩</a></li><li id='fn:6'> <p><a href=''>Apple officially surpasses 10 million iPhones sold in 2008</a></p> <a href='#fnref:6' rev='footnote'>↩</a></li><li id='fn:7'> <p>Apple’s Safari, Google’s Chrome, Adobe’s AIR.</p> <a href='#fnref:7' rev='footnote'>↩</a></li></ol></div> How to use Method#to_ruby 2008-12-08T16:17:09-07:00 <p>In Ruby, there’s a handy dandy way to get a string representation of a method.</p> <pre>"</code></pre> <p>Uses the <a href=''>ruby2ruby</a> and <a href=''>ParseTree</a> gems.</p> Understanding operator precedence using ParseTree 2008-12-08T16:09:53-07:00 <p>A small tribute to Guy Decoux, an early Ruby programmer who once walked the Ruby parse tree to answer a simple operator precedence question posed by Matz.</p> <p>Read <a href=''>Matz’s question</a> and <a href=''>Guy’s answer</a>. Today, we can answer the same question with the following code:</p> <pre></code></pre> <p><a href=''>Guy passed away earlier this year</a>. His genius was admired and he will be missed by the entire Ruby community.</p> <p>One more gotcha on operator precedence.</p> <p>According to the Programming Ruby chapter on <a href=''>expressions</a>, the difference between the <code>&&</code> (double ampersand) and <code>and</code> operators, is precedence ordering: <strong><code>&&</code> has higher binding than <code>and</code></strong>.</p> <pre><code>>> false and true ? 'chunky' : 'bacon' false >> false && true ? 'chunky' : 'bacon' "bacon" >> (false and true) ? 'chunky' : 'bacon' "bacon"</code></pre> <p>The <code>or</code> and <code>||</code> (double pipe) operators behave similarly.</p> <p>These two code snippets also have very different abstract syntax trees. Seeing the difference will also further clarify things.</p> <pre><code>>> y pt.parse_tree_for_string("false and true ? 'chunky' : 'bacon'") - - - - - :and - - :false - - :if - - :true - - :str - chunky - - :str - bacon >> y pt.parse_tree_for_string("false && true ? 'chunky' : 'bacon'") - - - - - :if - - :and - - :false - - :true - - :str - chunky - - :str - bacon</code></pre> <p>Uses the <a href=''>ruby2ruby</a> and <a href=''>ParseTree</a> gems.</p> Gisting, an early preview of MapReduce in Ruby 2008-11-13T17:00:06-07:00 <p>Earlier this year I gave <a href=''>a talk</a> on <a href=''>ruby2ruby</a> at my local Phoenix Users group. I followed up with a longer and more technical talk at <a href=''>RubyConf 2008</a>. Not wanting to show up with a lack of code, I demonstrated the power of ruby2ruby by writing a couple of programs.</p> <p>One of the programs I wrote is called Gisting, which is an open source, Ruby implementation of Google’s MapReduce framework which simplifies writing distributed data intensive applications.</p> <pre><code>inputs = args spec = Gisting::Spec.new inputs.each do |file_input| input = spec.add_input input.file_pattern = file_input input.map do |map_input| # 2722 mailbox 2006-05-23 00:08:39 # 217 - 2006-05-23 15:41:48 # 1326 2006-05-23 18:00:30 # 2722 mailbox 2006-05-23 00:08:39 # 2722 mailbox 2006-05-23 00:08:42 # 2722 jc whitney 2006-05-23 00:25:47 1 words = map_input.strip.split("\t") Emit(words[1], "1") end end output = spec.output output.> XmlSimple.xml_in(xml1) => {"head"=>[{}], "list"=>[{"item"=>[{"id"=>"1", "content"=>"chunky"}]}]}</code></pre> <p>Ugh, every key returns an array of hashes so you’ll end up doing things like <code>hash["head"].first</code> or <a href=''><code>hash["item"]</code></a> to access values. It looks nasty, but it actually makes sense since there’s no way to know a priori whether <code>list</code> or <code>head</code> contain 1 or many items.</p> <p>Let’s try that with the XmlSimple option of forcearray => false.</p> <pre><code>>> XmlSimple.xml_in(xml, "forcearray" => false) => {"head"=>{}, "list"=>{"item"=>{"id"=>"1", "content"=>"chunky"}}}</code></pre> <p>A little cleaner, but problematic as we’ll see later.</p> <p><strong>Test #2: XmlSimple uses <code>content</code> to reference element values, so what happens if you have an attribute called <code>content</code> ?</strong></p> <pre><code>>>> XmlSimple.xml_in(xml, "forcearray" => false) => {"head"=>{}, "list"=>{"item"=>{"id"=>"1", "content"=>["chunky", "bacon"]}}}</code></pre> <p>By default, both values for the attribute and the element named “content” are returned in a single array. <strong>There’s no way to distinguish between the two.</strong></p> <p><strong>Test #3: What happens if you have more than one <code><item></code> in a <code><list></code>?</strong></p> <pre><code>>>> XmlSimple.xml_in(xml, "forcearray" => false) => {"head"=>{}, "list"=>{ "item"=>[{"id"=>"1", "content"=>"chunky"}, {"id"=>"2", "content"=>"bacon"}] }}</code></pre> <p>In this example, note that <code><item></code> returns an array of two hashes. Like I previously mentioned, there’s no way for XmlSimple to know that an element will have 1 or many items. With the <code>"forcearray" => false</code> option, a key could return a Hash or an Array depending on the XML. Not desirable, but you can probably coerce the correct behavior with the right XmlSimple configuration options.</p> <p>Now, let’s take a look at XmlSimple embedded and mixed-in with the Hash class, as it is in Rails.</p> <p><strong>Test #4: What do the Rails defaults do?</strong></p> <pre><code>>>> Hash.from_xml(xml) => {"xml"=>{"head"=>nil, "list"=>{"item"=>"bacon"}}}</code></pre> <p>No <code>id</code> attributes.</p> <p>Yikes!</p> <p><strong>Test #5: Similarly to before, what happens if you have more than one item, like in the case of xml2?</strong></p> <pre><code>>>> Hash.from_xml(xml) >> {"xml"=>{"head"=>nil, "list"=>{"item"=>["chunky", "bacon"]}}}</code></pre> <p>Same as before, the <code>id</code> attributes are removed, and <code><item></code> references both element values with a single key.</p> <p><strong>By default, <code>Hash.from_xml</code> in Rails will eat your attributes.</strong></p> <p>In summary, Ruby’s XmlSimple is bork^H^H^H^H surprising to use and in Rails, doubly so. Actually this really shouldn’t be surprising since most of these cautions are already mentioned on the <a href=''>XmlSimple</a> homepage.</p> <p><strong>Updated: January 3rd, 2009</strong>: What to use instead of XmlSimple?</p> <p>Check out <a href=''>libxml-ruby</a> and more recently <a href=''>HTTParty</a>. Check out HTTParty <a href=''>examples</a>.</p> EC2 at Phoenix Rails User Group 2008-02-21T11:00:29-07:00 <p>Recently, <a href=''>I spoke</a> at the <a href=''>Phoenix Rails Users group</a> about <a href=''>Amazon’s EC2</a> services.</p> <p>The presentation started off with a basic introduction of EC2:</p> <ol> <li>Virtual computing environment,</li> <li>Running RedHat FC4,</li> <li>With a pay-as-you-grow, no long term contract payment plan</li> </ol> <p>Since EC2 is a web service (SOAP), there’s no shortage of freely available tools that help you manage your EC2 instances, including:</p> <ol> <li>The official <a href=''>EC2 command-line tools</a></li> <li>The Firefox browser extension, <a href=''>EC2UI</a></li> <li>The <a href=''>amazon-ec2</a> RubyGem</li> <li>If you’re feeling particularly ambitious, <a href=''>the WSDL file is available too</a></li> </ol> <p>After the introduction, I talked about some of the deployment architectures that we’ve been using, including a 1-box, 2-box, and an N-box approach. Since it was a Ruby/Rails talk, I included some notes/gotchas on various configuration files and deployment scripts.</p> <p>Finally, I demoed a 2-box instance running <a href=''>MPICH2</a> and <a href=''>MPI Ruby</a>, which is a set of Ruby bindings for MPI.</p> <p>Derek Neighbors <a href=''>posted a recap</a> of the event.</p> <p>Chris Matthieu <a href=''>recorded the presentation</a> over at <a href=''>Rubyology</a></p> <p>Here are <a href=''>the slides</a> to follow along.</p> <p>Thanks to IntegrumTech for hosting the event.</p> Life imitating art 2008-02-16T16:41:59-07:00 <p>A few years ago, I read about the city of Beloit’s <a href=''>recreation</a> of George Seurat’s “Sunday Afternoon on the Island of LaGrande Jatte”</p> <p class='image'><a href=''><img src='/images/seurat_grande_jatte.jpg' alt='Sunday Afternoon on the Island of la Grande Jatte' /></a></p> <p>Beautiful.</p> <p>Last year, my friends and I went to Chicago. We stopped by the Art Institute of Chicago and did a recreation of our own.</p> <p class='image'><img src='' alt='The audience didnt want to participate' /></p> Collect with Ruby and Java 2008-02-14T08:00:00-07:00 <p>Recently I’ve been doing a lot of Ruby programming. I’ve done a lot of Java and C++ in the past, so it’s always interesting to compare styles and design techniques between languages.</p> <p>Ruby has closures which, amongst other things, allows the language to operate on collections in a compact and concise manner. For instance, take for-loops. Ruby has for-loops, but you rarely use them.</p> <p>Take the following list:</p> <pre><code>list = ["matz", "eats", "sushi"]</code></pre> <p>Instead of looping over it with:</p> <pre><code>for i in list puts i end</code></pre> <p>A common Ruby idiom is:</p> <pre><code>list.each {|i| puts i}</code></pre> <p>The power, in this case, comes from expressiveness balanced with brevity.</p> <p>There are a whole bunch of other collection methods such as <a href=''>select</a>, <a href=''>find</a>, and <a href=''>collect</a>.</p> <p>For a bunch of reasons, my favorite method is collect.</p> <p>Say you had a collection of User objects with the method <code>first_name</code>. To get a list of first names, you could do something like this:</p> <pre><code>users = [...] first_names = [] for u in users first_names << u.first_name end</code></pre> <p>But as before, idiomatic Ruby looks like:</p> <pre><code>first_names = users.collect { |u| u.first_name }</code></pre> <p>Again, brevity with expressiveness.</p> <p>Just for comparison, let’s try and do this in Java6-land. Assuming a User object with the method <code>getFirstName()</code>, one easy approach might look like:</p> <pre><code>List<User> users = ... List<String> first_names = new ArrayList<String>(); foreach(User user : users) { first_names.add(user.getFirstName()) }</code></pre> <p>But what if we wanted to call <code>User.getLastName()</code>, or <code>User.getAge()</code> which returns a totally different type. Without closures, the only approach is to duplicate the same for-loops over and over again, each with a different method call and return type.</p> <p>Is a closures-like approach possible in Java6? Let’s give it a shot.</p> <p>First, since Java6 doesn’t come with closures, you’re going to have to model one.</p> <pre><code>public interface Closure<R, T> { public R call(T t); }</code></pre> <p>A closure in this case is simply a function that accepts an object, type <code>T</code>, and returns an object, type <code>R</code>. Seeing a concrete implementation will help clear things up.</p> <p>A User object, which we’ll skip. Just keep in mind that it has a method called <code>getFirstName()</code> which returns a String and <code>getAge()</code> which returns an Integer.</p> <p>An actual closure implementation which looks like</p> <pre><code>Closure<String, Person> nameColl = new Closure<String, Person>() { public String call(Person t) { return t.getFirstName(); } };</code></pre> <p>And finally, the Collect method:</p> <pre><code>public static <T, R> List<R> collect(List<T> list, Closure<R, T> clo) { List<R> res = new ArrayList<R>(); for (final T t : list) { res.add(clo.call(t)); } return res; }</code></pre> <p>A test harness:</p> <pre><code>List<User> list = new ArrayList<User>(); list.add(new User("marc", 26); list.add(new User("michelle", 25); List<String> results = collect(list, nameColl); => ["marc", "michelle"]</code></pre> <p>To get a list of ages, your closure implementation would look like this:</p> <pre><code>Closure<Integer, User> ageColl = new Closure<Integer, User>() { public Integer call(User t) { return t.getAge(); } };</code></pre> <p>A test harness:</p> <pre><code>List<Integer> results = collect(list, ageColl); => [26, 25]</code></pre> <p>As you can see the Java solution is much longer. In Java, more <a href=''>Typing</a> means more <a href=''>typing</a>.</p> <p>An open challenge: Is a more concise approach possible in Java6?</p> <p>Frustrated with all that typing? Don’t worry, there is ongoing work to <a href=''>make closures part of the Java programming language</a>.</p> Happy Year of the Rat 2008-02-07T00:08:00-07:00 <p>Happy Chinese New Year.</p> <p>I admit I was caught by surprise at how early Chinese New Year starts this year.<br />I’ve been extraordinarily bad about keeping the traditions alive in my house.</p> <p>Specifically the one about cleaning.</p> <p>In previous years, just before the New Year, I usually spent a few weeks cleaning the entire house. You see, the Chinese culture believes that in order for good fortune to spread throughout the household, all the garbage, and rubbish, and dust, and crap must be removed before the new year. Superstitious? You bet it is. There’s even a whole process for sweeping the dirt away.</p> <p>Sweeping during the new year, sweeps your good luck away. This means no mops, brooms, brushes, or <a href=''>Roombas</a>. Sorry, no Roombas allowed during Chinese New Year. Turn those gizmos off.</p> <p>Xing Nian Quai Le</p> <p>Previously, <a href='/2006/01/how-to-celebrat.html'>how to celebrate the Lunar New Year</a></p> What I know about Honduras 2008-02-05T08:00:00-07:00 <p>Last week I was invited by <a href=''>US Southern Command</a> to speak at COPECO about the use of <a href=''>face recognition</a> as a form of biometric identification during times of crisis. (Disclaimer: I work at <a href=''>OpenRain</a> which is an affiliate of <a href=''>img surf</a> where I developed Mugr)</p> <p><a href=''>COPECO</a> (Comisión Permanente de Contingencias) is the equivalent of America’s <a href=''>FEMA</a>. They’re the organization responsible for making sure Honduras and her neighboring nations are well prepared for handling various disaster scenarios like earthquakes, tsunamis, and hurricanes.</p> <p>This was the first time I’ve been to Honduras and the first time I’ve traveled out of the United States since becoming an American citizen.</p> <p>I learned a lot from this trip.</p> <ol> <li> <p>Honduras has hundreds of bilingual schools at the preschool, primary, and secondary levels, which is the American equivalent of K through 12. One preschool taught French and Spanish: Spanish-speaking students learning French from French teachers.</p> <p>This is amazing for two reasons: 1) the students are learning two languages and 2) they start learning at a much younger age. This should be the way we teach multiple languages in America. It doesn’t have to be Spanish, because I believe there should be options like Arabic or Chinese, but we ought to encourage our kids to learn to speak multiple languages.</p> <p>Learning a new language is actually quite fun, but difficult to do if we’re only taught three to four times a week beginning at the 9th grade, as it’s done in American public schools.</p> </li> <li> <p>COPECO’s headquarters is built on a Honduran military base. The construction of COPECO was a joint effort between Honduras and America. Funding for half of the building was contributed by Honduras, and the other half by America. This was done through the efforts of the <a href=''>U.S Agency of International Development</a>.</p> <p><img src='' alt='Bienvenido a COPECO' /> Entrance to COPECO</p> <p><img src='' alt='Flag' /> Honduras’ Flag</p> <p><img src='' alt='From the American People' /> From the American People!</p> <p>During this trip, there were several other organizations demonstrating a variety of technologies aimed at supporting Honduras during a crisis.</p> </li> <li> <p>A yurt is an easily dismantled and transportable man-made shelter used by various nomadic tribes in Central Asia. A <a href=''>hexayurt</a> is a hexagonal shaped, man-made shelter, built from local resources for as little as $200USD per shelter.</p> <p>During a natural disaster, one challenge that arises is providing shelter for thousands and thousands of disaster victims. If your country doesn’t have a <a href=''>stadium</a> or a bunch of <a href=''>cancer-causing trailers</a> lying around, one option might be to construct a hexayurt.</p> <p>Hexayurts are quickly deployable, cheap to construct, and environmentally friendly which makes them highly useful for meeting human needs where available services are inadequate.</p> <p>The hexayurts we constructed in Honduras were made out of compressed wood, string, and super-powered tape.</p> <p><img src='' alt='Roofing' /> Dan making the roof</p> <p><img src='' alt='Walls up' /> Col. Bartone building the walls</p> <p><img src='' alt='Hexayurt' /> A smaller hexayurt</p> <p><img src='' alt='' /></p> <p>Completed hexayurts. Honduran army + students from local university. (Not the entire Honduran army)</p> </li> <li> <p>The <a href=''>U.S. Geological Survey</a> (USGS) provides a boatload of information geared towards assessing an earthquake’s impact.</p> <p><a href=''>PAGER</a> (Prompt Assessment of Global Earthquakes for Response) is an automated system that provides information about the scope of the potential disaster so that various agencies can prioritize their disaster response. It does this by combining information from ground instruments as well as feedback from actual people, which effectively makes it a social web application for measuring earthquake impact.</p> <p><a href=''>ShakeMaps</a> are another neat service. Earthquakes are typically measured by magnitude and epicenter. It turns out that the complexities of the Earth’s crust (rock and soil) influences the propagation of seismic waves (ground shaking) through out a region. Instead of providing simply the magnitude and epicenter, a ShakeMap represents the ground shaking produced by an earthquake.</p> </li> <li> <p>The presentation by <a href=''>Pat McArdle</a> on solar cooking pretty much blew my mind away. A solar cooker is a device that uses sunlight to cook. That’s it. No wood, no gas, no coal. Just sunlight.</p> <p><img src='' alt='' /> A solar cooker</p> <p><img src='' alt='' /> Chicken del la Solar</p> <p><img src='' alt='Chocolate freaking cake' /> Chocalate cake</p> <p>These devices are deceptively simple looking and yet they work remarkably well. Pat made a chicken dish, pasteurized water, and even baked a cake. You can <a href=''>build one easily</a> or you can <a href=''>buy one online</a>. If I didn’t believe in science, I would still be in complete disbelief that something so simple could work so well.</p> </li> <li> <p>On the last day, a small group of participants were invited to the local children’s hospital. The situation, I’m sad to share, is grim. The hospital has 400 beds, 8 intensive care units, and only 2 critical care units. The infant mortality is 23/1000. The hallways are packed and patient occupation is at 139% often resulting in two children to a bed.</p> </li> <li> <p>The military personnel responsible for organizing the event were among the brightest, most talented, and incredibly motivated group of individuals I’ve ever met.</p> </li> <li> <p>I felt incredibly ignorant (not in the pejorative sense) for not knowing more Spanish. I live in Phoenix, Arizona dammit, why don’t I already speak it?</p> </li> </ol> <p>Some fun things I learned:</p> <ol> <li> <p>You can buy Cuban cigars in Honduras and bring back a small amount for personal use. I’m talking 3 or 4 cigars, not 13 or 14 boxes. In order words, try not to look like you’re a dealer.</p> </li> <li> <p>The local word for “awesome” in Honduras, is “micizo,” pronounced mee-sue-so.</p> </li> <li> <p>Google.com will redirect you to Google.hn and localize all your results in Spanish. All your results will take you to the Spanish version of the website, if one exists.</p> </li> <li> <p>There’s a city of <a href=''>Arizona, Honduras</a>. It has a population of about 5,000. Tegucigalpa, the capital city is home to about a million people.</p> <p><img src='' alt='An evening in Tegucigalpa' /> An evening in Tegucigalpa</p> </li> <li> <p>According to our translator, Tegucigalpa is home to the the largest soccer stadium in Central America. Go fútbol!</p> </li> <li> <p>Honduras spends a large portion of it’s national budget buying down the price of oil.</p> </li> <li> <p>The president of Honduras does not live in the Presidential palace.</p> </li> </ol> <p>Check out <a href=''>more photos</a></p> Dilbert Will Teach You To Be Rich 2008-01-18T08:00:00-07:00 <p>It looks as though famed cartoonist <a href=''>Scott Adams</a> revealed the secret to finance success in <a href=''>Dilbert and the Way of the Weasel</a>. At least one person smarter than myself thinks it’s <a href=''>worthy of a Nobel Price in Economics</a>. I graduated a few years ago, so I’ve had time to formulate my own thoughts on personal finance, but let’s see how I stack up against Dilbert.</p> <ol> <li> <p>Make a will</p> <p>Nope, haven’t done that one yet.</p> </li> <li> <p>Pay off your credit cards</p> <p>Yep. In full, every month.</p> </li> <li> <p>Get term life insurance if you have a family to support</p> <p>I don’t have my own family, but in the past I’ve usually take the default plan my company offers.</p> </li> <li> <p>Fund your 401k to the maximum</p> <p>Definitely. I’ve taken the 401(k) route with every company I’ve worked for. At the very least, you should put in whatever your company matches, and the yearly limit if you can afford it ($15,500 in 2007). <a href=''>My current company</a> doesn’t do this right now, but we’re just starting out.</p> </li> <li> <p>Fund your IRA to the maximum</p> <p>Most definitely. Since the yearly limit is $3k, it’s easy to max out your Roth or IRA account.</p> </li> <li> <p>Buy a house if you want to live in a house and can afford it</p> <p>The housing market is tanking, so if you’ve been saving up for a rainy day, certainly now is the time to look into buying a house. Also, according to this MarketWatch (01/08) article, it looks like <a href=''>people are house shopping again</a>.<br />M and I bought our house back in October 07.</p> </li> <li> <p>Put six months worth of expenses in a money-market account</p> <p>And done.</p> </li> <li> <p>Take whatever money is left over and invest 70% in a stock index fund and 30% in a bond fund through any discount broker and never touch it until retirement.</p> <p>Kind of. I have a Vanguard Target Retirement Fund. The fund diversifies investment according to age. Since I’m young, apparently I can take risks like Indiana Jones, so it invest in stocks. As I get older, it plays it safe and invests in things like bonds and peanut butter.</p> </li> <li> <p>If any of this confuses you, or you have something special going on (retirement, college planning, tax issues), hire a fee-based financial planner, not one who charges a percentage of your portfolio</p> <p>I’m not really in either of those positions so…</p> </li> </ol> <p>Not a bad list. I’m lucky for a guy working in his own start up. Should they have taught subjects like this at <a href=''>ASU</a>? I’m not sure, but it sure would have been more useful than, say, UNI 194 - Introduction to being a Student aka How To Study.</p> <p>How do my fellow readers do?</p> Yet another first post 2007-10-24T08:00:00-07:00 <p>My site will be eventually moving to a Joyent powered Accelerator as well as receiving a much needed makeover.</p> <p>I hope to minimize the inconvenience, so please bare with me as I make these changes.</p> <p>I’ll write up about the redesign later, as well as the reason I haven’t been posting recently. I’ve also got a huge backlog of drafted articles in Google Docs just waiting to see the light of day.</p> <p>There are a few reasons I’m moving: I’ve been writing here for a few years now, but I’ve always been a little frustrated with the Wordpress format. I like to write articles that are a little longer than usual, intermixed with short blog posts, and I just never felt that was happening from a visual perspective. It’s time to change that.</p> <p>I’ve also been spending an awful lot of time developing in Ruby on Rails, so it makes sense to power my personal site with a Ruby-powered blogging/CMS software.</p> <p>Update your RSS feed, to something a little <a href=''>hotter</a>.</p> <p>Stay tuned.</p> Happy Year of the Golden Pig 2007-02-25T20:02:58-07:00 <p>This would be the second New Year’s greeting that <a href='/2007/01/07/when-is-a-resolution-not-a-resolution.html'>I’m seven days late</a> for.</p> <p>This Lunar New Year is special since it’s the Year of the Golden Pig, which occurs every 600 years. According to the placemat at the Chinese restaurant we had new years lunch at, the pig represents traits such as fortitude, loyalty, and honesty.</p> <p>Singaporeans, and perhaps all Asians, have an important concept called saving face. Ingrained since my childhood, saving face is a way to resolve a situation in a way that minimizes or avoids embarrassment. When in doubt, the guiding principle on saving face is to never disrespect anyone or hurt someone’s dignity. Honesty, I think, conflicts with saving face.</p> <p>Some recent and not so recent conversations on honesty:</p> <p>From The Pie (Seinfeld season 5, episode 15):</p> <blockquote> <p>Audrey: Ah! Poppie.</p> <p>Poppie: Sweetheart, hello.</p> <p>Audrey: Poppie, this is Jerry.</p> <p>Poppie: Welcome (shakes Jerry’s hand)</p> <p>Jerry: Hello Poppie.</p> <p>Poppie: Don’t fill up on the bread. I’m making you a very special dinner. Very special. (he leaves)</p> <p>Jerry: The pies. I’m going to the bathroom. You know. (he leaves)</p> <p><em>Jerry and Poppie in the bathroom. Jerry washes his hands while Poppie flushes and gets out of the stall</em></p> <p>Poppie: Ah, Jerry! Tonight you in for a real treat. I’m personally going to prepare the dinner for you and my Audrey.</p> <p><em>He zips up and leaves without washing his hands. Jerry notices it. back at the table with Audrey, Jerry can see Poppie in the kitchen with his hands in the dough, making dinner</em></p> <p>Audrey: Jerry are you OK?</p> <p>Jerry: Huh?</p> <p>Audrey: Is anything wrong?</p> <p>Jerry: No, Nothing.</p> <p>Audrey: You look like you’ve seen a ghost.</p> <p><em>Jerry can’t talk and he’s staring at Poppie’s hands. Poppie smiles and winks at him</em></p> </blockquote> <p>Later, while eating pizza and talking to P about the Seinfeld episode</p> <blockquote> <p>M: You’re telling me if I caught the chef doing that, you wouldn’t want to know?</p> <p>P: No, I wouldn’t. I just want to enjoy my pizza.</p> </blockquote> <p>Years later, while talking about P’s recent break up.</p> <blockquote> <p>M: I wish I had told you about her, but I just didn’t know if that was OK.</p> <p>P: What do you mean?</p> <p>M: Well, it’s like that pizza conversation. Even though I knew you two wouldn’t get along, I just thought you might not want to know about it.</p> </blockquote> <p>The truth is harder to set free when you’ve been raised with a cultural predisposition to avoid it, <em>especially if it’s embarrassing</em>. It would be much easier if I could ask all my single friends if they would rather eat pizza or hear my honest thoughts.</p> Refactoring, a three step business plan 2007-02-15T09:02:57-07:00 <ol> <li>Write test cases.</li> <li>...</li> <li>Profit. No, I mean refactor.</li> </ol> All your base class 2007-02-07T17:02:44-07:00 <p class='image'><img src='/images/duke_nyanya.jpg' alt='Duke: Nya nya' /></p> <p><a href=''>Actually</a>, all your ”<a href=''>compiler.misc.<strong>base</strong>.membership</a>” class do, in fact, belong to <a href=''>Java</a>. Don’t worry. According to <a href=''>Peter</a>, that compile error can’t occur and is left there for sentimental <a href=''>reasons</a>.</p> Seth on Fixing Bugs 2007-02-06T23:02:15-07:00 <p>When I read Seth’s recent post on <a href=''>apologizing to customers</a>, I couldn’t help but observe a similar approach one takes when dealing with software bugs.</p> <p>There are many incorrect ways to handle a software bug, but only a few correct ones. If you’re blessed with tact, technical know how, and a burning desire to right the wrong, then you probably already knew this.</p> <p>On a scale of 1 to 10, where 10 is the best approach</p> <ul> <li>“I didn’t do it.” (-1). Actually, you did. Last Friday at 1:42 PM. Honesty, and good source control, is the best policy.</li> <li>“It’s not my fault.” (1): It’s not personal, it’s bug triage. Your team is trying to determine what to fix, and who should fix it. No one is trying to assign blame.</li> <li>”I’m not done with it yet, don’t use it.” (1): Fair enough, but if you checked it in, you should at least write a unit test to go along with it, even if it explicitly fail()’s. This way, we know it’s not suppose to work and nobody is caught by surprise. Type II errors, or false negatives, are a huge liability for a development team because <a href=''>the tests are believed to be verifying the intended behavior of the software</a>.</li> <li>“It’s not my fault; the spec is wrong.” (2): Not a problem. Mention the behavior to a colleague or notify the team lead about the discrepancy. If two heads see a problem, then there’s probably a genuine problem. Don’t get too defensive about it and be careful not to start with “The spec is wrong…”</li> <li>“It’s not my fault the spec is wrong.” (1): What did I just say about getting defensive?</li> <li>“It’s not a bug, it’s a feature.” (3): Oh? <em>Really</em>?</li> <li>“Yes, it is a bug.” (5): Well, all right then, these things happen. What are you going to do to fix it?</li> <li>“Yes, it is a bug. Stop by in a few hours and I’ll either have a fix, or I’ll have an idea for a fix.” or “Yes, it’s a bug, but a fix is already in the works and should be in by tomorrow’s build.” (9): Brilliant and spot on. This is pretty much the response everyone wants to hear, but it doesn’t mention what actions you’ll take to prevent the bug, or similar bugs, from occurring in the future. The complete approach is:</li> <li>“Yes, it’s a bug. I have a fix. In addition, I also wrote a unit test that makes sure that bug, and bugs similar in nature, will never occur again. This way, we can prevent a whole class of bugs from occurring with one fell swoop. This is a good thing because <a href=''>life is too short</a> to only use an approach for testing that relies solely on people <a href=''>yet</a>.” OK, so in truth, you probably won’t say something like this, but that shouldn’t stop you from doing it.</li> </ul> Go Deeper 2007-02-01T08:02:05-07:00 <p>Last year, when Warren Buffet announced <a href=''>a massive donation</a> to the <a href=''>Bill and Melinda Gates Foundation</a>, he left the foundation’s CEO Patty Stonesifer one piece of advice.</p> <p><a href=''>Go deeper</a></p> <p>Two, more recent, encounters I’ve had about going deeper.</p> <p><a href=''>How To Become a Better Programmer by Not Programming</a></p> <blockquote> <strong>cultivate passion for everything else that goes on <em>around</em> the programming</strong>.</p> <p>The more things you are interested in, the better your work will be.</p> </blockquote> <p><a href=''>Just one more thing?</a></p> <blockquote> <p>Use your time, all your time, to sell just one thing.</p> </blockquote> Lisp is a fun drive 2007-01-30T08:01:08-07:00 <p>Two experiences with the <a href=''>Lisp</a> programming language.</p> <p class='image'><img src='/images/lisp_ducati.jpg' alt='Ducati' /></p> <p>The Ducati of programming languages. An <a href=''>extension of mind and body</a>.</p> <p class='image'><img src='/images/lisp_vwbug.jpg' alt='Volkswagon bug' /></p> <p>Volkswagen Lisp. <a href=''>Infinite reconfigurability</a>. Beyond college, I haven’t had much experience with Lisp, but with my recently renewed passion in programming languages, perhaps it would be a good time to test drive Lisp again.</p> Marking all as read 2007-01-29T07:01:04-07:00 <p><strong>Marking blogs as read</strong></p> <p>Happiness is mustering enough courage to say “F*ck it,” opening Google Reader and clicking “Mark all as read.” As odd as it sounds, it feels like a great burden has been lift off my shoulders. I have no idea why I have this obsessive need to stay up to date with the latest news on the tubes. In a way, it’s a bit like revolving your life around TV, which is quite ridiculous and thankfully is something I don’t do.</p> <p>New goal: I’m going to use ”<a href=''>Mark all as read</a>” more often, even for my favorites.</p> <p><strong>Reading blogs as Marc</strong></p> <p>The blogs I enjoy reading are the ones that make me realize I still have so much to grow, at least professionally and technically, like in the area of building kick ass software. Realizing this, of course, immediately throws my personal ass kicking machine into overdrive and this usually means <em>major nerding</em>. I also enjoy reading anything that completely obliterates one of my preconceived opinions and allows me to look at the world (or a problem) with a completely new perspective. Contemplation and reflection is fun.</p> <p>That being said, here are ten blogs that are currently in my “daily-reads” category.</p> <ol> <li><strong><a href=''>Artima Developer</a></strong>. Artima is a great all around community about building software. What I like about this community, is that they discuss a wide variety of programming topics. Since I recently got engaged to C++, I’ve found it’s the closest thing to <a href=''>Javalobby</a> that the C++ community has.</li> <li><strong><a href=''>Data Mining</a></strong>. This is probably one of my new favorite blogs. I discovered it last year while I was taking a data mining course. Matthew does a terrific job at pointing out observations and trends using terminology that won’t give you an aneurysm. Make sure to check out the articles in the <a href=''>data mining</a> category.</li> <li><strong><a href=''>How to Change the World</a></strong>. Guy Kawasaki: Macintosh evangelist, venture capitalist, author, and speaker. Also kicks more ass than <a href=''>Jackie Chan</a>.</li> <li><strong><a href=''>Joel on Software</a></strong>. He writes software, he writes about writing software, and he writes about the business of writing software. How couldn’t I read his blog?</li> <li><strong><a href=''>Raganwald</a></strong>. Also a new addition to my top ten and also a blog about software. The first time I ran across Reg’s blog, it was regarding <a href=''>his favourite interview question</a> which I still think about once in awhile.</li> <li><strong><a href=''>Seth Godin</a></strong>. Remember what I said earlier about learning to look at the world with a different perspective? This is just a swag, but I’d guess that 70% of Seth’s posts cause me to do that.</li> <li><strong><a href=''>Signal vs. Noise</a></strong>. I love the 37signals guys, and if you love the idea of software that is simple to use, you should too. If you read two things, make it <a href=''>Getting Real</a>, their book on building software, and their <a href=''>manifesto</a>. I don’t agree with everything they wrote in their book, but I certainly appreciate their pragmatic approach to building software. (<a href=''>Don’t write a spec</a>… seriously?)</li> <li><strong><a href=''>Stevey’s Blog Rants</a></strong>. Just when I think I <em>get</em> programming, Steve comes along and turns my entire world upside down. Three things Steve made me do: <a href=''>learn Emacs</a>, <a href=''>read Refactoring</a>, and <a href=''>write more</a>. I spent a month in Emacs writing C++ before reverting back to Eclipse. Two out of three isn’t too bad.</li> <li><strong><a href=''>The Old New Thing</a></strong>. Raymond Chen scares the sh*t out of me. Ever notice the side bar when you <a href=''>Google</a> for him? Yea that’s right, Google/Jobs bought an AdWord with his name.</li> <li><strong><a href=''>The Dilbert Blog</a></strong>. I am shocked by everything Scott Adams writes, yet I am wildly excited that he chooses to share it with the world. It pays to have a good sense of humour.</li> </ol> <p>Well that’s it. In a nutshell, seven blogs are about building better software, two are about changing the world, and one keeps me laughing while I do the other two.</p> Allergic to bad blogs 2007-01-25T22:01:30-07:00 <blockquote> <p>Me: ”I’ve been so busy,” I said to M, “I don’t even have time to read my blogs.”</p> <p>M: “You should be able to catch up this weekend.”</p> <p>Me: ”I’ll probably just read the good ones and mark the rest as read”</p> <p>M: “The good blogs?”</p> <p>Me: “Yes,” I reply, delighted I get to explain my blog reading strategy, “I have a folder of good blogs that I read first. It’s a bit like going to a restaurant and ordering the good wines first and the not-so-good wines later. As the night progresses, you drink more wine and, eventually, your palette can’t tell the difference between good or bad wine.”</p> <p>M: “But you break out in hives when you drink bad wine.”</p> <p>Me: …</p> </blockquote> <hr /> <p>No, I don’t break out in hives when I read bad blogs, but I probably should. I <a href=''>blame Google Reader</a> for my allowing my RSS addiction to flourish. With Bloglines, I found that I could subscribe to about 200 blogs before category management became a nightmare, so I had to be picky about what I subscribed to. With Google Reader–the “New Hotness” edition–I am able to break that barrier since I can manage my categories much more intuitively with the use of <a href=''>labels</a> (aka tags).</p> <p>Trust me, it’s a bad thing :-)</p> <p>It helps to read <a href=''>Digg</a>, <a href=''>Reddit</a>, or <a href=''>dzone.com</a> as they tend to aggregate the popular links, which the majority of people tend to regurgitate blog about.</p> <p><strong>Updated 1/28/2007:</strong> I picked up this tidbit from <a href=''>a comment by Robert Scoble</a> over at <a href=''>CrunchNotes</a>:</p> <table id='reading' width='100%' style='border: 1px solid #eee;'> <tr> <th /> <th>Subscriptions</th> <th>Read</th> <th>Starred</th> <th>Shared</th> </tr> <tr> <td>Scoblelizer</td> <td>504</td> <td>26,308</td> <td>Zilch</td> <td>1,473</td> </tr> <tr> <td>Chung</td> <td>266</td> <td>1,213</td> <td>5</td> <td>Nada</td> </tr> </table> <p>That’s RSS-tastic!</p> Breaking up is hard to do 2007-01-19T07:01:32-07:00 <p>How hard is it to cancel a service?</p> <p>Quite hard, according to this PCWorld article, ”<a href=''>Just Cancel the @#%$* Account!</a>”</p> <p>But it really shouldn’t be. If I were the CEO of an awesome company, of course I would be upset that users are leaving my service.. my super awesome Web 2.0 service.. after all, these users would likely include my friends and family. And I hate disappointing friends and family.</p> <p>So instead of focusing my energy on cheap tactics designed to complicate life for loved ones, I would learn why they want to leave. It might suck in the short run, but if understanding why 10 users are leaving prevents 100 more from doing so, isn’t that a better choice in the long run?</p> <p>There’s no such thing as a free lunch. As a consumer, I believe this. I dread providing my personal identity elements to companies because I know they’ll just spam me, trade it away, or lose it on a laptop. Do you really need all my information to provide a rock solid service?</p> <p>Two consumer empowering websites</p> <ul> <li><a href=''>The Consumerist</a> - Been burned by a company? BBB not doing it for you? Then bite back at The Consumerist.</li> <li><a href=''>GetHuman</a> - Calling a company’s 1-800 number? Tired of navigating the menu system? Not getting the high quality phone support you’re use to? Then use GetHuman to find the key stroke combination separating you from a real person.</li> </ul> My Top 3 posts for 2006 2007-01-07T16:01:07-07:00 <p>Top three blog posts of 2006.</p> <ol> <li><a href='/2005/01/24/performing-a-jsf-get-2/'>Performing a JSF GET</a>. I’m surprised that the JSF spec still doesn’t make this easier to do.</li> <li><a href='/2006/03/11/ssh-remix/'>Automating SSH logins with PuTTY</a></li> <li>My (Fake) Demo 2006 Review. Day <a href='/2006/02/08/demo-day-one/'>one</a> and <a href='/2006/02/08/demo-day-two/'>two</a>. A personal favorite.</li> </ol> <blockquote> <p>Step 1. Write a popular post reviewing Demo 2006 <em>without</em> even attending the conference.</p> <p>Step 2. …</p> <p>Step 3. <em>Free</em> guest pass for Demo 2007?</p> </blockquote> When is a resolution, not a resolution 2007-01-07T15:01:40-07:00 <p>It’s seven days into 2007 and I’m finally getting round to writing down my goals and resolutions for the year. I have four; they are quite modest. First, some thoughts…</p> <p>I’ve always thought New Year’s resolutions were a silly concept. Don’t get me wrong, I’m all for ambitious ideas, attaining the unattainable, doing the impossible, yada yada yada. But the thought of using the new year as an opportunity to create unrealistic and unreasonable (though super sexy) resolutions for myself just doesn’t appeal to me. And I know I’m not the only one who has repeated this pattern for the last 20+ years. To me, it’s more important to have goals that are constantly evolving and not something you redo simply because it’s a new year.</p> <p>Anyway, on to the goals:</p> <ol> <li><strong>Write for 30 to 45 minutes a day</strong>, no longer than an hour. It’s just a way to manage my thoughts for the day, possibly crystallizing them on this blog.</li> <li><strong>Read more</strong>. Not just blogs, or websites, or programming books, but real books. The ones made from pulp. I want to churn out at least two or three books a month. I do this now with technical references, and it’s just not the same. Programming languages come and go but Shakespeare will always be Shakespeare.</li> <li><strong>More triathlons</strong>. Last year, my girlfriend and I did a sprint triathlon together. We did it by going to the gym and swimming, biking, and running three to five times a week. I want to do more sprint triathlons.</li> <li><strong><a href=''>Make more mistakes</a></strong>. OK, I stole this one from a friend of mine. In our college days, we were extreme perfectionist programmers, to the point where it became impossible to release any software. It’s been awhile since our college days and we’ve both learned that being perfect isn’t exactly what life is about. It’s not even that much fun.</li> </ol> <p>Only 358 days left.</p> Wii vs PS3 vs XBox 360 2006-12-28T07:12:10-07:00 <p>Which <a href=''>7th generation gaming console</a> did <a href=''>Saint Nicholas and his six to eight black men</a> bring you for Christmas?</p> <p class='image'><img src='/images/wii_vs_ps3_360.png' alt='Wii vs. PS3 vs. 360' /></p> My CSE572 review or What I learned from the AOL search logs 2006-12-27T07:12:05-07:00 <p>Last week, I wrapped up my first grad-level class, <a href=''>CSE 572-Data Mining</a>. It was hard. Not prove ”<a href=''>P = NP</a>” hard, but “juggling new job, real life, gymming, and awesome girlfriend” hard. The class was fun, I got to learn a lot about the usual algorithms like decision trees and stumps, k-nearest neighbors, Naive Bayes classification, bagging, boosting, classifier comparisons, lots of clustering techniques–top-down, bottom-up, distance-, graph-, and density-based methods, and techniques for mining association rules, like apriori, which I’ll write about in a future post. I even got to argue with the CTO of an upcoming startup over his approach for social suggestions, which was fun, until he IPOs and I don’t :-).</p> <p>But I have to say, the really fun work was the project and all the stuff I learned outside class which, in another nutshell, includes distributed computations, first-class functions, concurrency issues, and techniques for (trivially?) parallelizing really, <em>really</em>, space and time intensive computations. I got to work with Amazon’s EC2 (Thanks Mike), a platform providing scalable hardware and bandwidth as a service, the recently released AOL search logs, and techniques for mining association rules. For my project, I decided to perform an analysis on the AOL search logs. Specifically, deriving association rules from the logs similar to the market-basket problem.</p> <p><strong>Market-basket analysis.. old and busted, or new hotness?</strong></p> <p>Let me take a second to talk about the market-basket problem. In this problem, we are given a set of all items, let’s call it A, and a large collection of transactional data. Each transaction (or basket) is a subset of A. Now the task here is to find relationships between the items within these baskets based on various factors.</p> <p>Too complicated? OK, let’s try that again.</p> <p>The canonical example of the market-basket problem is the supermarket (where the problem gets its name from). Now, instead of “the set of all items”, think “everything Safeway sells” and instead of “large collection of transactional data” think “what people purchase per visit.” Now we can find what products people tend to buy together. Knowing this, Safeway can stock their inventory, plan their sales, and market accordingly. This of course, increases ROI, embiggens synergistic… powers, and makes our lives easier overall. That’s the theory anyway.</p> <p><strong>Snap back to reality</strong></p> <p>My project was to analyze the AOL search logs in a very similar fashion. Instead of “the set of all items,” think “all unique queries in the search logs” and instead of “large collection of transactional data” think “what people search for per search session.” Now I can find out what searches people tend to make together. And what did I learn? Damn. People search for the craziest things. And by craziest I mean sexually explicit. And by people I mean you. No, not you, the person sitting next to you.</p> <p>As I previously mentioned, the project was easily the most interesting component of the course. The third and current iteration of the code is under development. It turns out that, for a variety of reasons I won’t get into right now, implementing a scalable and efficient algorithm to mine association rules is a non-trivial task. Stay tuned, I’ll try to write more about it in the future.</p> Happy Holidays To All 2006-12-24T14:12:13-07:00 <p>To my friends and family, whether it’s <a href=''>Christmas</a>, <a href=''>Hanukkah</a>, <a href=''>Yuletide</a>, <a href=''>Kwanzaa</a>, <a href=''>Lohri</a>, <a href=''>Winter Solstice</a>, <a href=''>Gantan- sai</a>, <a href=''>Eid-ul-Adha</a>, the <a href=''>Day of Santa Lucia</a>, <a href=''>Theophany</a>, <a href='' title='Christian'>Epiphany</a>, <a href=''>Hajj</a>, the <a href=''>Feast of St. Basil</a>, <a href=''>Las Posadas</a>, <a href='' title='holiday'>Twelfth Night</a>, <a href=''>World Religion Day</a>, or <a href=''>Festivus</a> (for the rest of us)–may your holiday festivities be filled with love, peace and happiness for you and yours.</p> <p>A personal thank you to Mr. Jose F. Ina for sending me such a culturally assorted seasons greeting, O Nevo Bersh!</p> Embiggening Java 2006-11-12T23:11:03-07:00 <p>From Tim Bray’s <a href=''>Ongoing</a>:</p> <blockquote> <p>Remember: However many forks there are, it ain’t Java unless it’s called “Java” or has the coffee-cup on it. If it has the name and cup, it is Java and it’s compatible. And Sun will <em>absolutely enforce</em> that in court if we have to. We have in the past and we will again.</p> </blockquote> <p>In one short, sweet, and concise paragraph, Tim alleviated concerns I had that evil-doers could flood the market with cheap Java knockoffs. I’m as much for open source as the next software engineer, but the thought of supporting 9 different compilers, 10 API implementations of the class libraries, and 3 VM platforms sends shivers down my spine. By enforcing Java strictly, Sun is giving people a way to distinguish the official Java platforms from renegade implementations.</p> <p>The facts from Mr. Bray:</p> <ol> <li>Unmodified GPL2 for our SE, ME, and EE code</li> <li>GPL2 + Classpath exception for the SE libraries. <strong>This means that the developers are free to link non-GPL code to the Java libraries; similar to LGPL.</strong></li> <li>Javac and HotSpot and JavaHelp code drops today</li> <li>Expect libraries to follow. <strong>The rest of the stack will be released in 2007</strong></li> <li>External committers are a design goal</li> <li>No short-term changes in the TCK or JCP</li> </ol> <p>By maintaining control over the TCK/trademark process, Sun gets to keep a high bar of quality and also prevents new functionality from breaking backwards compatibility. I like how this is panning out. Hats off to <a href=''>Jonathan</a>, <a href=''>Rich</a>, <a href=''>Tim</a>, and <a href=''>James</a> for doing a great job of raising their baby and enbiggening open source.</p> <p>Check out more information at <a href=''>sun.com/opensource/java</a>.</p> <p>Update: A Noble Spirit <strong><a href=''>Embiggens</a></strong> the Smallest Man</p> Visual searching with Riya's Like.com 2006-11-10T08:11:10-07:00 <p>Riya just released Like.com, a visual search engine geared towards women and their collective billions.</p> <p class='image'><img src='/images/jessica_alba_polka_dots.jpg' alt='Jessica Alba wearing polka dot shoes' /></p> <p>Imagine this, you’re walking down <a href=''>ASU Palm Walk</a> and of all the people in the world, you run into Jessica Alba who is sporting a pair of black shoes. Since they looked incredible on Jessica, the first thought that runs through your mind is to get your girlfriend a pair just like it. The problem is, you lack the basic knowledge required to purchase female foot accessories. So you do the next best thing: you take a picture of her shoes in the hopes that one day, someone will invent a search engine where you can search for shoes, visually. Then one day, you meet a <a href=''>guy</a> who runs a Silicon Valley start up called Like.com. Like.com let’s you search for images, visually. According to <a href='-'>TechCrunch</a>, Like.com creates a “visual signature” for the query image, where the signature is a mathematical representation of the image using 10,000 variables. If enough variables are identical, Like.com decides the images are similar. Right now, the site seems to be geared towards female accessories like shoes, bags, watches, etc. Some interesting tidbits from a data mining perspective:</p> <ol> <li>I remember Riya when it’s facial recognition software caught headlines back in early 2006; there were rumors of being bought out by Google. Good thing they didn’t because the work with Like.com looks promising.</li> <li>It turns out that doing facial recognition was too complicated, at least according to user feedback, so they changed the game by going after a different market: women and non-geeks.</li> <li>The engine needs to work on high-resolution versions of the image.</li> <li>The software deconstructs these images into approximately 10,000 data points (or, I’m guessing attributes), which include:</li> <li>Characteristics like color, texture, material, shape, pattern, brand, style, and blingness, etc.</li> <li>To process the jewelry set takes 20GB of RAM.</li> <li>Shoes and bags are the easiest items to search for. Which is just as well since they are probably the easiest to shop for.</li> </ol> <p>Now, you can take that picture of Jessica’s shoes and start punching in words that describe it. Black. Shoes :-). Ok, ok, Black, open, toe, polka, dot, shoes. Viola.</p> <p class='image'><img src='/images/likedotcom_polkadot.jpg' alt='Like.com results' /></p> <p>I showed my girlfriend the website:</p> <blockquote> <p>Michelle: Type in Manolo Blahnik Me: Umm, [as I type in “M-a-n-a-l-o B-l-a-n-i-k”] and how do you spell that [Hits Enter]? Oh cool, it made a spelling suggestion, look “Manolo Blahnik.”</p> </blockquote> <p>Pretty cool stuff!</p> Always on 2006-11-09T21:11:32-07:00 <p>I don’t know how other people do it, but I find it hard to tune out work or school mode.</p> <p>Last weekend, my girlfriend and I saw <a href=''>2 Pianos and 4 Hands</a>:</p> <blockquote> <p>Richard, playing as a Conservatory teacher: <em>Good afternoon, this is your 7th grade examination at the Conservatory. This means you’ll be tested on techniques, terminologies, history, hearing tests, arpeggios, and, of course, you’ll play scales in a key of my choosing, which I’ve decided to be <a href=''>C. Sharp</a>.</em></p> </blockquote> <p>It’s funny how much I think about code (or algorithms) on a daily basis.</p> <p>The show was a blast. I couldn’t stop laughing at the dialog, and I thoroughly enjoyed the musical performance.</p> Self-eating code 2006-10-28T08:10:50-07:00 <p>Computer Programmer Clinton Eugene Curtis testifies that <a href=''>Tom Feeney tried to pay him to rig election vote counts.</a> Feeney was Speaker of the Houe of Florida at the time, but is currently US Representative representing the Florida 24th</p> <blockquote> <p>Congress: “Assuming for the moment that such software to rig a vote was used in one or more machines in Ohio or Florida, could you today detect that, if you could look at the source code?”</p> <p>Clinton Eugene Curtis: “If you can get the machine, and they have not been patched yet and then take those machines, decompile them, which I couldn’t do, but possibly a [person from] Microsoft or MIT could do. You might, you might, be able to see them.”</p> <p>C: “You might?”</p> <p>CEC: “Yes, you might, it depends on how good they are destroying what they had.”</p> <p>J: “Destroying what they had by tampering with the machine they had access to or destroying the instuctions on the machine in the first place.”</p> <p>CEC: “Either or both. You didn’t actually see what’s in there , so you don’t know if the code is running in a single executable or if the code is running in various modules. if it’s running in modules, <strong>you can make the code actually eat it self</strong>.”</p> </blockquote> <p>… audience expresses amazement …</p> My favorite NPR moment 2006-10-28T08:10:27-07:00 <p>October 16th, <a href=''>the day before America hit 300 million</a> users citizens.</p> <blockquote> <p>Robert Siegel: “Justin Timberlake, whom you’re listening to, you of course knew that already, is hot right now. I’ve never heard this song before but it is the nation’s number one pop single and it’s called <em>Sexy Back</em>”</p> </blockquote> Layability, a lesser known software metric 2006-10-16T22:10:36-07:00 <p>It has come to my attention that the good folks over at the SEI forgot one important software metric.</p> <p>From jwz’s ”<a href=''>Groupware Bad</a>”</p> <blockquote> <p>So I [<a href=''>jwz</a>] said, narrow the focus. Your “use case” should be, there’s a 22 year old college student living in the dorms. How will this software get him laid?</p> <p>That got me a look like I had just sprouted a third head, but bear with me, because I think that it’s not only crude but insightful. ”<strong>How will this software get my users laid</strong>” should be on the minds of anyone writing social software (and these days, almost all software is social software).</p> <p><strong>“Social software” is about making it easy for people to do other things that make them happy: meeting, communicating, and hooking up</strong>.</p> </blockquote> <p>From a recent Newsweek Q&A with Steve Jobs, ”<a href=''>Good for the Soul</a>”</p> <blockquote> <p>Newsweek: Microsoft has announced its new iPod competitor, Zune. It says that this device is all about building communities. Are you worried?</p> <p! <strong>You’re much better off to take one of your earbuds out and put it in her ear. Then you’re connected with about two feet of headphone cable.</strong></p> </blockquote> <p>From a <a href=''>Slashdot comment</a></p> <blockquote> <p>Of course, I mention that I know BASIC. Next night, we’re at my apartment, using my room mate’s TI Silent 700 to log into the Wellsley PDP/11 (Simmons didn’t have their own computer) via its acoustic coupler and the phone’s handset. I check her work, fix a few mistakes, and run her program. Looking over the results, printed out on that thin thermal paper, our eyes meet…</p> <p>Yeah, <strong>BASIC got me laid. Perl, not so much</strong>.</p> </blockquote> <p>Layability: A runtime quality of the system which describes the ease at which the end user can get laid. Not to be confused with Interoperability.</p> Zen and C++ 2006-10-08T16:10:34-07:00 <p>A <a href=''>programmer</a> walks into a C++ Kung Fu Studio and has the following conversation with the resident <a href=''>master</a><a href='#sorry'><sup>1</sup></a>.</p> <p>Programmer: I want to learn C++. I’m willing to spend time and money learning. How long will it take me to master C++?</p> <p>Master: It will take you 10 years to master C++.</p> <p>Programmer: But master, I cannot wait that long. I will do anything you tell me to do. I’ll even work for you for free.</p> <p>Master: Hmm, well in that case, it will likely take you 30 years.</p> <p>Student: Master, first you said 10 years, then you said 30 years. I will work far more intensively than anyone else. How long would it take me?</p> <p>Master: Well in that case you will have to remain with me for 50 years. Someone in such a hurry as you are to get results seldom learns quickly.</p> <p>I don’t know about you, but whenever I need to learn a new language, there’s such a strong temptation to buy a dozen “Teach yourself <em>XYZ</em> in 24 hours” or “Learn <em>ABC</em> in 30 Day” books.</p> <p>Overcome it.</p> <p>As Norvig writes in ”<a href=''>Teach Yourself Programming in Ten Years</a>,” it takes a lot more to be successful at programming. Some ingredients I can relate to:</p> <ol> <li>Do it because it’s fun. Seriously, if you’re going to have to put in 10 years, you really need to find programming fun.</li> <li>Talk to other programmers.</li> <li>Write code often. More importantly, improve code often.</li> <li>You don’t have to be the best programmer on all projects. It’s ok to be the worst, provided you learn what the best ones do… and what they don’t do.</li> <li>Maintain software. By doing so, you will inevitable curse, spite, and learn how to design your programs to make it easier for those who will maintain it after <em>you</em>.</li> <li>Learn different programming languages. Different paradigms (OOP, functional, parallel, declarative) allow you to think differently.</li> <li>Participate, but be careful, in a language standardization efforts. Don’t shave the yak.</li> </ol> <p><a href=''><a href='#sorry'>1</a></a> 老子/孔子, 请原谅我.</p> Sentiment analysis 2006-10-07T02:10:45-07:00 <p><a href=''>Data mining the world for anti-U.S. sentiments</a></p> <blockquote> <p.</p> </blockquote> <p><snip></p> <blockquote> <p>The approach, called natural language processing, has been under development for decades. It is widely used to summarize basic facts in a text or to create abridged versions of articles.</p> <p>But interpreting and rating expressions of opinion, without making too many errors, has been much more challenging, said Professor Cardie and Janyce M. Wiebe, an associate professor of computer science at the University of Pittsburgh. Their system would include <strong>a confidence rating for each “opinion” that it evaluates and would allow an official to refer quickly to the actual text</strong> that the computer indicates contains an intense anti- American statement.</p> </blockquote> <p>Let’s hope that something like <a href=''>M-x spook</a> on Emacs doesn’t render the $2.4 million system ineffective</p> Tainted spinach 2006-10-07T02:10:18-07:00 <p><a href=''>Scared of spinach?</a> Here are some vitamin and mineral packed dark, leafy green alternatives:</p> <ul> <li>Swiss chard</li> <li>Baby bok-choy</li> <li>Collard greens</li> <li>Kale</li> <li>Turnip greens</li> </ul> <p>Thanks <a href=''>NPR</a>!</p> Previously unreleased bibs and indexes of NSA publications 2006-10-03T01:10:19-07:00 <p>Imagine an <a href=''>organization</a> so secretive, the <a href=''>index and bibliographies of their internal publications</a> were hidden from the public, for the last 40 to 50 years, until just recently.</p> <p>Browsing through the PDFs, I’m surprised (and a little sad) to find topics about software engineering that may still be relevant today.</p> <ul> <li>Prototyping Man-Machine Interface to Facilitate Early Identification of Software Deficiencies - Winter 1986</li> <li>Structured Testing as a Learning Tool - Winter 1991</li> <li>Error Messages: The Importance of Good Design - Spring 1992</li> <li>Designing Secure Reliable Software -A Methodology - Fall 1976</li> <li>FUZZY: An Evolutionary Model for Data Structures - Summer 1979</li> <li>Software Maintenance -The Other Side of Acquisition - Summer 1978</li> <li>Software Maintenance: Putting Life Back into the Life Cycle - Winter 1987</li> <li>Work Breakdown Structure: A Better Implementation to Manage Software Overruns - Fall 1980</li> </ul> <p>Some other topics relating to data mining and information retrieval.</p> <ul> <li>The Apparent Paradox of Bayes Factors - Winter 1965</li> <li>Full-Text Searching: Coming of Age - Fall 1989</li> <li>The Association Factor in Information Retrieval - Winter 1961</li> <li>Information Storage and Retrieval - Fall 1963</li> <li>The use of the B-Coefficient in Information Retrieval - Fall 1968</li> <li>Probabilities of Hypotheses and Kullback-Leibler Information-Statistics in Multinomial Samples - October 1956. (When creating decision trees, KL can be used to partition the datasets.)</li> <li>Reference Patterns for Nearest Neighbor Rule - Winter 1977</li> <li>So You Want to Correlate - Spring 1965</li> </ul> <p>Looks like they also did book reviews.</p> <ul> <li> <p>Book Review: <a href=''>Structure and Interpretations of Computer Programs</a> - Fall 1990</p> </li> </ul> Less costs more 2006-10-03T00:10:49-07:00 <p>Precisely <a href=''>why big movie studios simply don’t get it</a>.</p> <blockquote> <p.</p> <p>The studios still hate that, because they think digital movie downloads should be priced higher than physical DVDs, even though there are no physical production, distribution or inventory costs. <strong>They should cost more, the reasoning goes, because of the added convenience to consumers.</strong></p> </blockquote> Google Reader 2006-09-30T17:09:23-07:00 <p><a href=''>You</a> had me at <a href=''>List View</a>.</p> <p>Now, if I could just figure out how to rename my “tags” AND magically star all the older articles I’ve checked “Keep New” under that other <a href=''>popular blog reader</a>.</p> <p>Ironically, you can’t search the feeds you’re subscribed to. And, it doesn’t render correctly with <a href=''>Opera</a>.</p> <p>Update: Sometime in the future around 2009: Search is integrated and more than awesome. Reader still doesn’t work well under Opera.</p> Visualizing DNA 2006-09-25T00:09:33-07:00 <p>A year late, but interesting since I’m currently taking a <a href=''>Data Mining</a> course. According to the Sept 2005 edition of Nature, chimps and humans share 96 percent of the same genetic material.</p> <p><img src='/images/clint_the_chimp.jpg' alt='Clint the Chimp' /></p> <p>Clint the chimp was the source of the DNA that scientists used to map the chimpanzee genome.</p> <p>National Geographic: <a href=''>Chimps, Humans 96 Percent the Same</a>. With a statistic like that, journals and articles should really make an effort to provide screenshots. I’m not talking about <a href=''>bar graphs or pie charts</a>; I mean some sort of visual eye candy that makes me say “Oh sh*t, that does look like 96%.” Something like what Dr. Eamonn Keogh out of UC Riverside did with his work on <a href=''>visualizing the similarity of human and chimp DNA</a>. Make sure to watch the video comparing human and chimp DNA.</p> 3 Eclipse articles 2006-09-24T18:09:05-07:00 <p>The first article is a short tutorial on the Eclipse Modeling Framework (EMF) and the Graphical Modeling Framework (GMF). What is the EMF? From <a href=''>the EMF website</a>, “EMF is a Java framework and code generation facility for building tools and other applications based on a structured model.” Let me paraphrase: EMF allows you to describe your object model in a neutral structure, the XML Metadata Interchange (XMI).</p> <p>There are several ways you can generate/write this XML:</p> <ol> <li>XML-heads can create the XMI document directly, using a text editor</li> <li>Hard core UML OOA/D-<em>icts</em> can generate XMI using tools like Rational Rose</li> <li>Java-heads can annotate Java interfaces with model properties</li> <li>Finally, if you’re writing an application that must read/write XML, you can use XML Schema to describe the model</li> </ol> <p>Now why would you, Java Master/Mistress of the Universe, want to do any of this?</p> <p>Because the EMF provides the foundation for interoperability between other EMF-based tools and applications. You can create a single model, in EMF, and your organization can develop several tools and applications based on that model. Since the majority of an Eclipse RCP application consists of Editors and Views, the advantage of EMF becomes obvious after you’ve developed your 15th Editor, and you begin to discover that there’s a significant amount of boilerplate code that each Editor needs, such as validation, listening to model changes, tracking model versions, etc.</p> <p>This is where GMF gets exciting. From <a href=''>the GMF website</a>, “GMF provides a generative component and runtime infrastructure for developing graphical editors based on EMF.” Let me paraphrase: GMF takes your model (generated in EMF) and transforms it into a full-blown graphical editor. Both EMF and GMF are projects under development and hosted at <a href=''>the Eclipse Foundation</a>.</p> <p><a href=''>Learn Eclipse GMF in 15 minutes</a></p> <p>The second article is about how to draw custom Table and TreeItems. If you’re getting started with Eclipse RCP, and you had to pick one component to learn masterfully, I would highly recommend the SWT Table–as well as the JFace TableViewer, TreeViewer, and TableTreeViewer components. As <a href=''>I mentioned before</a>, the recent release of Eclipse Rich Client Platform 3.2 offers significant improvements to the Table component, that this article describes very well.</p> <p><a href=''>Custom Drawing Table and Tree Items</a>.</p> <p>Finally, the third Eclipse link is to the eRCP, where the “e” stands for <strong>embedded</strong>. From the eRCP website, “the intent of the eRCP project is to extend the Eclipse Rich Client Platform (RCP) to embedded devices.” This release provides support for the Nokia Series 80 and the Windows Mobile 2003/5 mobile platforms. Why is this important? Two observations:</p> <ul> <li>Last year, Nokia, outshipped the entire PC industry by a factor of close to three, delivering 153 million mobile phones to consumers. Almost all almost all those devices ship with a version of the Java ME. [Source: Altima, <a href=''>Future of Mobile Java</a>].</li> <li>Today, there are around 50 device makers churning out Windows Mobile devices, such as Cingular 8125, T-Mobile’s SDA and MDA, Treo 700, HP’s new line-up, the Motorola Q, and the new Samsung i320 [Source: GigaOm, <a href=''>Revenge of Windows Mobile</a>]</li> </ul> <p><a href=''>Eclipse eRCP homepage</a></p> Got sugar? 2006-09-19T12:09:01-07:00 <p>According to the <a href=''>Center for Science in the Public Interest</a>, a nutritional advocacy group, the Starbucks Frappuccino is equivalent in calories to <a href=''>a McDonald’s coffee plus 11 of their creamers and 29 packets of sugar</a></p> <p>Imagining later today:</p> <blockquote> <p>Hi, Could I get a Quad Ristretto, Venti, 1/2 Breve, 1/2 Organic, Decaf, Upside Down, Double Blended Frappuccino with Caramel Sauce, Extra Ice, and Whipped Cream.</p> <p>You know, I better make that sugar-free and non-fat instead.</p> </blockquote> White and Nerdy 2006-09-18T07:09:58-07:00 <p class='image'><img src='/images/white_and_nerdy_schrodinger.png' alt='White and Nerdy' /></p> <p>Priceless</p> <blockquote> <p><em>Happy Days is my favorite theme song I could sure kick your butt in a game of ping pong I’ll ace any trivia quiz you bring on I’m fluent in JavaScript as well as Klingon</em></p> </blockquote> <p>Check out the video on YouTube: <a href=''>Weird Al Yankovic’s White and Nerdy</a>. Finally, since it was obviously the first question on your mind, the physics equation seen throughout the video is the time-independent form of the <a href=''>Schrödinger wave equation</a>.</p> A voting machine virus 2006-09-14T15:09:55-07:00 <blockquote> <p>An attacker who gets physical access to a Security Analysis of the Diebold AccuVote-TS Voting.</p> </blockquote> <p>The latest findings on Diebold’s voting machine isn’t pretty. Physical access to a machine is all it takes to inject vote stealing code: the lock to side door containing the memory card can be picked, and the memory card can be replaced with evil code which can be loaded in the system. Check out the <a href=''>full research paper</a> and the <a href=''>video demonstrating an attack</a>.</p> 5 years on... 2006-09-11T11:09:33-07:00 <p class='image'><a href=''><img src='/images/gaping_void_20060911-200.jpg' alt='' /></a></p> Some energy tips from SRP 2006-08-22T22:08:26-07:00 <p>Is it possible for an energy company to advocate power conversation in the household? A brochure from SRP sure makes me think so.</p> <p class='image'><img src='/images/powerwise.jpg' alt='Power Wise' /></p> <ol> <li><strong>Every degree you raise your thermostat saves you approximately 2-3% on cooling costs.</strong> Crush your energy bill by installing a programmable thermostat. Set it between 78°F (23.8°C) and 80°F (26.6°C) degrees when home and 85°F (29.4°C) or higher when away. Use a ceiling fan if possible.</li> <li><strong>Keep it cool with electric bills. Place sun screens over windows and save on air-conditioning</strong>. Shaded windows can save up to 25% of the cost of air-conditioning, when compared to unshaded windows.</li> <li><strong>Run your dryer during morning or late evening to avoid adding heat to your home when it’s warmest out.</strong> Keep it cool. Dry clothes during the cooler part of the day.</li> <li><strong>Nearly 90% of energy used to wash clothes goes to heat water.</strong> Defeat the enemy of inefficiency in laundry. Wash in cold water when possible. BONUS: Your clothes don’t shrink.</li> <li><strong>Compact fluorescent bulbs use 75% less energy and last up to 10 times longer.</strong> Don’t be lured in by energy-wasting glow of incandescent light. Use compact fluorescent bulbs. Ikea sells bulbs that require fewer watts but provide just as bright light</li> </ol> <p>Just doing my part to reduce my daily energy consumption.</p> A Box.net Review 2006-08-15T21:08:05-07:00 <p><a href=''>A friend of mine</a> recently wrote about his experience with the free online file storage service, <a href=''>Box.net</a>. I admit I wasn’t surprised to hear about his less than stellar experience, as I ran into several situations where the Box.net crew left me wondering if they were actually serious about running their company.</p> <p>I have a similar list of issues, but not from the perspective of a user, but as a developer of their <a href=''>public API</a>.</p> <p>Flashback to February, Aaron contacted me with a request to do a review on the relaunch of Box.net. I really didn’t want to write a review, but I wanted to do something useful for them, so when I noticed they had a developer API, I decided to do them a favor and provide an implementation in Java. It started out easy enough; a very simple REST API–you send HTTP, they send XML.</p> <p>Fast forward a few months, several emails, and no results later, the list of problems with their API had grown, or perhaps I had just discovered all of them. Since sending email to them doesn’t seem to have any positive effect, I thought it would be nice if I provided issue tracking services by listing the bugs (and gripes) I have with their API. So, in no particular order:</p> <ol> <li>None of the developers hang out on the <a href=''>chat room</a> anymore.</li> <li>The documentation is terrible; there are values that aren’t documented, and there are results that aren’t even mentioned.</li> <li>There is an error on line 141 of /var/www/box/mod<em>Account</em>Upload.php</li> <li>File uploads don’t work if the file already exists. In addition, the response doesn’t indicate a failure.</li> <li>If the request is incorrectly constructed, a PHP fatal error occurs. An XML response with details on what I missed would be helpful.</li> <li>Of course, you couldn’t prove any of this since the <a href=''>API documentation page</a> is password protected and requests for access fall on deaf ears.</li> </ol> <p>The last bullet point really made my day. All of a sudden and without warning, the page–you know the one documenting the publicly available API–became private.</p> <p>Now, if you’re reading this, you might be asking yourself: “Jeez, why is this guy making such a big deal about a bad API?” You know what, in the grand scheme of things, it probably isn’t. In fact, by tomorrow, I will likely forget what I wrote for bullet point 4. But then again, the same guys running the company wrote the API… the buggy, undocumented, and closed API.</p> Learning SWT 2006-07-31T21:07:52-07:00 <p>Getting started with a new framework is not an easy task, especially if it’s a UI toolkit such as Eclipse’s SWT. One way, I’ve found, that works with me is to peruse snippets of code that get straight to the point. The <a href=''>org.eclipse.swt.snippets</a> project in the Eclipse CVS repository does just that. The project, which can be checked out via Eclipse, is an excellent illustration of techniques and UI widgets available to an SWT developer. I highly suggest you check out the project and run each snippet. Ok, maybe not each snippet, but you should definitely spend some time browsing them.</p> <p>For instance, <a href=''>Snippet231</a> illustrates an SWT Table with multi-line columns. Before Eclipse 3.2, a third party SWT library had to be used to emulate that functionality.</p> <p>To check out the Snippets project from Eclipse</p> <ol> <li> <p>File > New > Project</p> </li> <li> <p>CVS > Projects from CVS</p> </li> <li> <p>Create a new respository location with the following information</p> <blockquote> <p>$CVSROOT=:pserver:anonymous@dev.eclipse.org:/home/eclipse</p> </blockquote> </li> <li> <p>Or just enter the following details</p> </li> </ol> <p class='image'><img src='/images/eclipse_cvs_dialog_screenshot.png' alt='Eclipse CVS Snippet' /></p> <p>Viola, you should be playing around with SWT snippets in no time. Visit <a href=''>SWT Snippets</a> for more information.</p> Power of Ten 2006-07-04T10:07:34-07:00 <p>I remember watching this video as a child and having my thoughts instantly occupied with dreams of science and discovery.</p> <p align='center'> <object height='350' width='425'> <param name='movie' value='' /> <embed src='' type='application/x-shockwave-flash' height='350' width='425' /> </object> </p> <p>I still feel the same way today. BTW, there’s a kiosk at the <a href=''>Skydeck</a> atop the <a href=''>Sears Tower</a> in <a href=''>Chicago</a> with the same video.</p> Meeting Bob Parsons 2006-05-25T23:05:57-07:00 <p>This past Tuesday (5/23) I attended an ATW meeting where I got to hear Bob Parsons speak about the secrets to his success: luck and perspective. This was the first time that I had met Bob Parsons but I read his <a href=''>blog</a> frequently and listen to his <a href=''>podcast</a> occasionally, so I had a pretty good idea of what to expect. As it turns out, I was mostly familiar with his story, but it was still a huge pleasure to hear him speak. From the perspective of a software engineer, here’s what I got out of the talk:</p> <ul> <li>His companies were started from scratch and with no investors. As of today, he is still GoDaddy’s single and only investor.</li> <li>He is definitely a nerd. He taught himself BASIC on a short flight and wrote software to do everything he needed.</li> <li>Perspective is knowing how to think about a problem; doing this will allow you to be in control of the problem.</li> <li>Luck.. is just that, luck. But he also took risk, broke rules, and worked incredibly hard.</li> <li>Borrowed $5k to buy an IBM/PC when they first came out.</li> <li>MoneyCounts was priced at $99, then $69, and finally $12 before it finally made a ton of sales.</li> <li>MoneyCounts had a 5.5 day release cycle.</li> <li>Today, GoDaddy has over 30 software development teams.</li> <li>Intelligence has nothing to do with business success.</li> </ul> <p class='image'><a href='/images/bob_parsons_and_marc_chung_l.jpg' title='Bob Parsons and Me'><img src='/images/bob_parsons_and_marc_chung_s.jpg' alt='Bob and me' /></a></p> <p>Bob also took a moment to share his 16 rules of survival. I’m listing it here, even though <a href=''>you can read it over at his blog</a>.</p> <ol> <li>Get and stay out of your comfort zone.</li> <li>Never give up, if it were easy, everybody would be doing it.</li> <li>When you’re ready to quit, you’re probably a lot closer than you think. The temptation to quit is greatest when you’re just about to succeed.</li> <li>Make it a point to accept the worst thing that could happen to you. Very seldom will the worst consequence be anywhere near as bad as a cloud of “undefined consequences.”</li> <li>Focus on what you want to have happen. If you dream it, it will happen.</li> <li>Take things one day at a time</li> <li>Always be moving forward. Remember the Japanese concept of Kaizen: Small daily improvements eventually result in huge advantages.</li> <li>Be quick to decide.</li> <li>Measure everything of significance. If you measure it, it will improve.</li> <li>Anything not managed, will deteriorate.</li> <li>Pay attention to your competition, but pay closer attention to what you’re doing.</li> <li>Don’t get pushed around.</li> <li>Life is not fair.</li> <li>Solve your own problems. Don’t follow others.</li> <li>Don’t take yourself seriously. We’re usually in less control than we think; Luck plays a bigger role.</li> <li>Always have a reason to smile- Find it. “We’re not here for a long time; we’re here for a good time.”</li> </ol> <p>Thanks Bob!</p> Voter turnout in the U.S. 2006-05-25T20:05:03-07:00 <p>An interesting comparison between voter turnout for the 2006 American Idol Finale and the <a href=''>2004 U.S. Presidential election</a>.</p> <p class='image'><img src='/images/us_vs_ai_2006_voter_turnout.png' alt='2004 US General election voters vs. 2006 American Idol voters' /></p> <p>Source: <a href=''>ZabaSearch</a></p> <p>Update: Looks like the Huffington Post agrees: <a href=''>Hicks Wins Idol After “63.4M Votes Were Cast This Season”…More Than Any US President In History Has Received…</a></p> Hanzis for Silicon Valley 2006-04-12T08:04:20-07:00 <p>Today, Google announced their new Chinese new name, 谷歌.</p> <p>At long last, the Chinese names for the GYM triumvirate is finally complete:</p> <p><strong>G</strong>oogle - 谷歌 - gǔ gē - Valley Song</p> <p><strong>Y</strong>ahoo! - 雅虎 - yǎ hǔ - Elegant Tiger</p> <p><strong>M</strong>icrosoft - 微软 - wéi ruǎn - Small & Flexible</p> <p><a href=''>Valley Song</a> is a song by Jars of Clay.</p> <p>Incidentally, Elegant Tiger is the nick name of a character from the chinese xiao shuo, Water Margin. In the story, Elegant Tiger, or <a href=''>Yan Shun</a>, is known for his strength.</p> <p>Thanks, Eden for the great <a href=''>CE dictionary</a>.</p> HR 4437 2006-04-10T06:04:33-07:00 <p>In less than 24 hours, hundreds of thousands of people will be gathering across every metropolitan city across the United States to protest the <a href=':'>Border Protection, Antiterrorism, and Illegal Immigration Control Act of 2005</a> (H.R. 4437).</p> <p>Every year, thousands of immigrants from Mexico and South America come to the United States to seek a better opportunity for themselves and their families. They take up jobs that most Americans won’t perform and do it outrageously low wages. H.R. 4437 is going to make it a crime for illegal immigrants to be in the United States. It also places a set of broad powers in the hands of the Department of Homeland Security to take sweeping actions without any checks and balances.</p> <p>You should check out this thoughtful piece by danah boyd on <a href=''>why she opposes h.r. 4437</a>.</p> The Art of API development 2006-03-26T11:03:27-07:00 <p>Writing a good API is not an easy task. Like any other piece of software, you need time to talk about requirements, get some design going on a whiteboard, and do lots and lots of testing. If you work hard, at the end of the day, you’ll have another component to add to your arsenal of software, which you’ll be glad to have when you run into a similar problem down the road. I’ve learned some good and bad things about API design, mostly by practice (read: making mistakes) so I thought share some thoughts about what I think makes a good API. If there’s a flaw or a gaping void, please leave a comment, as I’d like to hear your thoughts on the subject.</p> <ol> <li><strong>Be Focused</strong>. You’ve got to focus on the problem. To do this well, you must do two things. First, you have to dig for those requirements. They aren’t going to come to you, so you have to go after them, which leads me to the second point. Speak with your intended audience. Become intimate with the problems they are trying to solve. Bounce ideas off each other and listen to feedback.</li> <li><strong>Document</strong>. Be fanatical about documentation. Document everything from HTML-friendly Javadoc at the method, class, and interface level, to suggested working examples of how your API should be used in your project’s homepage, release notes, and/or blog. Document exceptions, parameters, constructors, and packages (overview.html). Tossing in an image of the <a href=''>“big picture”</a> won’t hurt. Document intention, as it’s far more valuable to know what the programmer intended. Don’t just duplicate your source code in the documentation, otherwise you’re just repeating yourself and you run the risk of having the documentation drift out of sync with the source code.</li> <li><strong>Be Intuitive and Simple</strong>. Did you read the previous point? Did you document every iota of your API inside and out? Do you even have a blog that you use to post advice on how to best use your API? Great. By the way, nobody is going to read it, well not at the very beginning anyway. You have to apply the “don’t make me think” approach to your API. It’s like a really well polished UI that requires very little training and is easy to pick up. If you make it intuitive to use, people will get a good impression with it from the start. Similarly, you need to get that initial positive reaction to your API and one way to do this is by making it intuitive to use, even without documentation. Things are intuitive if they fit into a person’s mental model. Keep things simple and people will love you for it.</li> <li><strong>Ask (Hard) Questions</strong>. Should this API support generics? The <code>enum</code> type instead of a <code>String</code> object? Should my factories be singleton objects lying around in memory forever? Should I return null, throw an (unchecked or checked) exception, or return an empty, non-null array of zero length? How much boilerplate code should I place in an abstract class? Will this be thread-safe? Immutable and reusable? between n-threads? Should I load all limited resources up front and manage them in a pool or a lazily initialize them? The answers will vary slightly by kind of API you’re developing and the requirements you have, but make sure you ask them.</li> <li><strong>Use Interfaces</strong>. In your API, always make the type as generalized as possible. If you use <code>Map</code> instead of <code>Hashtable</code> you insulate yourself against future changes to the choice of <code>Map</code> implementations. Similarly, your Super XML/REST parser should accept an <code>IXmlParser</code> instead of a <code>ConcreteDomXmlParser</code> or a <code>ConcreteSaxXmlParser</code>; let your users decide which strategy to use. Now, don’t go refactoring every method in every class you have out to an interface. Figure out what can be reused and remember to keep details of how an implementation works to a minimum.</li> <li><strong>Eat your own dog food</strong>. That’s right, you wrote an API, now write a program that uses the API. Better yet, write three. If you’re writing an API that manipulates images, write a quick desktop app that can return the image as an SVG, or a web app that returns it as a JPG. Or better yet, do both. An API should be about how the user thinks, eating your own dog food forces you to do this. If you’re releasing an XML/RESTful API, pick a language and write an XML-to-Object parser and maybe even an Object-to-XML parser. By doing this, you’ll find out just how easy it is to parse your own XML, or figure out that a service is returning too much XML, or if there are too many inconsistencies, etc. Remember, your APIs first user will be your test cases. Write them early and assert everything. If you find your API too cumbersome to use or too complicated to test, you may want to rethink some decisions. Refactoring makes this process trivial.</li> <li><strong>Minimize visibility</strong>. Dealing with visibility is a tricky issue. On one hand you don’t want to make everything private since it may conflict with the reusability or extendability factors of your API, but on the other you don’t want users of your API doing things that they shouldn’t be doing. The argument can be made either to make everything <code>protected</code> to maximize reusability or to minimize visibility and increase scope later, if the need arises. I take the latter, though I’ve heard good reasons for the former. Either way, you’re going to have to document those reasons; if a class or a method is not meant to subclassed, specialized, or overridden kindly mention why. Always deliberately pay attention to the scope your methods and variables have.</li> <li><strong>Have a friendly license</strong>. Choose a license that deliberately communicates your intent. If you want to be friendly to businesses, make sure you find a license that let’s developers take your API, build something cool on top of it, and not have to worry about any legal repercussions. If you want to enforce the rule that all software built on top of your API is to be freely available, there are licenses for that too. Either way, you’ll want to make sure your intent is clearly communicated.</li> <li><strong>Grow</strong>. Finally, if you’ve decided to release your software to the public, thank you. Doing this is no easy task, especially if you have something that people really want to use. This final point is meant to highlight the relationship you’re going to have with the community. Make sure you a process (forum, blog, newsgroup, defect tracker, wiki, etc) that let’s you listen and respond to the feedback of your users. Just like any social software community (frameworks like JSF, platforms like Eclipse, OSes like Linux) you have to listen to your users, tweak and retweak the API so that it can grow. Be careful not to go feature crazy, otherwise you’ll swamp yourself with work, violate the principle of simplicity, go outside the bounds of your original problem, and end up with something completely unmanageable.</li> </ol> <p>These are just a few heuristics I’ve found work best for me. You shouldn’t blatantly violate them, but you also shouldn’t follow them blindly. You’re going to find that achieving API nirvana is next to impossible, but you should try anyway.</p> <p><strong>Updated a few hours later</strong>: Wrote closing statement & fixed grammar.</p> Seth speaks at Google 2006-03-06T13:03:38-07:00 <p>“Technology gives you a chance at marketing.” What an unsual, mind twisting, nail biting, nerve wracking, unpossible new idea for a software engineer like myself to comprehend–I freaking love it. <a href=''>See Seth Speak</a></p> Singapore is a fine, a real fine country, 2006-03-06T07:03:29-07:00 <p>”..kena pay all the time, bankrupt all my money”. Pulling up a <a href=''>satellite view of Singapore</a> using Google Maps brought back some good memories.</p> <p>Although I haven’t been back in about 12 years, I still remember good things about her.</p> <ol> <li><strong>Cuisine</strong>. I could talk for hours about what I remembered. Newton Hawker Centre, Cuppage Centre, Adams Road Hawker Centre, Indian food, Chinese food… It just doesn’t stop. You can’t claim to be a food lover, and not have been to Singapore. Satay, kuay tieu, roti, pratha, curry, dim sum, nasi goreng, laksa, durian.</li> <li><strong>MRT (SMRT)</strong>. Awesome public transportation. I remember taking Somerset to Yishun to watch movies at the Yishun 10 Cineplex.</li> <li><strong>Singlish</strong>. Add one part tamil, one part malay, one part english, and one part chinese and you’ve got an local slang that you either love or hate. I haven’t practiced in years though, so I’ve completely forgotten how to speak it. :(</li> <li><strong>Soccer</strong>. Two words, Fandi Ahmad. Boo ya ka shaw.</li> <li><strong>Nightlife</strong>. Not just clubbing, but in general places don’t close at 1 or 2am like they do here in Phoenix. I’ve heard the nightlife is amazing, but I was too young to be interested.</li> <li><strong>Orchard Road, Centerpoint, Yishun 10, Jurong Bird Park, Haw Par Villa, Botanical Gardens, Far East Plaza, Lucky Plaza, even Changi Airport</strong> were fun places to visit as a kid.</li> <li><strong>Chinese New Year</strong>. Especially festive with my family</li> <li><strong>Malaysia</strong>. There’s not much I remember about Johor Baharu or Penang, other than cheap movies, eating a lot, and the Golden Sands Hotel.</li> </ol> <p>I’ll have to write about a list of things I don’t miss about Singapore. Oh, and that lyric was by a local Singaporean band (at the time, >10 years ago) called the Kopykat Klan that doesn’t seem to be around anymore.</p> <p><strong>Updated Mar 8 2006</strong>: Ran spell check on “Johor Baharu”</p> DEMO 2006 - (Fake) Day 2 2006-02-08T22:02:43-07:00 <p>It’s been a pretty crazy day (not being) at DEMO 2006. (Not actually) Going to this event has taught me a lot about what makes a great demo. Here is the remaining review of the companies and their services or products:</p> <ul> <li><a href=''>mypeople</a>: Looks like an unlimited coast-to-coast cell phone service plus a personal concierge service for cell phones. Reminder calls, wakeup calls, sport scores, etc.</li> <li><a href=''>Eqo communications</a>: Here’s the use case: Someone calls you on Skype (PC). EQO’ installed software routes the call to your handset, all this without high-speed wireless or being on a 3G network.</li> <li><a href=''>Zink kat</a>: Chili, according to their webpage, really doesn’t look like anything. It looks like a box, and I think music is involved. According to TJ and Jeff’s page, it looks voice activated, and it plays more music than you can chuck a stick at.</li> <li><a href=''>Transparensee</a>: It looks like another discovery/recommendation engine. Understanding relationships between items is complicated. Take restaurants for instance. It’s easy to recommend restaurants based on genres, or cars based on specifications, but what about dating? Hair color–brunette, eyes–brown, height–5’ 6”, ok, and what about chemistry? How do you recommend chemistry?</li> <li><a href=''>Nexidia</a>: Audio mining; speech analytics; NLP. Freaking Cool!</li> <li><a href=''>Kosmix</a>: I’ve also been hearing a bit of buzz about Kosmix’s subject- oriented search engine. For now, the three subjects are health, travel, and politics. I hope to see more subjects like real estate, or automobile repair, or even a legal search (sort of like Westlaw).</li> <li><a href=''>Truveo</a>: Video search. It’s like <a href=''>YouTube</a> or <a href=''>Google Video</a> without the community, the videos, or the remotely accurate search engine.</li> <li><a href=''>Panoratio Database Image</a>: A technology spun off by Siemens. Put confusingly, it’s a tool that can reduce the size of the result set without losing any details. I’d like to hear what sort of mathamagical compression algorithms they are using since it sounds too impressive.</li> <li><a href=''>Zimini</a>: Ok, so I have an idea: I’m going to write this program that people will download. They can then submit their personal information (providing us as much as they want, of course) and in return we’ll give them coupons. Right!</li> <li><a href=''>Sproutit</a>: It seems like an email management service for small businesses. It reminds me of <a href=''>Basecamp</a> or <a href=''>Salesforce.com</a>. I have to admit, I didn’t know there was a demand for outsourced email management.</li> <li><a href=''>Eeminder</a>: No, not reminding, eeminding. They push “reminders” to your cell phone. I can’t even pretend to be excited about technology like this.</li> <li><a href=''>Iotum</a>: Looks like a highly configurable rules engine that can route incoming office calls to IM, email, your calendar, your companie’s bluetooth enabled toaster, etc, etc. I guess this is perfect for the kind of person that get’s a ton of calls. To do all this, the software taps into your company’s IP-PBX. Sounds neat.</li> <li><a href=''>Open Connect</a>: Old and busted: “Mainframes and green screen” New hotness: “Web-based UIs and web services”. soaComprehends takes your mainframe interactions and builds a custom web-application that optimizes your user mainframe interactions. If you know what all of that means, I feel truly sad for you.</li> <li><a href=''>Sharpcast</a>: Transparently share photos between your PC and your phone. I guess this would rock if your phone has a lot of memory and a nice screen.</li> <li><a href=''>LocaModa</a>: I text message a phone number, and the message appears on a medium. (<a href=''>See live example</a>).</li> <li><a href=''>BroadRampCDS</a>: <em>“BroadRamp CDS™ Content Delivery System is the world’s first multimedia content delivery system that delivers a broad spectrum of media by converting existing content into online interactive multimedia.”</em> Let me translate: “Broad spectrum” = AVI, MPEG, DIVX, XVID. “Online interactive multimedia” = “Flash, whatever the latest version is”.</li> <li><a href=''>Vizrea</a>: Looks like another cell phone photo management service. Looks like they are exclusively running on Nokia phones.</li> <li><a href=''>Smilebox</a>: An online scrapbook service. I hope it’s simple enough to use. My gut feeling tells me that it sounds like the sort of software that should run on the desktop, as opposed to on the web.</li> <li><a href=''>Newsgator</a>: I like where Newsgator is going: feed ubiquity. They released a Hosted Solution service.</li> <li><a href=''>VividSky</a>: <em>“Have you ever found yourself sitting at a sporting event with your attention away from the action only to hear the roar of the crowd?”</em> No, not really. I suppose if you were to put wireless access points in football stadiums, accessing unlimited game content was the next logical thing to do. I’d like to see a real fan do this. <thinking>Let me put my beer down, shove my popcorn under my left armpit, lick my fingers clean, whip out the latest Treo 700w, and "access" that content.</thinking>. Meanwhile, the play is being shown over and over again on 10 of the 50 ginormous overhead projectors, and my buddy is screaming at me for spilling the beer. Right.</li> <li><a href=''>Simplefeed</a>: I wish the website cut down on the ROI talk, and focused on getting me signed up. From the “About” page, it looks like an RSS manager (like <a href=''>Feedburner</a>), except that there doesn’t seem to be any possible way to signup.</li> <li><a href=''>Azos AI</a>: Looks like two products which convert your phone into SUPER CRISIS PHONE during an emergency.</li> <li><a href=''>StrikeForce</a>: <em>“WebSecure’s breakthrough technology proactively stops keylogging programs by encrypting keystrokes at the keyboard level and rerouting them directly to your browser.”</em> Cute. My beef: it works only under Internet Explorer; it’s a bandaid covering the real problem–that you have a keylogger; and if someone really wanted your keystrokes, they could tap into the browser and read every FORM input field on the webpage. Quite a false sense of security</li> <li><a href=''>MI5</a>: A rack mountable unit capable of detecting spyware traffic, spyware in webpages, spyware in “phone home” applications, spyware infections, and pretty much any sort of malware in your enterprise. It sounds incredibly comprehensive. I’d like to see it in action.</li> <li><a href=''>Astav</a>: Fraud protection. Can’t really tell from the website. Apparently it’s a password-replacement technology. Not sure how it’s integrated with existing systems.</li> <li><a href=''>PayWi</a>: Not to be confused with Pei Wei, Pay Wi let’s you pay bills, transfer money, purchase stuff online with your cell phone. Doesn’t the rest of the world do this already?</li> <li><a href=''>Pay By Touch</a>: No need for credit cards or checkbooks, or cash, now you can pay with your thumbprint.</li> <li><a href=''>Shimon Systems</a>: No need for passwords, now you can login to wireless network with your thumbprint.</li> <li><a href=''>Cesura</a>: Uptime management services. You get a page or a text message if your system is down.</li> <li><a href=''>Fortify Software</a>: Fortify Application Defense appears to be a J2EE application protection tool that guards code by injecting extra boundary checks at the bytecode level. The <a href=''>demo</a> looks like it manipulates the bytecode of your deployed WAR file. Just a couple of things <puts on Java hat>: that application was pretty terribly written to begin with. 1) Strings should be sanitized and escaped before being placed in an SQL statement (or just use a PreparedStatement) 2) Never let your servlet container display stack traces. Always redirect the user to a friendly 404 page.</li> <li><a href=''>IronPort</a>: From TJ: <em>“[T]heir newest product today scans all inbound web traffic and gives all of them a reputation ranking. Only traffic with a certain ranking goes through. So basically it is a spam filter not just for your inbox but for your whole network working with 1GigBit/s.”</em> Cool!</li> </ul> <p>Well that’s all folks. For a real account of what happened at this year’s DEMO 2006, please visit <a href=''>TJ</a> or <a href=''>Jeff</a>.</p> A (not actually real) DEMO 2006 review 2006-02-08T07:02:28-07:00 <p>DEMO 2006: If I <strong>were</strong> attending this year’s DEMO conference, this is a review of my first day might look like:</p> <ul> <li><a href=''>Moobella</a>: It’s an entire ice-cream factory on the go. If you’ve always wondered what a twinkie ice-cream would taste like, Moobella answers that question. My (tasty) suggestion: Apply some sort of collaborative filtering technique on flavors.</li> <li><a href=''>Blurb</a>: Blurb let’s you convert your digital content into a paperback. If you’re a blogger, a digital scrapbooker, or that guy with a ton of grandma’s old recipes, and you want to produce a book from your writings, then you should check out Blurb.</li> <li><a href=''>Bones in Motion</a>: Think of software that tracks your location through your cell phone. The flagship product appears to be a piece of software that tracks your outdoor fitness achievements via the cell phone/GPS. The idea itself doesn’t sound terrible exciting (since I eat Krispe Kreme and Twinkies for breakfast), but the underlying technology fascinates me. Developing an application that runs on multiple cell phone platforms AND provides location- based services via GPS–now that’s cool!</li> <li><a href=''>MP3Car</a>: Commoditized Car PC parts.</li> <li><a href=''>Digismart</a>: You know that scene in Star Wars where R2D2 projects a 3D animation of Princess Leia? It looks like these guys are stepping in that direction. Digismart let’s you project your image from handheld devices on to a wall about three feet away.</li> <li><a href=''>Accomplice</a>: I hope the world is ready for <a href=''>yet</a> <a href=''>another</a> To-Do list application.</li> <li><a href=''>Grassroots Software</a>: I couldn’t really find out too much about this product, but I guess if non-linear presentation software AND taking on Microsoft head first is your thing.</li> <li><a href=''>Network Streaming</a>: Ok, let me sum these guys up. 1) Download Joel Spolsky’s <a href=''>Aardvark specification</a> 2) Implement said specification (smart summer interns optional) 3) Prof^H^H^H^H DEMO 2006.</li> <li><a href=''>Peppercon</a>: KVM-over-IP? In 2006?</li> <li><a href=''>TinyPictures</a>: Tiny niche. I hope they do something 100x more awesome than <a href=''>TextAmerica</a> and <a href=''>Flickr</a>.</li> <li><a href=''>Ugobe</a>: <em>“We develop and market revolutionary robotic technology that transforms inanimate objects into lifelike creatures exhibiting stunning, organic movement and dynamic behaviors.”</em> It’s Furby 2.0.</li> <li><a href=''>Zingee</a>: Share files. Great idea, but I’m biased since I did something like this back in college. One small problem, the Windows client relies on the NET 1.1 Framework. Well two problems really: 1) Where are the Mac and Linux clients? 2) Users have to download the .NET Framework 1.1. If you really want wide adoption, may I suggest using MFC or WTL. Maybe even consider wxWidgets for those cross platform needs.</li> <li><a href=''>Garageband</a>: It looks like some sort of socialized rating system for music. I wonder what they’re doing differently than <a href=''>Pandora</a> or <a href=''>Yahoo! Launch</a>.</li> <li><a href=''>Multiverse</a>: A small step towards the commoditization of the <a href=''>World of Warcraft</a>, <a href=''>Second Life</a>, and all those other incredibly addicting MMORPGs.</li> <li><a href=''>GuardID</a>: A secure USB keychain for computer passwords. Appears to work only on Microsoft Windows.</li> <li><a href=''>biggerBoat</a>: <em>“The Internet’s most comprehensive, entertainment industry-specific search engine delivering cross-category, cross-format, and cross-retailer search results to online entertainment consumers. We currently provide music and movie results to our partners, with television, video games, and books coming soon.”</em>Sounds like something Amazon’s obidos engine can handle.</li> <li><a href=''>Gravee</a>: A community powered search engine. Not a bad idea. When they do achieve some sort of critical mass, I wonder if results could potentially be skewable by the community. Results are taggable (finally, an adult-themed tag-cloud) and there’s even a specialized blog search.</li> <li><a href=''>Polyvision</a>: An electronic virtual whiteboard. I want to replace the whiteboards, currently covering the walls of my company, with this technology. There is definitely a need for more tools that let virtual teams work together.</li> <li><a href=''>VSee</a>: If you think video conferencing software sucks, then chances are you’re not using Apple’s iChat, which is just as well since the VSee demo appears to be Windows-only.</li> <li><a href=''>Kaboodle</a>: Hmmm, social shopping? I personally take recommendations from friends and specialty review sites. With the guerilla marketing tactics I’ve been <a href=''>reading</a> <a href=''>about</a> lately, it’s even more important to me that recommendations can have some degree of trust associated with it. I’m not sure how Kaboodle handles this.</li> <li><a href=''>Plum</a>: Collect, Share, and Discover content. Cool! Sounds a little like Google Base.</li> <li><a href=''>RawSugar</a>: Sharing knowledge is good. The site goes down randomly, so I couldn’t figure it out</li> <li><a href=''>Riya</a>: I remember hearing about this idea a few months ago. It’s basically one of the first facial recognition web applications. I wish they would team up with Facebook or Orkut or Picasa to do something cool.</li> <li><a href=''>Tagworld</a>: If MySpace is <a href=''>ghetto by design</a>, then maybe Tagworld is the opposite.</li> <li><a href=''>Miaplaza</a>: Social recommendations? You’re kidding, right?</li> <li><a href=''>Krugle</a>: Search engine for publiclly available source code. 1) I wonder if I can search for examples of specific design patterns 2) Screenshots primarily list Java, can I search for a hash map implementation in Scheme? 3) If krugle searches mailing lists, how does it tell if the code is a “good” or a “bad” example? 4) Can I annotate and mark up code?</li> <li><a href=''>Jitterbit</a>: Looks like a really amazing web services management tool. From what I can tell, you can control (through their downloadable client) a ton of web service APIs from Amazon, eBay, Google, Eventful, etc. The tool lets you make XML (SOAP/REST) requests to the various web services and displays the results immediately. From the screenshot, it looks like you can schedule calls, perform XSL transformations, and mashup results from different services. I hope results are persistable to a database. Written in Java (NetBeans RCP?), so it’ll run on everything.</li> <li><a href=''>IPSwap</a>: Think Craigslist or eBay for intellectual property. Definitely by developers, for developers.</li> <li><a href=''>Loglogic</a>: Looks like a Log analyzing engine for all sorts of logs. HTTP, SSH, Samba, FTP, Proxy, SMTP, etc. Works on Unix and Windows environments</li> <li><a href=''>Persystent Technologies</a>: Virii, worms, registry malfunctions, deleting key files are no longer the problem when you can restore the system to a previous state with very little intervention from IT or NetworkStreaming.</li> <li><a href=''>Avokia</a>: It looks like a high availability solution for “The Enterprise(TM)”. They appear to take the “We scale everything horizontally” approach.</li> <li><a href=''>Extricom</a>: According to the press release, it looks like they released a wireless LAN product that boosts channel capacity three-fold. In other words, more <em>internets</em> for everyone.</li> <li><a href=''>iGuitar</a>: A simple USB adapter that connects your guitar to your PC or Mac, allowing you to capture music on your companyer. Very cool.</li> </ul> <p>So that wraps up my first fake day at DEMO 2006. For real and actual coverage, check out TJ’s Day 1 coverage <a href=''>here</a> and <a href=''>here</a>, as well as <a href=''>Jeff’s Day 1 coverage</a>.</p> Dear DEMO 2006 2006-02-07T18:02:47-07:00 <blockquote> <p>Dear <a href=''>DEMO 2006</a>: I need a feed. I want minute-by-minute coverage of the actual demos. I need a website that doesn’t behave badly under Firefox. And while I’m up here, why are you advertising for DEMOfall 2006 already? You’re not even done with DEMOnow?</p> </blockquote> <p><falls off slippery box> I can’t seem to find that much live coverage of DEMO 2006. I found a pretty good write up at TJ’s Weblog <a href=''>here</a> and <a href=''>here</a>. I also managed to find a complete list at the DEMO.com website. From what I can grep, it looks as though this year’s underlying theme is all about providing services with a more human touch (the technorati call this, “Web 2.0”). Lots of old ideas look like they’ve come back with a vengeance and an emphasis on being more specialized, personalized, and socialized.</p> Simplicity 2006-02-01T08:02:49-07:00 <p>Simplicity. Take a moment out of your software writing, caffeine inducing, image photoshopping, animation authoring, interaction designing day and remember that technology should be making our lives less complicated.</p> <div class='quoted'> <blockquote> <p>The ability to simplify means to eliminate the unnecessary so that the necessary may speak.</p> </blockquote> <p> <p>–<a href=''>Hans Hofmann</a>, Introduction to the Bootstrap, 1993</p> </p> </div><div class='quoted'> <blockquote> <p>A well-designed and humane interface does not need to be split into beginner and expert subsystems.</p> </blockquote> <p> <p>–Jef Raskin, <a href=''>The Humane Interface: New Directions for Designing Interactive Systems</a></p> </p> </div><div class='quoted'> <blockquote> <p>Simple things should be simple and complex things should be possible.</p> </blockquote> <p> <p>–<a href=''>Alan Kay</a>, Disney Fellow and VP of R&D, The Walt Disney Company.</p> </p> </div><div class='quoted'> <blockquote> <p>Simplicity is the ultimate sophistication.</p> </blockquote> <p> <p>–Leonardo Da Vinci</p> </p> </div><div class='quoted'> <blockquote> <p>Things should be made as simple as possible, but not simpler.</p> </blockquote> <p> <p>–Albert Einstein</p> </p> </div><div class='quoted'> <blockquote> <p>It is simplicity that is difficult to make.</p> </blockquote> <p> <p>–Bertholdt Brecht</p> </p> </div><div class='quoted'> <blockquote> <p>Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction.</p> </blockquote> <p> <p>–E.F. Schumacker</p> </p> </div><div class='quoted'> <blockquote> <p>Life is really simple, but we insist on making it complicated.</p> </blockquote> <p> <p>–Confucius</p> </p> </div> How to celebrate the Lunar New Year 2006-01-27T08:01:45-07:00 <p>To my friends, colleagues, and family, may you have a Happy and prosperous new year filled with good fortune.</p> <p>This Chinese new year (春节 - chūn jié) falls on a Sunday the 29th of January and is also known as the Year of the Dog. Chinese new year (or “The Spring Festival”) marks the first day of the lunar new year. It ends 15 days later on the second full moon of the lunar new year also called “The Lantern Festival”)</p> <p>In case you’re feeling left out, I’ve come up with a short list of things you can do to make your Chinese new year more enjoyable.</p> <ul> <li><strong>Learn to offer seasonal greetings in Mandarin</strong>. Practice saying 恭喜发财 (gōng xǐ fā cái), which means “Wishing you a prosperous new year.” 新年快乐 (xīn nián kuài lè), which means “Happy New Year.” And my personal favorite: 国际化软件不容易 (gúo jì huà ruǎn jiàn bù róng yì), which means “Software internationalization is non-trivial.”</li> <li><strong>Eat a lot</strong>. In Mandarin, the Lantern Festival is written 元宵节 (yuán xiāo jié). Yuanxiao phonetically sounds like 圆宵, which literally means “round overnight.” You see, during this week, massive amounts of sweet or meat filled dumplings are consumed by about 3 billion people.</li> <li><strong>Chinatown</strong>. Head down to your local Chinatown and partake in the festivals. Celebrations go on for not just 1, not just 8, but 15 days. FIFTEEN.</li> </ul> <p>And of course, in the spirit of maintaining balance, here are three things you shouldn’t do on Chinese new year.</p> <ul> <li><strong>Do not get a Chinese tattoo</strong>. Because showing off your new tattoo that’s above your ass, to your asian friends, really isn’t that spiritual, especially if it says “Beef and Broccoli.”</li> <li><strong>Do not wear black</strong>. Black clothes signify bad fortune. Instead, wear something red or gold which signifiy happiness and good luck.</li> <li><strong>Do not buy a chihuahua and walk around like Paris Hilton</strong>. Ok, I was really going to finish up with “Don’t clean your house.” Sweeping your house during this time is considered the equivalent of sweeping away your good luck.</li> </ul> <p>平安顺心 (píng ān shùn xīn) - Be safe and well</p> You never forget your first web server 2006-01-23T00:01:27-07:00 <p><a href=''>Jeremy’s entry</a> about his first web server brought back fond memories of my own web server that I ran during my college years just over 5 (golly) years ago.</p> <p>It was a Pentium 3, 256MB, 20GB running FreeBSD 4.x off a Qwest 256Kb/s downstream connection. In a time before blogs, Gandalf.MarcChung.com was a convenient way for my friends to run their personal websites and for myself to learn UNIX. I was webmaster, sysadmin, and customer support rep all rolled into one. One day I’d be fixing a friend’s HTML, and the next I was using setting up Apache+SSL, MySQL, and PHP using the usr/ports system.</p> <p>Some websites I ran (that are still up today) are <a href=''>Cork</a>, <a href=''>AwareLabs</a>, <a href=''>Artique.ro</a>, <a href=''>Vivin.net</a>, and <a href=''>my personal website</a>. My college roommate (chapter president of the ASU <a href=''>BMES</a> club) also ran his club’s website on Gandalf. Later, as chapter president (but of the ACM), I also ran the ASU ACM website. It was eventually moved over to ASU’s campus and eventually lost in the great sea of red tape.</p> <p>For “fun”, I wrote a personal information manager in PHP that kept track of my daily To-Do items, managed my online writings/rants/diary, and even let me upload and download files between school and home.</p> <p>Like Jeremy, this experience also led to my first “web programming” job at a Startup 1.0 during my time at ASU.</p> <p>I maintained Gandalf, until the terrible hard disk crash of 2003, just after graduation, and fortunately just after I setup my last “client” with a Real Webhosting Company (TM). These days, Gandalf sits quietly in my storage closet slowly gathering dust and dreaming of a day where it will one day run another startup. Or at least prototype one.</p> Happy Lunar New Year 2006-01-22T22:01:33-07:00 <p>恭喜发财.</p> <p>In less than week, it will be the year 4703, the Year of the Dog. Before 4702, the Year of the Properous Cock (Rooster) is over, I’m going to take second to summarize my year.</p> <p>January:</p> <ul> <li>I got a great new job writing desktop applications for a software company.</li> <li>Visited Seattle.</li> </ul> <p>February:</p> <ul> <li>How hard is it to buy a house?</li> <li>Knights of the Old Republic II consumes me</li> <li><a href=''>Rotaracter</a></li> <li><a href=''>Igniter</a></li> </ul> <p>March:</p> <ul> <li>Dayong’s Power Hour</li> <li>Reconnecting with old high school and college friends</li> <li>Dear <a href=''>EVDB</a>: Please make me a beta tester</li> <li><a href=''>Boxing</a></li> </ul> <p>April:</p> <ul> <li>I think I should start up <a href=''>MarcChung.com again</a></li> <li>Viva il Papa!</li> <li>1 GB of memory should be enough for anybody</li> <li><a href=''>Ruby… on Rails</a>?</li> <li><a href=''>Walking to End Violence</a></li> </ul> <p>May:</p> <ul> <li>Four words: World of Fracking Warcraft</li> <li><a href=''>Happy Birthday</a></li> </ul> <p>June</p> <ul> <li>Buying a house is a non-trivial activity</li> <li>Who is the Phantom of the Opera?</li> </ul> <p>July</p> <ul> <li><a href='/eve/'>Eve</a>: The Exciting Venues and Events Browser</li> <li>The Shuttle is grounded</li> </ul> <p>August</p> <ul> <li>Intelligent Design, <a href=''>Church of Pastafarianism</a>.. so many religions, so little time</li> <li>I BOUGHT A CONDO</li> </ul> <p>September</p> <ul> <li>Went to Chicago</li> <li>Googlewhacking</li> <li>“Brownie, you’re doing a heck of a job.” –President Bush after Hurricane Katrina devastated New Orleans</li> </ul> <p>October</p> <ul> <li>XBox 360</li> <li>Playstation 3</li> <li>Nintendo Revolution</li> </ul> <p>November</p> <ul> <li>Me gusta <a href=''>Ubuntu</a></li> <li>Preparing for GRE</li> <li>Sony almost <a href=''>fracks me with a rootkit</a></li> <li>Happy Thanksgiving</li> </ul> <p>December</p> <ul> <li>Merry Christmas</li> <li><a href=''>Vivin</a> goes to Iraq</li> <li>Pablo Francisco talks about chicken pot pie.</li> <li>Mommy, what’s a Jellicle Cat?</li> </ul> Be Nice 2005-12-01T23:12:55-07:00 <p>With two years of full time professional employment under my belt, two of the most important things I’ve learnt so far don’t even have anything to do with my software engineering background.</p> <p>The first was by a former software engineering professor of mine at ASU.</p> <blockquote> <p><strong>Be tactful.</strong> I hear stories from industry about a new kid right out of college attending his or her first meeting and they would just start shouting out their thoughts on how this and that design should be. Don’t Do That.</p> <p>–<a href=''>Joseph Urban</a></p> </blockquote> <p>And the second was by one of my former boss’ at Thomson Financial:</p> <blockquote> <p><strong>Never make your boss look bad.</strong></p> <p>–<a href=''>Craig Columbus</a></p> </blockquote> Entrepreneur? 2005-11-05T19:11:05-07:00 <p>I am the guy that comes up with the ‘idea’. For the longest time, to me, the words ‘entrepreneur’ and ‘idea’ went hand in hand. I’d think to myself, “Wow, I have such great ideas, I’m such a great entrepreneur.” Sometime during my sophomore year, I learnt that being an entrepreneur wasn’t about having ideas.</p> <p>You need a business model, the skills to bring the idea to life, and the discipline to execute it all.</p> <p><a href='' title='Don'>Entrepreneurs</a> aren’t idea people, <strong>everybody and their brother has ideas.</strong> Entrepreneurs are people that <strong>exploit ideas</strong> by <strong>matching them to market needs</strong>, <strong>executing them despite scarce resources</strong> and designing <strong>a business model</strong> that makes the idea <strong>profitable</strong>.</p> Manifesto 2005-11-05T19:11:04-07:00 <p>Every once in a while, I’ll read or hear about a piece of advise that on some personal or professional level, I believe in. When I find one, I reach for the closest pen and paper and write them down. Inspired by <a href=''>37signals manifesto</a>, I started placing my writings in my personal <a href='/manifesto.html'>manifesto</a>.</p> <p>Feel free to share your thoughts.</p> Avast me hearties! 2005-09-09T08:09:27-07:00 <p>‘Tis be <a href=''>Talk Like a Pirate Day</a> Arrrrr!</p> <p class='image'><img src='/images/jolly_roger.gif' alt='Arrr, th Jolly Roger!' /></p> On July 13th, 2005... 2005-07-13T05:07:57-07:00 <p class='image'><img src='/images/googlewhack_dgorman.png' alt='Dave Gormans Googlewhack Adventure' /></p> <p>… I popped my <a href=''>Googlewhack</a> cherry. Too bad I can’t actually tell you what it is (I hope I’m not violating some GoogleWhack TOS).</p> <p>Update: The phrase was “Ultrasophisticated briton” and ceased being a Googlewhack sometime in 2007. Here’s the full copy I wrote when Googlewhack came to Phoenix:</p> <p class='image'><img src='/images/googlewhack_ignite_copy.png' alt='Ignite Copy' /></p> Giving AIMS a Chance 2005-06-21T07:06:00-07:00 <p>The following is a transcript of a spoken essay available at <a href='' title='NPR on KJZZ'>KJZZ.org</a>.</p> <p><em>This is KJZZ’s morning edition, I’m Dennis Lambert. This morning, an East Valley teacher speaks out against two recent decisions to water down AIMS test standards. One was the State Board of Education’s decision to lower passing scores for the AIMS test. The other, the State Legislature’s decision to allow students to use course work on core courses and other factors to supplement their AIMS test scores.</em></p> <blockquote> <p>I’m Elizabeth Viator. I’m a teacher at Dobson High School and the Mesa Public School District, and I am your child’s teacher.</p> <p>After reading about the latest debacle regarding lower passing scores on the AIMS test, I’m reminded of a line from a Tom Petty song, “Don’t Back Down.” I would have begged our legislators not to back down. I would have pleaded with them not to weaken the system by providing an alternative to the AIMS test. Not yet. Not until we took it all the way to the end. Arizona has invested far too much money, time, and effort to see this test, that the state legislators insisted we needed, be watered down. But it’s too late. In an act of political spinelessness, that’s just what the Legislature and State Board of Education did, back down.</p> <p>Under the old scoring standards some seniors wouldn’t have graduated next spring and received their diplomas. That was the point. The kids who needed extra help might actually have taken it seriously next year. Next year, if they buckled down and worked hard, many could have actually passed; they could have risen to the standard. Now, however, they’ll never know what they could have achieved.</p> <p>The AIMS test was intended to wake up students, teachers, and parents. It was implemented and touted by legislators as the great cure for education. This had some success. If the state legislators would have found their back bones, we could have seen some real gains in education in the next few years. If the legislators could have stood tall, it would have meant that this state did indeed stand behind its self-made policy. If the legislators could have stood tall, it would have meant that kids and their parents would have had to be more responsible for their own education.</p> <p>Years ago the State of Arizona said that simply attending class and earning A’s, B’s, and C’s was not good enough and a whole lot of educators agreed. Many of us actually cheered and rallied behind a solid, valid test. Now, however, the alternate path to augmenting low AIMS scores places the pressure solely and wrongfully on the shoulders of teachers. Why was the AIMS test initiated at all? Let me remind you: too many kids earned diplomas but lacked minimal skills. Too many educators found it easier to pass students rather than deal with angry parents and thus succumb to a modern day adult bullying. As a result, they passed students who did not deserve to pass. Many teachers offered extra credit. These extra assignments, anything from bringing in a box of Kleenex to writing a report on the benefits of Benadryl, artificially boosted the student’s grade enough to <em>fah la</em> pass the class, everybody’s happy. But what did the student learn? The lesson learned here is that if the system provides enough loop holes, anyone can pass to the next level–without skill, without accountability. Welcome, to the new loop hole! With this new plan, many teachers will again resort to inflated grades to pass undeserving student so they can augment their AIMS score and keep parents happy. With this new plan, teacher shopping will be more plentiful than shopping for the latest outfit at Abercrombie and Fitch.</p> <p>Initially I thought the AIMS test was going to be the great equalizer. It would finally show what I’ve known all along: some teachers just don’t teach. My secret hope about the AIMS was that all the inept teachers who offered extra credit would be sued by the parents of those students who did not pass the AIMS test. <em>Pathetic</em>, I know. I also naively thought parents would be more engaged with their kid’s education and students might pay more attention to their own learning. But why should they work hard now? The Legislature and the State Board of Education just made it easier, a whole lot easier for kids to pass.</p> <p>At a time when we all could have risen to the occasion, the state legislators pulled the rug out and have returned us to a mediocre mire of miserable mush. It won’t be long before I walk away from teaching English and start teaching Yoga.</p> </blockquote> <p><em>Elizabeth Viator is an English teacher at Dobson High School in the Mesa Unified School District. You can <a href=''>hear</a> this essay again at <a href='' title='Giving AIMS a chance'>KJZZ.org</a>.</em></p> <p>I grew up in Singapore where every year from Primary 1 to Pre-U 2 (the equivalent of 1st through 12th grade in the States) a final exam determines whether or not you move on to the next grade. There is a test for every subject, English, Math, Science, and Mother tongue (Chinese, Malay, or Tamil). You don’t past, you don’t move on. No politics, no mollycoddling. Nothing good will come from lowering education standards, especially with the current job climate where the marketplace is competitive and global.</p> PHP5, DOM, and screen scraping 2005-06-06T08:06:45-07:00 <p>I spent some time using PHP5 to screen scrape a web page so that I could generate an RSS feed from it.</p> <p>Textdrive forbids the usage of wget or fetch so I had to grab the file directly using a socket connection:</p> <pre><code>$ <f:verbatim>Some Link</f:verbatim> <f:param </h:outputLink></code></pre> <p>This will emit the following link in your JSP/JSF page.</p> <pre><code></code></pre> <p>Now we add a filter to listen to requests for “jsf.get”:</p> <pre><code><filter> <filter-name>JSFGet Filter</filter-name> <filter-class>com.JSFGet</filter-class> </filter> <filter-mapping> <filter-name>JSFGet Filter</filter-name> <url-pattern>*.get</url-pattern> </filter-mapping></code></pre> <p>Now, you need a filter that handles incoming GET requests properly. Included below is a stripped down version. I hope this bit of code will help anyone trying to accommodate GET requests with JSF.</p> <pre><code>import com.SuperBean; import java.io.IOException; public class JSFGet implements Filter { private FilterConfig filterConf; private ServletContext servletContext; public void init(FilterConfig filterConfig) throws ServletException { this.filterConf = filterConfig; this.servletContext = filterConfig.getServletContext(); } public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException { FacesContext facesContext = getFacesContext(req, res); req.getRequestDispatcher(facesContext.getViewRoot().getViewId()). forward(req, res); } public void destroy() { this.filterConf = null; this.servletContext = null; } /** FacesContext.setFacesContextAsCurrentInstance method is protected. */ private abstract static class ProtectedFacesContext extends FacesContext { protected static void setFacesContextAsCurrentInstance( FacesContext facesContext) { FacesContext.setCurrentInstance(facesContext); } } /** Here's where the Filter/JSF integration takes place. */ private FacesContext getFacesContext(ServletRequest req, ServletResponse res) { /** Try to get it first */ FacesContext facesContext = FacesContext.getCurrentInstance(); if (facesContext != null) return facesContext; // Use the FactoryFinder to grab the Lifecycle object); // Put my Bean into HttpSession HttpServletRequest httpReq = (HttpServletRequest) req; HttpSession httpSess = httpReq.getSession(); SuperBean editor = new SuperBean(); String key = req.getParameter("editKey"); editor.setEditKey(key); // If your loadSomething method requires a FacesContext object, // call it after it has been constructed editor.loadSomething(); httpSess.setAttribute("SuperBean", editor); // Here's where the ProtectedFacesContext comes in. facesContext = contextFactory. getFacesContext(servletContext, req, res, lifecycle); ProtectedFacesContext.setFacesContextAsCurrentInstance(facesContext); // Create a new ViewRoot. Default behavior returns null UIViewRoot view = facesContext.getApplication(). getViewHandler().createView(facesContext,"edit.jsf"); facesContext.setViewRoot(view); // Call loadSomething(FacesContext) // editor.loadSomething(facesContext); return facesContext; } }</code></pre> On Firefox and safe sex 2004-12-21T08:12:11-07:00 <p>I am an avid Firefox user. I <a href=''>donated</a>, I beta tested, and occasionally I have convinced my non-geek friends to take it for a spin, only to usually have them flip out over <a href=''>tabbed browsing</a>, <a href=''>the built-in pop up blocker</a>, and lots of <a href=''>themes</a>. Recently, while convincing a friend, I came up with a great analogy between Firefox and safe sex.</p> <p>Surfing the internet with Internet Explorer is like having unprotected sex with strangers. If you are going to have sex, be smart and take the necessary protection. Firefox is that protection. It allows you to be visit all the websites you want while protecting you from <a href=''>getting infected</a>, which will happen.</p> <p class='image'><a href=''><img src='/images/practice_safe_hex_with_firefox.jpg' alt='Practice safe computing' /></a></p> <p>Source: <a href=''>Flickr</a></p> | http://feeds.feedburner.com/marc | crawl-002 | refinedweb | 25,238 | 64.81 |
.
status= mex (…)
Compile source code written in C, C++, or Fortran, to a MEX file.
status is the return status of the
mkoctfile function.
If the compilation fails, and the output argument is not requested, an error is raised. If the programmer requests status, however, Octave will merely issue a warning and it is the programmer’s responsibility to verify the command was successful.); /* Return empty matrices for any outputs */ int i; for (i = 0; i < nlhs; i++) plhs[i] = mxCreateDoubleMatrix (0, 0, mxREAL); } Simple test of the functionality of a mex-file.
In this case, the function that will be executed within Octave will be given by the mex-file, while the help string will come from the m-file. This can also be useful to allow a sample implementation of the mex-file within the Octave language itself for testing purposes.
Although there cannot be multiple entry points in a single mex-file, one can
use the
mexFunctionName function to determine what name the mex-file was
called with. This can be used to alter the behavior of the mex-file based on
the function name. For example, if
#include "mex.h" void mexFunction (int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { const char *nm; nm = mexFunctionName (); mexPrintf ("You called function: %s\n", nm); if (strcmp (nm, "myfunc") == 0) mexPrintf ("This is the principal function\n", nm); return; }
is in the file myfunc.c, and is compiled with
mkoctfile --mex myfunc.c ln -s myfunc.mex myfunc2.mex
then as can be seen by
myfunc () ⇒ You called function: myfunc This is the principal function myfunc2 () ⇒ You called function: myfunc2
the behavior of the mex-file can be altered depending on] | https://docs.octave.org/v6.4.0/Getting-Started-with-Mex_002dFiles.html | CC-MAIN-2022-40 | refinedweb | 283 | 60.65 |
acl_check man page
acl_check — check an ACL for validity
Library
Linux Access Control Lists library (libacl, -lacl).
Synopsis
#include <sys/types.h>
#include <acl/libacl.h>
int
acl_check(acl_t acl, int *last);
Description
The acl_check() function checks the ACL referred to by the argument acl for validity.
The.
If the ACL referred to by acl is invalid, acl_check() returns a positive error code that indicates which type of error was detected. The following symbolic error codes are defined:
- ACL_MULTI_ERROR
- The ACL contains multiple entries that have a tag type that may occur at most once.
- ACL_DUPLICATE_ERROR
- The ACL contains multiple ACL_USER entries with the same user ID, or multiple ACL_GROUP entries with the same group ID.
- ACL_MISS_ERROR
- A required entry is missing.
- ACL_ENTRY_ERROR
- The ACL contains an invalid entry tag type.
The acl_error() function can be used to translate error codes to text messages.
In addition, if the pointer last is not
NULL, acl_check() assigns the number of the ACL entry at which the error was detected to the value pointed to by last. Entries are numbered starting with zero, in the order in which they would be returned by the acl_get_entry() function.
Return Value.
Errors
If any of the following conditions occur, the acl_check() function returns
_valid(3), acl(5)
Author
Written by⟨a.gruenbacher@bestbits.at⟩.
Referenced By
acl(5), acl_calc_mask(3), acl_error(3), acl_valid(3). | https://www.mankier.com/3/acl_check | CC-MAIN-2016-50 | refinedweb | 228 | 56.05 |
I have been using Spyder as my IDE of choice, which has been great. However, it tends to hang when it is trying to autocomplete something (note, this only happens the first time I call a module). So, if I type in the editor:
- Code: Select all
import pandas as pd
data = pd.DataFrame()
I will typically get so far as "data = pd.Da" when Spyder hangs for 10s (seriously, 10s!)to think about ALL the autocomplete options available. I really like Spyder, but this is VERY frustrating. I have not found a solution online so I wonder if anyone else has had a similar experience with this IDE and hopefully found some solution.
This should not be a hardware issue since I am running on a Xeon E5-1650 CPU, 32GB RAM. Any help is appreciated. | http://www.python-forum.org/viewtopic.php?f=6&t=10851&p=14091 | CC-MAIN-2014-49 | refinedweb | 137 | 74.9 |
Normally, the loading for namespace data is automatically initiated by the master server. If that does not occur, run the nisping command as described in this procedure.
The NIS+ principal performing this operation must have modify rights to the domain's directory object.
The domain must have already been configured and have a master server up and running.
The new replica server must already be configured as an NIS+ server, as described in Setting Up an NIS+ Server.
The new replica server must be configured as a replica, as described in Using NIS+ Commands to Configure a Replica Server.
Run nisping on the directories
This step sends a message (a “ping”) to the new replica, telling it to ask the master server for an update. If the replica does not belong to the root domain, be sure to specify its domain name. (The example below includes the domain name only for completeness. Since the example used throughout this task adds a replica to the root domain, the doc.com. domain name in the example below is not necessary.)
You should see results similar to these:
If your namespace is large, this process can take a significant amount of time. For more information about nisping, see Chapter 18, Administering NIS+ Directories. | https://docs.oracle.com/cd/E19253-01/816-4558/c5server-33421/index.html | CC-MAIN-2018-30 | refinedweb | 210 | 55.24 |
qt_backport 0.1.0
Makes PySide/PyQt4 code work with Qt5 (using PyQt5)
qt_backport
qt_backport makes unmodified python code based on Qt4 work with Qt5.
More specifically (and currently), if you have PyQt5 installed and functional, but want to work with older PyQt4 or PySide code without having to do any conversion work, this package is for you!
Installation
- Uninstall any existing Qt4 wrapper (PyQt4 or PySide) if you have one.
- Install PyQt5
- pip install qt_backport
Usage
qt_backport automatically makes both ‘PyQt4’ and ‘PySide’ packages available that will function like the old Qt4 versions, but will actually be backed by PyQt5.
ie: your old code like this will just work as-is:
import PyQt4 from PyQt4 import QtCore from PyQt4.QtGui import * #<-- this is supported, but yuck
or
import PySide from PySide import QtCore from PySide.QtGui import * #<-- this is supported, but yuck
When to use qt_backport?
This package is particularly useful when you have installed a modern Qt5 wrapper (currently only PyQt5) and are trying to learn Qt using legacy code examples you find on the web.
qt_backport is not primarily intended as a method for porting your applications from Qt4 to Qt5 (you are better off converting if you can), but it does do a good job of this and can definitely help get you started.
Why is qt_backport needed at all?
When Qt4 was updated to Qt5 there was a major reorganization done to the class organization. In addition, there have been many other API changes.
One of the most significant changes was that a huge number of classes that used to be contained within ‘QtGui’ were dispersed out to various other locations instead. eg: All of the widgets were moved out of QtGui and into a new module called QtWidgets. Although the new locations make much more sense, it broke a lot of old code. qt_backport is a hack to make old code work as-is.
There have been many more API changes in the Qt 4.x to Qt 5.2 transition (Qt 5.2 is current the time of writing this). qt_backport deals with many of these changes, but all of them may not be captured (yet). A simple example of such a change (that qt_backport handles) is that QColor.dark() was removed and replaced with QColor.darker() in Qt 4.3.
Note that, although the backport generally works quite well, there may be additional changes you need to make to to your old code for it to work. These changes depend on the vintage of your old code. For example, old style signal/slot connections are not currently supported.
NOTE: At the current time, the only Qt wrapper for python that works with Qt5 is PyQt5. In future this may change (eg: when PySide upgrades to use Qt5).
How does it work?
qt_backport wraps Qt using PyQt5 (currently the only python wrapper for Qt5), but provides an emulation layer that emulates both the PySide and the PyQt4 APIs. Installing qt_backport automatically makes the PySide and PyQt4 emulators available for import.
This is easier to see visually:
+-----------------------------------+ | | | Existing Python code that expects | | the PyQt4 or PySide API | | | +-------+------------------+--------+ | | OLD <with qt_backport> WAY | | +-----+-------+ | | | qt_backport | | PySide or | Emulation layer: | | PyQt4 | | | | | +-----+-------+ | | +--------+--------+ +-----+-------+ | | | | Wrapper layer: | PySide or PyQt4 | | PyQt5 | | | | | +--------+--------+ +-----+-------+ | | +----+-----+ +---+-----+ | | | | Qt library layer: | Qt4 | | Qt5 | | | | | +----------+ +---------+
To do:
support old-style connections (ie: connect(app, SIGNAL(), app, SLOT())
- support more known api changes
- API change coverage is currently not 100%, being mostly driven by demand for certain classes/methods. Coverage is currently quite good, though.
- other potential changes are covered here:
unit tests for the zillion api patches
License
MIT. See LICENSE file.
- Author: Russell Warren
- Keywords: Qt PyQt4 PyQt5 PySide
- License: MIT
- Categories
- Development Status :: 3 - Alpha
- Intended Audience :: Developers
- License :: OSI Approved :: MIT License
- Operating System :: OS Independent
- Programming Language :: Python
- Programming Language :: Python :: 2.6
- Programming Language :: Python :: 2.7
- Topic :: Software Development
- Topic :: Software Development :: Libraries :: Python Modules
- Topic :: Software Development :: User Interfaces
- Package Index Owner: rwarren
- DOAP record: qt_backport-0.1.0.xml | https://pypi.python.org/pypi/qt_backport/0.1.0 | CC-MAIN-2016-22 | refinedweb | 666 | 63.19 |
index.mdwn | 4 + reference/dependencies.mdwn | 131 ++++++++++++++++++++++++++++++++++++++++++++ xsf.css | 5 + 3 files changed, 140 insertions(+) New commits: commit dfb93d750512f99ecbbe8e7d97db97acb6641505 Author: Cyril Brulebois <kibi@debian.org> Date: Tue Feb 1 13:34:52 2011 +0100 dependencies: New reference document. diff --git a/index.mdwn b/index.mdwn index f3e1efc..ab5e152 100644 --- a/index.mdwn +++ b/index.mdwn @@ -8,6 +8,10 @@ * [How to configure input](howtos/configure-input.html) * [How to configure outputs](howtos/use-xrandr.html) +## Reference documentation + + * [Dependencies between server and drivers](reference/dependencies.html) + ## Other documentation * [Upstream features](upstream-features.html) diff --git a/reference/dependencies.mdwn b/reference/dependencies.mdwn new file mode 100644 index 0000000..fa0e816 --- /dev/null +++ b/reference/dependencies.mdwn @@ -0,0 +1,131 @@ +# Dependencies between server and drivers + +Cyril Brulebois <kibi@debian.org> + + +## Upstream-side: ABI version numbers + +The X server defines several +[ABI]() in +`hw/xfree86/common/xf86Module.h`, through the +`SET_ABI_VERSION(maj,min)` macro. In this document, the focus is on +`ABI_VIDEODRV_VERSION` and `ABI_XINPUT_VERSION`, which are +respectively about `video` drivers and `input` drivers. + +An example of input ABI is `12.1`, `12` being the `major`, `1` being +the `minor`. + +Like in usual shared libraries, the major is bumped when interfaces +are broken. There’s no compatibility at all in that case. + +The minor gets bumped when interfaces are added. In other words, if a +driver is working with `x.y`, it should also work with higher minors: +`x.z`; `z>y`. The converse is not true, if a driver requires a given +minor (for example because it needs a new feature, like MultiTouch), +it won’t work with lower minors (which didn’t provide the needed +feature). Put another way: we have ascending compatibility with the +minors. + +Conclusion: We need to keep track of both major and minor. + +Thanks to `pkg-config` we can query them: + + $ pkg-config --variable=abi_videodrv xorg-server + 9.0 + $ pkg-config --variable=abi_xinput xorg-server + 12.1 + + +## Debian-side: Using virtual packages + +### Server’s build system + +When `xorg-server` gets built, we use `pkg-config`’s output to +determine the current major. Through substitution variables, we add +two virtual packages in the `Provides` field of the server (for both +`xserver-xorg-core` and `xserver-xorg-core-udeb`): `xorg-input-abi-$x` +and `xorg-video-abi-$y`, where `$x` and `$y` are the major part of the +version queried through `pkg-config` variables. +***FIXME: Currently we have both major and minor.*** + +To handle ascending compatibility for minors, we maintain in +`debian/serverminver` the minimal version of `xserver-xorg-core` which +is needed. When a minor is bumped, we store the server version in that +file. This way, drivers built afterwards will depend on a *minimal* +version of the driver, the last which saw a minor version bump. In +other words: they will “depend on the server version they were built +against, or a higher/compatible one”. + +Both ABI and minimal server version are recorded in two files shipped +in `xserver-xorg-dev`, to be used while building drivers: + + * `/usr/share/xserver-xorg/xinputdep` + * `/usr/share/xserver-xorg/videodrvdep` + +Example for `xinputdep`: + + xorg-input-abi-11, xserver-xorg-core (>= 2:1.8.99.904) + +***FIXME: Lies! That's currently `xorg-input-abi-11.0, …` instead.*** + + +### Driver’s control file + +Drivers also use substitution variables in their control file, +replaced at build time. + + # Input driver: + Depends: ${xinpdriver:Depends}, … + Provides: ${xinpdriver:Provides} + + # Video driver: + Depends: ${xviddriver:Depends}, … + Provides: ${xviddriver:Provides} + +For now, `${xinpdriver:Provides}` is always replaced with +`xorg-driver-input`, and `${xviddriver:Provides}` is always replaced +with `xorg-driver-video`. Hopefully provided packages will not change, +but using substitution variables is cheap, and makes it easy to add +tweaks afterwards if needed. + + +### Driver’s build system + +To set those variables, we ship a `dh_xsf_substvars` script in +`xserver-xorg-dev` starting with ***FIXME_version***, to be run before +`dh_gencontrol`. It iterates on the packages listed by +`dh_listpackages` (very old `debhelper` command) and does the +following work: + + * It reads variables from the files mentioned above. + * If a package name ends with `-udeb`, it replaces + `xserver-xorg-core` with `xserver-xorg-core-udeb`. + * If a package name ends with `-dbg`, it does nothing for this + package. Debug packages usually depend strictly on the non-debug + packages, which in turn have appropriate dependencies. + * If a package name starts with `xserver-xorg-input-`, it appends + `xinpdriver:Depends=…` and `xinpdriver:Provides=…` to this + package’s substvars file. + * If a package name starts with `xserver-xorg-video-`, it appends + `xviddriver:Depends=…` and `xviddriver:Provides=…` to this + package’s substvars file. + +Why such heuristics? The idea is to avoid getting “unused substitution +variable” warning messages while building. And since there’s a clear +`xserver-xorg-{input,video}-*` namespace, we can use that to specify . + +We probably should have some way of tracking ABI bumps automatically, +to make sure we bump `serverminver` when needed. commit 45ae4b42e61f581087bdad27a42df4b80fb37206 Author: Cyril Brulebois <kibi@debian.org> Date: Tue Feb 1 12:14:36 2011 +0100 css: Avoid too much margin in nested lists. diff --git a/xsf.css b/xsf.css index 1b7aaf6..5c070c4 100644 --- a/xsf.css +++ b/xsf.css @@ -59,6 +59,11 @@ ol { text-align: justify; } +/* Avoid too much margin in nested lists */ +ul ul, ol ul, ul ol, ol ol { + margin-left: 0px; +} + pre { margin-left: 60px; } | https://lists.debian.org/debian-x/2011/02/msg00021.html | CC-MAIN-2019-26 | refinedweb | 878 | 51.04 |
ole Freed695 Points
Doesn't a function need to be initialized/defined before it's called?
In the Functions section, the function "funky_math" is declared before, but initialized/defined after, the "main" function, in which it's called. How does this work? Doesn't a function need to be defined before it's called?
6 Answers
Nicole Freed695 Points
Ha! So I just got the answer from a senior programmer. It has to do with the difference between interpreted and compiled languages. JavaScript is an interpreted language: the interpreter runs and executes the program sequentially, therefore, functions have to be defined before they're called. However, C-based languages are compiled, which means that they're essentially run behind the scenes. C compilers make three passes: in the first, they check to see that all the syntax is correct; in the second, they "connect all the dots"—put together function declarations with definitions, etc.; and in the third, they actually run the program. Therefore, if things are out of order, they're put together in the compiling process, since the compiler doesn't actually execute the program linearly.
Alex Sell19,355 Points
You can read about functional hoisting in JavaScript here:
Joseph Taralson1,737 Points
Andrew - here's the best way to think about it:
Yes, you are correct that you can code the way you did in your example and it will work fine.
However, when coding a larger program, organizationally this is impractical. Your main() function is the body of your program, and in a larger program you may have 10, 20, or 100 additional functions you reference in the main() function. The reason we are taught to first declare functions above main() and then define after main() is for organization. In a large program you would have to scroll through lines and lines and lines of functions before getting to your main() function, which tells you what the heck all those other functions are doing.
Make sense?
Andrew King3,411 Points
I'd forgotten about this thread! Yeah it does make sense & I came to that same thinking as I worked ahead in the course.
Many thanks for taking the time to reply.
A
Andrew King3,411 Points
What confused me about this is that the code below runs and produces the exact same output as the version where you declare the function first & then implement it after. Can anyone explain then the need to declare it first and then implement it later? Seems like a wasted line of code that doesn't seem to be doing anything? Or am I missing a bigger picture for a larger scale program?
#include <stdio.h> int funky_math(int a, int b) { return a + b + 343; } int main() { int foo = 24; int bar = 35; printf("funky math %d\n", funky_math(foo, bar)); return 0; }
Nicole Freed695 Points
If the code above produces the same output as the code example in the video, it makes me wonder if the C compiler searches through the entire program for the definition of the function before attempting to execute it, rather than executing the program sequentially? If it executes the program sequentially, the code in the video doesn't make any sense (but yours does, Andrew), whereas if it searches for the definition of the function when it encounters it being called, and then executes it, both of the examples would work.
Nicole Freed695 Points
You're asking about the reason behind the separation of declaration and implementation, correct, Andrew? I've wondered about that, too. I've read that it's generally better to do both at once, but I can imagine there might be circumstances under which one would want to separate the declaration and implementation (but being a baby beginner in this stuff, I have no idea what those would be).
Andrew King3,411 Points
I came to C from a bit of Java Script background and this is how you do it there. You declare functions & then call them. It just seems like a massive waste to declare a function but not actually include what it 'does'. To then rewrite the declaration THEN include it's initialisation code.
My initial assumption is that on a larger scale program the need to declare it separately is required or if it's simply that the description in the video wasn't too stellar and / or made a mistake.
Andrew King3,411 Points
So surely by that reasoning it is pointless writing the function the way it's done in the video and you can just write it in one go like I did in the example above. If the compiler will figure it all out, it shouldn't be a problem, no?
You should ask the guy you just spoke to that.
Nicole Freed695 Points
I might, although it's not my primary concern. I'm sure there are times when one would want to separate declaration and initialization. However, it's your question; why don't you go ahead and put it in a separate thread?
Andrew King3,411 Points
My initial statement / question is just the next logical step in the question you initially asked. The answer you received from the person you spoke to simply raises the "yeah, so what difference does it make how it's written?". Seems highly inefficient to make a second fresh thread on the same issue, especially when a discussion is already in motion.
Hopefully one of the Treehouse tutors will see the thread & dive in with a follow up.
Tristan Gaebler6,204 Points
Your defining the function 'funky_math' before the main function, and manipulating the function after the main function.
Nicole Freed695 Points
I used the wrong terminology previously; I've updated the question to be clearer. The "funky_math" function is declared before the "main" function, but initialized/defined after the "main" function. However, it's used in the "main" function, before it's defined. How does this make sense?
Robert Mylne13,708 Points
Robert Mylne13,708 Points
Nicole Freed "JavaScript is an interpreted language: the interpreter runs and executes the program sequentially, therefore, functions have to be defined before they're called."
Then explain why that works. | https://teamtreehouse.com/community/doesnt-a-function-need-to-be-initializeddefined-before-its-called | CC-MAIN-2022-27 | refinedweb | 1,035 | 68.81 |
Type: Posts; User: qabdullah
#ifndef GUARD_Cb_n_h
#define GUARD_Cb_n_h
double** Cb_n(double roll, double pitch, double heading);
#endif // !GUARD_Cb_n_h
is this the correct use of tag? Thanks.
Qassim
I did not really do this on purpose as I still did not figure out how it works. There was a window for tag and it tells me you have max of 5 and should be seperated by comma. I cut and pasted the...
Hello,
I am new to C++ and having problem passing arguments between main and a function.
I would like to pass three values to a function, have it calculate a 2D matrix and return it back to main....
Thank you for your determination in helping me. The code you sent me came clean from all errors except this one "unexpected end of file while looking for precompiled". I was able to run it by moving...
Thank you very much, that was the problem. I am a happy camper now :) I guess it is the learning experience. Thank you for your patience. I find out where is the Go Advanced button, Heyy.
I apologize in advance for not using the tag as I am not sure how to do that. I shortened the program so we can focus on the problem which remains even after applying all the changes you suggested....
Thank you Paul for the promt response. Here is my code that I am trying to compile.
#include <stdlib.h>
#include <math.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include...
Running:
ifstream fin1;
results in the following error message:
error C2371: 'fin1' : redefinition; different basic types
Your help please. | http://forums.codeguru.com/search.php?s=192b3c71355c5c3fc8ebfc1341af2586&searchid=6137043 | CC-MAIN-2015-06 | refinedweb | 270 | 75.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.