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 |
|---|---|---|---|---|---|
CodeGuru Forums
>
Visual C++ & C++ Programming
>
Graphics Programming
> [RESOLVED] DirectShow filters synchronization
PDA
Click to See Complete Forum and Search -->
:
[RESOLVED] DirectShow filters synchronization
r_gueorg
September 10th, 2008, 12:37 PM
Hi,
I am trying to implement a filter graph consisting only of a source
filter and renderer. This is based on a code base with 3 filters
impementation - source, transform and renderer.
The transform filter was doing the decompression of the video stream
and passing the samples downstream to the renderer. I moved the
decompressor functionality into the source filter and reconciled the
media types and transport b/w the source filter and renderer.
The problem is that the stream stops after decompressing a single
frame because the second time around the allocator does not return (I
think because of a deadlock).
The input pin and output pin of the transform filter were synched
using the m_csReceive lock. With the transform filter gone, how do I
go about synchronizing the media stream b/w source and renderer? Do I
need to override the Receive() method on the renderer input pin?
The second call (after rendering the first and only frame) IMemAllocator::GetBuffer returns only after I stop the graph and the result is VFW_E_NOT_COMMITTED , although Decommit
() never gets hit an the m_pAllocator is still a valid pointer.
Thank you very much in advance.
r_gueorg
September 16th, 2008, 03:33 PM
The ref count on the IMediaSample* pSample interface ptr was incorrect. So when the input pin tries to allocate a buffer the pSample is not yet available in the pool. A detailed look at "Samples and Allocators" in MSDN DirectShow help was all that was needed. Remember that if the sampe is processed on a worker thread its ref count is increased.
Hope this helps somebody else developing for DirectShow.
codeguru.com | http://forums.codeguru.com/archive/index.php/t-460897.html | crawl-003 | refinedweb | 303 | 51.38 |
So I read through a few different threads but none of them seem to directly address how I fix my issue. I'm trying to create a Calendar (Gregorian) and then use the .complete() method so that in my classes using this (Paycheck) class I can find relative dates and create new Calendar(s) from those dates to determine wages payed and wages owed. However, it's telling me that .complete() .computeTime() and .computeFields() are all not visible.
From what I've read, this seems to be because they are protected methods and even though I import the java.util for them, I can't access them because that class is not in my package. How do I get this so that I can call the .complete() method?
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class Paycheck {
//fields
protected double grossAmount;
protected Calendar paymentDate;
protected Calendar payPeriodStart;
public Paycheck(double grossAmount, int iYear, int iMonth, int iDay, int sYear, int sMonth, int sDay) {
this.grossAmount = grossAmount;
TimeZone tz1 = TimeZone.getTimeZone("America/Chicago");
this.paymentDate = new GregorianCalendar(iYear, iMonth, iDay);
this.paymentDate.setTimeZone(tz1);
this.paymentDate.complete(); //says "method not visible"
this.payPeriodStart = new GregorianCalendar(sYear, sMonth, sDay);
this.payPeriodStart.setTimeZone(tz1);
}
I don't care about the actual time, I just want it to give me the date so I can determine the dayofweek (important based on various state laws).
That is very easy to do, and don't need any call to internal methods.
Calendar cal = new GregorianCalendar(2016, Calendar.SEPTEMBER, 22); cal.setTimeZone(TimeZone.getTimeZone("America/Chicago")); System.out.println("Day of week (1=Sun, ..., 7=Sat): " + cal.get(Calendar.DAY_OF_WEEK));
Output
Day of week (1=Sun, ..., 7=Sat): 5
Output is
5 because today is
Thu 9/22/2016, and that's the date that was given. | https://codedump.io/share/V975nh273UEY/1/calendar-gregoriancalendar-complete-method-not-visible | CC-MAIN-2017-47 | refinedweb | 306 | 51.24 |
2/2/2012 7:27 AM, redapple wrote:
> For example, I have a util.lib in C++ which includes a few c++ classes. I
> have a util.i to define what classes should wrapped out. Then generated
> _util.pyd used in python.
>
> Then in python 2.7,
>
> import _util
> quit() ----- python interpreter crash!
You may be bypassing some crucial setup/teardown functions in the Python
import module by importing the shared library directly. Is there a reason
you're not importing "util", which is the "util.py" import module that loads
"_util"?
Render me gone, |||
Bob ^(===)^
---------------------------------oOO--(_)--OOo---------------------------------
I'm not so good with advice...can I interest you in a sarcastic comment?
I used swig to wrapped some C++ classes used in the python. On 32 bit
windows, it works very well.
Recently I build all my applications on 64 bit machine, still using swig to
wrap the same classes into the python. However, some classes caused the
python interpreter crash.
For example, I have a util.lib in C++ which includes a few c++ classes. I
have a util.i to define what classes should wrapped out. Then generated
_util.pyd used in python.
Then in python 2.7,
import _util
quit() ----- python interpreter crash!
I checked and found _util.pyd works (no crash) if I remove a class A from
util.lib, this class A defines static function which returns a pointer.
I'm wondering what causing the crash problem and how to fix it. Any help
will be appreciated.
BTW, python is 2.7.2 64 bit version. My application is build by MSVS 2008
amd64 compiler.
Thank you.
--
View this message in context:
Sent from the swig-user mailing list archive at Nabble.com. | https://sourceforge.net/p/swig/mailman/swig-user/?viewmonth=201202&viewday=2 | CC-MAIN-2017-43 | refinedweb | 290 | 80.48 |
We don't yet really support extension methods except for the ones provided by a host using the DLR style extension methods. If you want to use those you need to just add: [assembly: ExtensionType(typeof(POCO), typeof(POCOExt))] And then call RuntimeHelpers.RegisterAssembly and pass in the declaring assembly. We should pick up the types after that. RuntimeHelpers.RegisterAssembly is not final API. It's likely to change in B2 as one of the last bug fixes to multi-runtime support. I don't know that we will support the C# 3.0 style extension attributes in the 2.0 timeframe. While we could presumably support it we'd be required to create every custom attribute on the 1st parameter of every method in an assembly. Therefore it may be more significant of a feature than we'd like to fit in during the betas because we'd have to do something more intelligent than that. Hopefully this work around will suffice - at least for your own extension types. And FYI I'm guessing you're probably using 2.0 B1 not B2 :). -----Original Message----- From: users-bounces at lists.ironpython.com [mailto:users-bounces at lists.ironpython.com] On Behalf Of Ben Hall Sent: Tuesday, April 08, 2008 2:53 PM To: Discussion of IronPython Subject: [IronPython] C# Extension Methods and IP B2 Hi everyone, Tonight I was going to write a blog post on C# Interop so I I was playing around a bit more with some of the new C# 3.0 features and I looked at Extension methods and I can't seem to get it to work with IP B2. My C# code is this: public static class POCOExt { public static void Print(this POCO poco) { Console.WriteLine(poco); Console.WriteLine(poco.Created); } } public class POCO { public DateTime Created { get; set; } public POCO() { Created = DateTime.Now; } } I drop that assembly into my DLLs folder, when using it in ipy it doesn't seem to be detecting the extension methods. After doing a dir on POCO, I expected to see the method Print. >>> from DLRInterop import * >>> p = POCO() >>> dir (p) ['Created', 'Equals', 'Finalize', 'GetHashCode', 'GetType', 'MemberwiseClone', 'ReferenceEquals', 'ToString', '__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'get_Created', 'set_Created'] >>> p.Print() Traceback (most recent call last): File , line unknown, in Initialize##48 AttributeError: 'POCO' object has no attribute 'Print' This appeared to work, but it does go against C# 3.0 and isn't a great approach.... >>> POCOExt.Print(p) DLRInterop.POCO 08/04/2008 22:43:59 Is there anything special I need to do to get this to work as I would expect, or is there something where to call the Extension Method you need to go to the extension class? Cheers Ben Blog.BenHall.me.uk _______________________________________________ Users mailing list Users at lists.ironpython.com | https://mail.python.org/pipermail/ironpython-users/2008-April/006817.html | CC-MAIN-2019-47 | refinedweb | 476 | 64 |
Created on 2018-05-14 20:53 by steveha, last changed 2018-05-15 07:49 by vinay.sajip. This issue is now closed.
When a logged file has a timed rotation, it is renamed with an archival filename that includes a timestamp. The logging library has a small set of predefined filename templates and no way is provided to override them.
Also, the current rule is that while the file is in active use for logging, it will not have a timestamp in the filename; the filename will be something like: foo.log
Then, at file rotation time, foo.log is closed and then renamed to an archival name that includes a timestamp (something like: foo-2018-05-14.log), and a new active log file is opened with the name foo.log again.
Proposed enhancement: it should be possible to provide template codes that specify the format of the timestamp, and there should be an option that when the file is in active use its filename will include the timestamp. (Then at rotation time, the file is simply closed, with no need to rename it; and a new file with a new timestamp is opened.)
For example, specifying a log filename of "foo-%Y%m%d-%H%M%S" would specify a filename like: foo-20180514-160000.log
Use case: the company that employs me had a logging system requiring both of the above features. The timestamp in the filename had to be in a format different than the one format built-in to the logging module, and the timestamp needed to be in the file at all times. The logging system included a daemon that did the equivalent of tail -f on the logfile and collected log events as they were written.
Note: I have written code that implements the features described above.
Additional note: some template formats could cause a problem with deleting the oldest backup files.
When the option backupCount is set to a number >= 1, then at rotation time the handler will check whether the number of backup files exceeds the specified count, and will delete the oldest files to reduce the number of backup files to exactly the backupCount number.
The oldest files are found by sorting the filenames; the presumption is that the archival filenames will sort with the oldest files first. All the built-in templates produce filenames where this presumption is correct. A foolish user could specify a timestamp format where month appears before date, or hour appears before month, or any other template that does not follow this ordering: year/month/date/hour/minutes/seconds
We could also add a feature where, when the template is specified and backupCount is specified, the handler will check that the template follows the ordering so that the oldest files do sort first, and raise an exception if the template doesn't follow the ordering. Alternatively, we can add a note in the documentation warning of this issue.
> The logging library has a small set of predefined filename templates and no way is provided to override them.
What about
which allows you to specify your own naming scheme?
What prevents you from subclassing one of the existing rotating handlers and implementing the algorithm you want?
> What about [ BaseRotatingHandler.namer ] which allows you to specify your own naming scheme?
I confess that I overlooked that; it was added later than the version of Python in which I wrote my original code.
The current Python code still has a small set of predefined file templates, but now has a way to specify a callable that can completely override the filename. I agree that this can be used to implement any desired filename system, although it would be more work than simply specifying the desired template codes.
Are you planning to remove the predefined filename templates and produce a more functional version of the code where the .namer() function is always used to produce a filename, with a set of predefined functions that produce equivalent filenames to the built-in templates?
I just reviewed the Python 3.6 logging code. Unless I am mistaken, it still has the limitation that when a logging file is active for writing log events, that file always has the same filename (self.baseFilename). Did I overlook anything?
At rotation time, the self.namer() function is called, and it could implement any desired naming scheme. However, its only argument is the already templated filename.
So if I needed to implement logging with a filename of: foo-YYYYmmdd.log at all times, how would I get the current file (the open file to which log events are being written) to have that pattern of name?
And if I needed to write a self.namer() function to rename to that standard, is this the recommended approach?
# for daily rotations, the built-in template is: "%Y-%m-%d"
def namer(self, filename):
# filename will look like: foo-YYYY-mm-dd.log
year = filename[-14:-10]
month = filename[-9:-7]
day = filename[-6:-4]
base = filename[:-14]
new_filename = base + year + month + day + ".log"
return new_filename # will look like: foo-YYYYmmdd.log
The logging event that triggered the rollover is not passed to the namer() function, just the templated default filename.
In my opinion, it is more convenient for the user to simply specify the desired format using template codes, such as:
handler = TimedRotatingFileHandler("foo", suffix="-%Y%m%d", when="D")
Also, unless I have overlooked something, using the self.namer() function to implement a custom naming scheme completely disables the code that automatically deletes the oldest backup files when backupCount is specified. The getBackupFilesToDelete() function uses the self.extMatch value (a pre-compiled regular expression) to find files to delete; with a custom naming scheme, the files will not match the pattern. Therefore users with a custom naming scheme would have to implement some external solution to deleting old files after log rotation.
The code I am proposing to donate to Python automatically builds a suitable regular expression for the self.extMatch member variable, based on the user's specified format string. I believe this is an advantage for the code I propose to donate.
> Are you planning to remove the predefined filename templates
No. They work fine as is for most people, from what I can tell.
> it still has the limitation that when a logging file is active for writing log events, that file always has the same filename (self.baseFilename)
That's not a limitation particularly, it's that way by design.
> So if I needed to implement logging with a filename of: foo-YYYYmmdd.log at all times
Implement your own subclass and do whatever you need in there, including deletion of oldest files etc. Publish it on PyPI and see what the uptake is like. I'm not sure a donation of code in this area will be accepted, but there's no need for your bespoke handler subclass to be in the stdlib. | https://bugs.python.org/issue33506 | CC-MAIN-2020-34 | refinedweb | 1,164 | 62.07 |
[SOLVED] How to Get string and drawtext?
I need your help!
I'm over 20 hours stucked in my case couse iam a bad programmer :(
This is my non answerd thread by stackof! Please some one help me!
Hello jagl,
You can make an object of Output.h class into Widget.h class.
Using this object You can call add(name,value) function into Widget.cpp.
But remember add(name,value) must be a public member of output.h class.
@sumit
thank you! I understand the strategy but don't know how to write the code!
this is my Button:
void Widget::on_pushButton_clicked()
{
QPaintEvent e;
QString name;
QString value;
unsigned int name_val= QString::fromStdString(OutPutText::add(name, value));
painter = paintEvent(e);
}
i dont know how to catch the strings from the add(name,value) ant paint them in the widget with my paintevent! it shouldn't be deficult but i dont have ist!!
ok you need code-I am just writing rough code so you can easily understand.
In Output.h class
class Output
{
public :
void add(name,value);
};
in Widget.h class
#include "Output.h"
class Output;
class Widget
{
private:
Output *pOutputObj;
};
in Constructor of Output class--
{
pOutputObj=new Output(this);
}
void Widget::on_pushButton_clicked()
{
pOutputObj->add(name,value); //here u can call add function
}
Remark ::-->Not Tested
@ semit
thank you my problem was, i couldn't get the painter word out from my on_pushButton?clicked! but i solved it! and the solution is now on stackoverflow !
Ok its good...
Write [SOLVED] before Title, if Your problem is solved. | https://forum.qt.io/topic/34802/solved-how-to-get-string-and-drawtext | CC-MAIN-2018-05 | refinedweb | 259 | 76.93 |
Adding OpenSSL Support for Android device. First include the header:
#include <QSslSocket>
Then use the following line to check if SSL is supported:
qDebug() << "Device supports OpenSSL: " << QSslSocket::supportsSsl();
Check Qt Creator's
Application Output section or the Android
logcat for the result.
Building OpenSSL for Android
A convenient Github repository with prebuilt and a build script can be used without the need for manual step-by-step build. For more information, see OpenSSL for Android. If you download the repository, you can then skip to Using OpenSSL Libraries with Qt for Android.
The following instructions guide you to build the OpenSSL libraries manually:
- Download OpenSSL 1.1.x sources.
- Extract the sources to a folder and navigate to that folder using the CLI.
Note: If your development platform is Windows, you need
msyswith
perlv5.14 or later to build OpenSSL.
- Add the Android LLVM toolchain (NDK r20b or r21) to your path:
export PATH="<android_ndk_path>/toolchains/llvm/prebuilt/<host>/bin":$PATH
- Configure the OpenSSL sources to build for Android using the following command:
./Configure shared android-<arch> -D__ANDROID_API__=21
Where <arch> can take a value of:
arm,
arm64,
x86,
x86_64.
Note: You must consider enabling or disabling the SSL features based on the legal restrictions in the region where your application is available. For more information about the configurable features, see OpenSSL Configure Options.
- To build
libcryptoand
libsslshared libraries that are not versioned, but with an _1_1 suffix, run:
make -j$(nproc) SHLIB_VERSION_NUMBER= SHLIB_EXT=_1_1.so build_libs
Without a suffix, Android 5 (API 21) will load the system libraries libcrypto.so and libssl.so, which are OpenSSL 1.0, rather than your libraries.
If you want to use a different suffix, you must change
SHLIB_EXTin the previous command, and set the
ANDROID_OPENSSL_SUFFIXenvironment variable before you access the Qt Network API.
make -j$(nproc) SHLIB_VERSION_NUMBER= SHLIB_EXT=<custom_suffix>.so build_libs
Then set the environment variable in your main.ccp file:
qputenv("ANDROID_OPENSSL_SUFFIX", "<custom_suffix>");
Note: Android does not load versioned libraries.
Using OpenSSL Libraries with Qt for Android
Depending on the method you obtained the OpenSSL libraries, you can use one of the following step to include those libraries in your project:
- Using the project files:
Using the convenience OpenSSL for Android repository, you can directly add the include projects into your own project, by adding the following to your
.profile:
android: include(<path/to/android_openssl/openssl.pri)
Or if using CMake, add the following to your
CMakeLists.txt:
if (ANDROID) include(<path/to/android_openssl/CMakeLists.txt) endif()
Alternatively, you can either use the Qt for Android variable ANDROID_EXTRA_LIBS to add extra libraries, mainly
libcryptoand
libssl. For QMake use:
ANDROID_EXTRA_LIBS += \ <path_to_libs_dir>/libcrypto_1_1.so \ <path_to_libs_dir>/libssl_1_1.so
For CMake:
set(ANDROID_EXTRA_LIBS <path_to_libs_dir>/ibcrypto_1_1.so <path_to_libs_dir>/libssl_1_1.so CACHE INTERNAL "")
Note: When targeting multiple architectures, include OpenSSL libraries for all the targeted architectures.
- Using Qt Creator, it is possible to add extra libraries. For more information, see Qt Creator: Adding Libraries to. | https://doc-snapshots.qt.io/qt6-6.1/android-openssl-support.html | CC-MAIN-2021-21 | refinedweb | 488 | 57.47 |
Variables from another class won't assign to main class
brent carter
Ranch Hand
Joined: Dec 15, 2011
Posts: 34
posted
Dec 15, 2011 13:06:02
0
Hey guys. Simple program and my variables are not recognized in the main even after calling them for assignment. When I try to print out the assigned Health, Strength etc variables in Line 20 it says they are not assigned. What am i doing wrong?
package rpgmain; import java.util.Scanner; public class Main { public static void main(String args[]) { System.out.println("Welcome to Earthbound!"); Scanner chooser = new Scanner(System.in); System.out.println("Do you want to be a fighter (1) or mage (2)?"); int Charpick; Charpick = chooser.nextInt(); if (Charpick == 1){ Fighter Fighter1 = new Fighter(); Fighter1.Fighterstats(); System.out.println("You have chosen: Fighter"); }else{ Mage Mage1 = new Mage(); Mage1.Magestats(); System.out.println("You have chose: Mage"); System.out.println("Health: "+ Health +" Magic: "+Magic+" Strength: "+Strength+" Heal: "+Heal); } } } package rpgmain; public class Mage { public void Magestats(){ int Health, Strength, Magic, Heal; Health = 50; Strength = 5; Magic = 25; Heal = 10; } } package rpgmain; public class Fighter { public void Fighterstats(){ int Strength, Health, Magic, Heal; Strength = 20; Health = 100; Magic = 10; Heal = 5; } }
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 11302
16
I like...
posted
Dec 15, 2011 13:19:59
0
There is no "Health" variable in scope in your main() method. Now, the Mage instance you have created has one defined. So, in line 20, tell it to print that:
System.out.println("Health: "+ Mage1.Health +...etc
Now, your code has several other issues, but this will get you past this first problem.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
brent carter
Ranch Hand
Joined: Dec 15, 2011
Posts: 34
posted
Dec 15, 2011 13:25:14
0
thanks for the reply fred. I tried this and it still said the same thing.
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 11302
16
I like...
posted
Dec 15, 2011 13:46:29
0
ah...I didn't look at your code close enough.
also, it would help if you would post the EXACT and COMPLETE text of what the error is. "not assigned" is different from "cannot find".
the problem is that your variables don't exist. look at your Mage class. You have nothing but a Magestats method. Inside that method, you declare the variables. That means those variable are local to that method. Once the method ends, the variables essentially disappear. You need to declare them as member variables...like this:
public class Mage { int Health, Strength, Magic, Heal; public void Magestats(){ Health = 50; Strength = 5; Magic = 25; Heal = 10; } }
Now the variables belong to each instance of the class. So, you can create 30 Mages, and each will have their own health, strength, etc.
A couple of notes....Classes should start with a capital letter. variables and such should start with a lower-case letter. So, your line
Mage Mage1 = new Mage();
really should be
Mage mage1 = new Mage();
and then the appropriate edits in your main method.
In a similar fashion, your Strength variable should really be named "strength".
There are a lot of other things we could talk about to make your code cleaner, but we'll worry about those another day.
brent carter
Ranch Hand
Joined: Dec 15, 2011
Posts: 34
posted
Dec 15, 2011 13:55:41
0
wow thanks for the nice reply. I've been on several different forums and no one answered me. I made the fixes and it worked.
I agree. Here's the link:
subject: Variables from another class won't assign to main class
Similar Threads
Class Practice Help
Question About Inheritance
seemingly identical code producing 2 different outcomes.
Calling a variable form the main class
calling same named variables in same class but in different subgroup
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/561863/java/java/Variables-class-won-assign-main | CC-MAIN-2014-41 | refinedweb | 674 | 74.39 |
Task: Write a Java program to Find Sum and Average of Array in Java.
First of all, the user will input 5 numbers of type double in array. After this, the Java program will calculate sum and average of the numbers in array.
Java Program to find Sum and average of Array
The source code of Java Program to find Sum and average of Array
/* * Write a Java program to input 5 double values in an array. find total and average of these values. */ package totalaverage; /** * @author */ import java.util.Scanner; public class TotalAverage { public static void main(String[] args) { Scanner input= new Scanner(System.in); double a[]=new double[5]; double sum=0.0, average; int i; for(i=0;i<5;i++) { System.out.print("Enter number in Array="); a[i]=input.nextDouble(); sum = sum + a[i]; } average = sum / 5.0; System.out.println("Sum ="+sum+ " and Average="+average); } } | https://easycodebook.com/find-sum-and-average-of-array-in-java/ | CC-MAIN-2020-05 | refinedweb | 151 | 52.46 |
VB2010. I understand how to save settings and load them from the My.Settings namespace. What I am trying to figure out is how to get the default value of a settings and present it to the user. I don't want to save the setting I just want to show what the current value is and what the default value is. I tried this but I don't think it does what I think it's supposed to do:
Msgbox "Current setting: " & My.Settings.CustLineWidth & vbcrlf & _
"Default setting: " & My.MySettings.Default.CustLineWidth
Current setting: 25
Default setting: 25
Current setting: 25
Default setting: 10
This worked for me:
My.Settings.PropertyValues("CustLineWidth").Property.DefaultValue | https://codedump.io/share/3QHVRnVmzGe1/1/vbnet-get-default-value-from-mysettings | CC-MAIN-2017-47 | refinedweb | 116 | 62.68 |
1
LUDMILLA ALEXEEVA RUSSI A — ACTIV IST were third-generation intellectuals. My mother was a mathematician and my father was a Communist. They came from very poor families who welcomed the Russian Revolution. They believed in the Communist ideals. The ideals weren’t bad; unfortunately, the result of imposing them in real life is a totalitarian state. Without cruel pressure, it is impossible to make people equal. I was born in 1927 and remember the beginning of World War II very well. My father was in the Soviet army and did not return. At the end of the war, I was a first-year history student at Moscow University and had begun to doubt the efficacy of Communist principles because of my experience of the poverty and totalitarianism in Soviet life. I could not discuss my doubts with anyone because, in Stalin’s time, to do so would have been very dangerous. I had known this as a small child. Everyone knew that even if we expressed our doubts cautiously, we would be arrested. The Communist Party was organized in such a way that it was possible to become a member, but there was no explanation as to how to leave the party. The only way out was to be excluded from it. Such exclusion meant you couldn’t have a job and there was no possibility of education for your children. You would not eat because there were no jobs outside state positions. You would simply be excluded from the national system. For that reason, I continued to be a party member, but I was not active. Only after Stalin’s death, when Nikita Khrushchev spoke openly about Stalin’s crimes against the Soviet people, could we discuss our doubts openly, although not officially. Censorship was not lessened, but there was more freedom to speak. I became very active in discussions with friends and acquaintances—not only about the problems of our country, but also about the relationship between power and society. Ten years after Stalin’s death, one could do this in private without being persecuted. This was particularly important for me personally because I needed to understand what kind of society my father had fought and died for. I wanted to know what future we could have. I did not see happy people around me and I was not happy either.
I also understood that this was not a personal problem; in my private life, everything was all right. I was discontented because I saw the terrible problems suffered by many of my compatriots. The human rights movement in Russia was born in the mid-1960s. Working for the movement was what I needed to do to be happy and fulfilled as a person. In the 50 years since then— in spite of being among unhappy people in a very unhappy country—I have been content because I do what I wish to do. Under Khrushchev it was easier to fight for human rights than it is now. Then there was a predictable price to be paid: you knew you would go to jail. Human rights activity under such conditions is difficult, but it is possible. Now the movement covers the entire country; it is no longer a small group of people. Many have joined us, and I believe they will continue what I began. In this administration, however, you do not know what to expect. There are cruel and unpredictable repressions. One can just be killed. Today, we do not live in a democratic state or in a totalitarian state. Ours is an authoritarian state. I doubt I will see democracy in Russia in my lifetime. But I know we will be a democratic country one day. I will never stop working to that end. I have two sons, one granddaughter, two grandsons, and two great-granddaughters. All of them live in America. During Brezhnev’s time, I emigrated, but as soon as it was possible to speak openly again, in the 1990s, I returned to Russia to live and work. I hope I am not a bad mother and granny to have left my family, but the sense of my life is to see the rule of law and democracy in my country. I believe it is important not only for me but for the younger generations too.
MY PARENTS
LUDMILLA ALEXEEVA (b. 1927) is an historian and activist; now in her eighties, she is considered the doyenne of Russia’s human rights community. A veteran of the 1960s dissident movement, she was a founding member of the Moscow Helsinki Group until forced into exile in 1977. In the United States, she was the group’s official spokesperson and a tireless advocate for its imprisoned members, writing extensively on the dissident movement and speaking regularly on Radio Liberty and Voice of America. When the Former Soviet Union (FSU) fell, she returned to Moscow and in 1996 became head of the revived Moscow Helsinki Group. It has flourished under her continued chairmanship and is now the oldest active Russian human rights organization.
16
ROBERT BADINTER FR ANCE — L AW Y ER which represents a man marked by a long life, is in fact me today. What can this old man say in his defense before the young lawyer he was 60 years ago who wanted to change justice?
The old man: “Do not forget my struggles to combat crimes against humanity everywhere. You know how close this cause is to my heart.”
THIS BEAUTIFUL PHOTOGRAPH,
The young man: “I find you are lenient with yourself. When I was 20 years old, there were other brilliant victories I needed to win in the name of justice. From the perspective of my dreams, your accomplishments are few.”
“I fought hard for justice in France so that it would no longer be a justice that kills. The death penalty is abolished. The guillotine is now a museum object. Are you satisfied?” The young man shakes his head: “It is true you did what you could, but it was François Mitterrand who made the political decision. You put the abolition into words. That’s all.”
The old man: “I think about you sometimes when crossing the Luxembourg Gardens; you were ruthless with yourself then. You have not changed. And that is very good. I am going to tell you a secret: I did what I could, that is all. I would like to start over to try to do better. But there are no second chances, alas. Farewell.”
The old man: “And those heads I saved, the six men whose heads the mob outside the law courts were shouting for? Well, it was I and my strength of conviction that snatched them from death.”
ROBERT BADINTER (b. 1928) is best known for successfully abolishing the death penalty in France. He devoted himself to the cause after the execution of Roger Bontems in 1972, for whom he had served as legal counsel. During the 1971 revolt in Clairvaux Prison, Bontems and a fellow prisoner named Claude Buffet had taken a nurse and prison guard hostage and their throats were slit. Although the defense maintained that Buffet was the one who had orchestrated the murders, Bontems was also sentenced to death by guillotine—a fact that struck Badinter as profoundly unjust. Badinter was Minister of Justice and then President of the Constitutional Council under François Mitterrand.
The young man: “The best of you in those moments was I, the young man still present within the lawyer in his prime who dictated fiery words that came from deep within, from the adolescent he was on the night of the occupation. It was I, the best of you. So, what else?” The old man: “I always fought to improve prisons so that detainees would be treated as human beings, deprived only of their freedom, whose rights and dignity were to be respected.” The young man: “I hear you. Can you say today, after so many years, that you feel the conditions of prisons have truly changed? Your eyes answer, ‘Alas.’ ”
18
AUNG SAN SUU KYI BUR M A — ACTIV IST.’s a mixture of greed and fear that pushes people to ill-treat others. They want to preserve their own security and enjoy the privileges to which their position entitles them. And also ignorance, because there are some people who really believe that it.
I DON’T THINK YOU CAN SAY
AUNG SAN SUU K YI elected to a seat in Parliament in spring 2012. Burma’s leaders continue to ignore the fact that she and her political party, the NLD, won the majority of votes in a 1990 national election.
20
SYDNEY KENTRIDGE SOUT H AFR ICA/BR ITAIN — L AW Y ER although now I cannot conceive of any other profession that I could have practiced with any success or satisfaction. My father was an attorney, but he was also a member of the South African Parliament for nearly 40 years—so politics were always part of my life. I had no particular interest in law, however, and I had never seen the inside of a courtroom. My decision was postponed by war service in the South African forces. After the end of the war, while still in Italy awaiting demobilization, I was told that the legal officers at South African headquarters had already been demobbed, and that I was to be the prosecuting counsel at two court-martials the following week. I protested that I knew no law. I was told that at least I had a university degree, and was given a small handbook of criminal law. I have little recollection of the cases themselves, but I found the trial process so absorbing that I knew that this was the profession for me. With the help of a grant from the South African government, I was able to take a law degree at Oxford University. In 1949, I began to practice at the South African Bar. I did not escape the usual travails of a young advocate, but I had one piece of good fortune. The apartheid government had come into power in 1948, and by 1949 its aggressive measures were being directed at trade union officials. Some of them began to brief me in cases against the government. From then onwards, although my main practice areas became commercial law and tort law, I appeared in many political trials in both civil and criminal courts, for members of various anti-apartheid organizations. Some critics questioned the effectiveness of fighting such cases, arguing that taking them to court gave a veneer of respectability to an oppressive system. However, the clients themselves almost invariably wanted legal representation, and, notwithstanding draconian legislation and a pattern of political appointments to the judiciary, it was sometimes possible to win. From 1958 to 1961, 90 leading members of the African National Congress and its allies were on trial in Pretoria on a charge of high treason. Naturally, it was a trial of great political significance. The historian Lord Macaulay said that in a trial for treason, an acquittal must always be considered a defeat for the government. In Pretoria, the court was a “Special Court” consisting of three judges specifically nominated for the case by the minister of justice—yet all the accused were acquitted.
Even when one had little hope of a favorable verdict, a hearing could be productive. At the inquest into the death in police custody of the black leader Steve Biko, the official verdict was “nobody to blame.” Nevertheless, as counsel for his widow we were, I think, able to expose the savagery and callousness that had led to his death. The black population of South Africa generally saw the law as an instrument of domination. I believed that it was important to show that the law could be a protector of liberty. I represented many remarkable men and women of all races, including Mr. Nelson Mandela; Bishop (not yet Archbishop) Desmond Tutu; and Chief Albert Luthuli, president of the African National Congress in the 1950s and 1960s, all three winners of the Nobel Peace Prize. After 30 years, I decided to practice the same occupation in a new country, and I was called to the English Bar. In England my practice has been a mixture of commercial and constitutional cases; I may, immodestly, mention one of the latter. The secretary of state for home affairs had deported an asylum seeker, despite the fact that a judge had issued an injunction prohibiting him from doing so before a further hearing. Proceedings for contempt of court were then instituted against the secretary of state. On appeal to the highest court (the House of Lords), the secretary of state contended that no court could issue an injunction against a minister of the Crown. I argued the contrary for the asylum seeker. We won. One of the judges said in his judgment that the case put up by the secretary of state, if successful, would have reversed the result of the 17th-century Civil War. The great English constitutional lawyer Sir William Wade said that this had been the most important constitutional case in England for 300 years. Can there be a more interesting profession?
I MORE OR LESS DRIFTED INTO THE LAW,
SIR SYDNEY KENTRIDGE (b. 1922) practiced law in South Africa for 30 years, becoming one of the most important advocates of the 20th century. He was the lead lawyer in the 1962 trial of Nelson Mandela and the 1977 inquest into the death of Stephen Biko, among other important political trials in apartheid South Africa. He served as an Acting Justice of the Constitutional Court of South Africa from 1995 to 1996. He was called to the English Bar in 1977 and appointed Queen’s Counsel in 1984. He was knighted (KCMG) in 1999. Sir Sydney has been married for more than 60 years to Felicia Kentridge, a founder of the Legal Resources Center, the leading human rights organization in South Africa. They are the parents of four children, including the artist William Kentridge.
30
DESMOND TUTU SOUT H AFR ICA — ARCHBISHOP EM ER IT US was deeply segregated. I was treated worse than the white children in our neighborhood of Klerksdorp, but I tried to make the best of it. I made toy cars out of wires and was read lots of books. My mother had only passed a few grades at school. She cooked and cleaned at a school for the blind. I have always known that I look like her physically—she was stumpy with a large nose—but I have also hoped to inherit her compassion, caring, and generosity. We were not well-todo, but we were all right—my father was an elementary-school principal. When my mother cooked, she cooked for more than just our family. She said, “You never know if somebody will come in who is hungry and we must be able to feed them.” My wife called her “the comfort of the afflicted” because she always stepped into a quarrel on the side of the one who was having the worst of it! When my family moved to Johannesburg, I was 12 years old and I almost died after contracting tuberculosis. It made me interested in the field of medicine; I was intent on becoming a doctor and finding a cure. Although my all-black high school was financially strapped, I received an excellent education and was given the impression that I could be anything I set my mind to be. I was accepted into medical school, but we could not afford the tuition, so I became a teacher instead and tried to inspire the same dreams in my students that my high school teachers had sparked in me. Then, in 1953, the Bantu Education Act was passed, effectively ensuring that no blacks would receive an education beyond the minimum needed for a life of servitude. I could no longer in good conscience be a part of an education system that deliberately advanced inequality, so I left teaching to become a priest. I have got to believe that we exist in a moral universe, that right will always prevail in the end, that we’re all—all of us, without exception—made for goodness. Going off the rails and doing wrong are the aberrations. It is a testimony to the extraordinariness of God, possessing all of that power, that God could say, “I’m going to create you. And I’m going to make you a person who has free choice.” We Christians believe that in the end God came into our world through Jesus Christ, who became a full human being in order to show us how to be human. We are enlisted by God in this extraordinary process, this great work of redeeming the world—a world where a Holocaust can happen, but also a world with people like Dietrich Bonhoeffer, a German Lutheran pastor, theologian, and martyr who opposed
Hitler. It is a world where you can have a Mother Theresa, a Martin Luther King Jr., a Mahatma Gandhi. And isn’t it extraordinary, in a world where might does sometimes seem to be right, that in the end it is goodness that prevails? We were involved in a struggle against the injustice of apartheid. Many times we seemed to be overpowered. The apartheid government had all the paraphernalia imaginable. Even so, goodness ultimately prevailed, and there were individuals whose actions have transformed the world for the better. Someone like the English Anglican bishop Trevor Huddleston, who was the second Archbishop of the Church of the Province of the Indian Ocean. I remember the first time I met him; I was walking with my mother, and the white priest tipped his hat as he passed us. I had never seen a white man pay his respects to a black woman. It made me realize the injustice of inequality, and the ability of religion to bridge the overwhelming gap between the treatment of blacks and whites. Huddleston became both a friend and a partner as we strove together to bring an end to apartheid. We worked with the hope of creating a just and democratic society without racial divisions, where blacks and whites could receive the same quality of education, possess equal civil rights, and live together. It is not the military junta in Burma that is admired by the world; it is a woman—petite, beautiful, with no military power but an extraordinary force for good. When I had the honor to announce the newly elected President Nelson Mandela, it was a glorious moment. I whispered to God that if I were to die, it would have been a suitable time. In the end, the truth will prevail over lies, light over darkness, life over death, human dignity over oppression.
THE SOUTH AFRICA OF MY YOUTH
ARCHBISHOP DESMOND TUTU (b. 1931) is Archbishop Emeritus of Cape Town, a veteran anti-apartheid activist and peace campaigner often described as “South Africa’s moral conscience.” He began his career as a high school teacher but turned to theology after the 1953 Bantu Education Act enforced racial segregation in educational institutions. He soon became well known internationally for his commitment to nonviolence and for his support for economic sanctions against apartheid South Africa. He organized many peaceful demonstrations and was awarded the Nobel Peace Prize in 1984 and appointed Chair of South Africa’s Truth and Reconciliation Commission in 1994. “Without forgiveness,” he says, “there can be no future for a relationship between individuals or within and between nations.” Since 2007, he has been the founding Chair of the Elders, an independent group of global leaders who promote peace and human rights worldwide. He is one of the most loved and respected activists of our time, a man whom Nelson Mandela once described as “sometimes strident, often tender, never afraid, and seldom without humor.”
50
JIMMY CARTER UNIT ED STAT ES — ACTIV IST All my neighbors were African American at a time when racial discrimination was legalized in the United States in the “separate but equal” ruling by the Supreme Court—a ruling that was supported by the churches, the American Bar Association, and all the state governments. No one thought of challenging racial segregation. My mother was a registered nurse and was impervious to pressures from her peer group to treat African Americans as inferior. She treated them as equals, and I learned that possibility from her. Later, as I became older, I saw that the racial discrimination legalized in our country was a devastating handicap for both black and white people. In my 1971 inaugural address as governor of Georgia, I said quite frankly that the time for racial discrimination was over. Never again would a black child be deprived of an equal right to education or any similarly basic need. It was a very brief speech, but it was so momentous that two weeks later I was on the front cover of Time magazine. As President, I said that America did not invent human rights: human rights invented America. I also announced that human rights would be the foundation of U.S. foreign policy, and my administration set an example that was later adopted and pursued. Ronald Reagan, who succeeded me, said that this stance was a sign of weakness, and he sent his UN ambassador to Chile and Argentina to tell them that Carter’s human rights policy had ended. In the succeeding months, however, Reagan abandoned his initial position and our country was enticed to resume its role as human rights champion. The Carter Center was established a year after I left office because governments and private organizations weren’t doing enough to protect their citizens and further their causes. We advocated two changes in the United Nations, beginning in 1993. One was to create a High Commission on Human Rights, a proposal that the incumbent secretary-general opposed very strongly. The second was the establishment of the International Criminal Court (ICC), which is primarily a deterrent to dictators who may be tempted to abuse their own people in a gross fashion. Both proposals have been adopted. The use of the rule of law in human rights is imperative, but it has its limitations. Last year I went to The Hague and met with the judges on the ICC. They described the overwhelming burden of new cases that were being presented to them; the court serves more as a deterrent than a sure punishment for
someone who has already committed a crime. At the same time, many leaders in the world are reluctant to step down from office because they are afraid they might be arrested by the ICC and punished. Impunity is therefore an argument that has arisen in the last 25 years among key human rights activists around the globe. I think impunity can be acceptable for the sake of protecting people, but other human rights activists, in their more pure way, feel differently. I keep a copy of the Universal Declaration of Human Rights on my desk. The U.S. government’s current policies are violating eight of the thirty human rights commitments that were made in 1948. The turning point was 9/11, when Bush began to circumvent basic human rights principles. President Obama has expanded George W. Bush’s agenda by proceeding with policies that violate the fundamental human rights commitments we had previously made. In the past, many countries were deterred from committing violations out of fear that the U.S. would condemn them in international public forums. Tragically, these countries now view the United States’ lapse in human rights enforcement as permission to commit atrocities that they would have otherwise been too afraid to carry out. We must realize that we are blessed people in America, and with privilege comes a responsibility to ensure that the same benefits are offered to others around the world. We must remember that we are all created equal. The poor people whom we tend to denigrate as inferior because they don’t have a proper home, adequate health care, decent education, or money in the bank, are no less intelligent, hardworking, and ambitious than we are. Their family values are just as good as mine. While some of us look on human rights as a theoretical and impractical form of idealism, we soon find, almost inevitably, that it is the most practical foundation for improving human life.
I GREW UP IN AN ISOLATED COMMUNITY IN GEORGIA .
PRESIDENT JIMMY CARTER (b. 1924) was the 39th President of the United States, serving from 1977 to 1981. Following his presidency, he established the nonpartisan and nonprofit Carter Center to promote democracy, protect human rights, prevent disease, and resolve conflict. The center’s health programs have led the international effort to eradicate Guinea worm disease, which is poised to be the second human disease in history to be completely eliminated. He and his wife, Rosalynn, volunteer for Habitat for Humanity, a nonprofit organization that helps needy people in the U.S. and in other countries renovate and build homes for themselves. He received the Nobel Peace Prize in 2002 for his decades of work on human rights, conflict mediation, and the promotion of economic and social development.
72
JESSELYN RADACK UNIT ED STAT ES — W HISTL EBLOW ER and joined the Justice Department through the Attorney General Honors Program, eventually becoming a legal adviser to the department’s new Professional Responsibility Advisory Office, which had been established to render ethics advice. Shortly after September 11, 2001, I received an inquiry from a Justice Department counter-terrorism prosecutor regarding the ethical propriety of interrogating “American Taliban” John Walker Lindh—a U.S. citizen allegedly fighting on the enemy’s side in Afghanistan—without a lawyer present. I had been informed that Lindh’s father had retained counsel for his son. Accordingly, I responded that interrogating Lindh was not authorized by law; the FBI proceeded to question him without an attorney anyway. When I was contacted again, I recommended that Lindh’s confession might have to be sealed and could only be used for national security and intelligence-gathering purposes, not for criminal prosecution. Five weeks after the botched interrogation, Attorney General John Ashcroft announced that a criminal complaint was being filed against Lindh. “The subject here is entitled to choose his own lawyer,” Ashcroft said, “and to our knowledge, has not chosen a lawyer at this time.” I knew that was untrue. Three weeks later, Ashcroft announced Lindh’s indictment, saying that his rights “have been carefully, scrupulously honored.” Ashcroft’s statement was contradicted by a trophy photo that was circulating worldwide of Lindh—naked, blindfolded, and bound to a board with duct tape. The next month, my supervisor gave me a blistering evaluation, despite my having received a performance award and raise a few months earlier. It did not mention the Lindh case by name, but it questioned my legal judgment. I was told to find another job, or the review would be put in my official personnel file. I had planned on being a career civil servant because I believed that public service was an important calling, and federal employment was the only way I could obtain health insurance as someone with multiple sclerosis. On March 7, 2002, the lead prosecutor in the Lindh case informed me that there was a court order for all of the Justice Department’s internal correspondence about Lindh’s interrogation. He said that he had two of my e-mails and wanted to make sure he had everything. I was immediately concerned because the court order had been concealed from me. Although I had written more than a dozen relevant e-mails, the Justice Department had turned over only two of them—neither of which reflected my concern that the FBI’s actions had been unethical and that Lindh’s confession, which formed the basis for the criminal case, I GRADUATED FROM YALE LAW SCHOOL IN 1995
96
could not be used. I checked the hard-copy file on Lindh and found that it had been purged. With the assistance of technical support, I then recovered 14 e-mails from my computer archives, gave them to my supervisor, and resigned. I also took home a copy of the e-mails in case they “disappeared” again. As the Lindh case proceeded, the Justice Department continued to assert that it didn’t know Lindh already had a defense attorney at the time of his interrogation. I heard a National Public Radio broadcast stating the Justice Department had never taken the position that Lindh was entitled to counsel during his interrogation. I did not think the department would have the temerity to make public statements contradicted by its own court filings if it had indeed turned over my e-mails, as per the court’s order. After hearing the broadcast, in accordance with the Whistleblower Protection Act, I sent the e-mails to a journalist who had been interviewed in the radio piece. He then wrote an article about the missing e-mails, which sparked a pretextual “leak investigation” against me. Shortly after my disclosure, on the morning that Lindh’s suppression hearing was to begin, Lindh pleaded guilty to two relatively minor charges. The surprise deal, which startled even the judge, averted the crucial evidentiary hearing that would have probed the facts surrounding his interrogation. Commentators widely agreed that the Lindh prosecution had “imploded.” In retaliation, the Justice Department placed me under criminal investigation without ever informing me of the alleged charges. It referred me to the state Bar authorities where I was licensed to practice law, based on a secret report I was not allowed to see, and I was placed on the “No-Fly List.” Senator Kennedy took up my cause, stating: “It appears Radack was effectively fired for providing legal advice that the Justice Department didn’t agree with.” Bruce Fein, a conservative constitutional scholar and a top Justice Department official under Ronald Reagan, represented me pro bono. I now write extensively on the plight of “enemy combatants” in the war on terrorism and have dedicated my career to representing whistleblowers who dare to speak truth to power. I live in Washington, D.C., with my husband and three children. JESSELYN RADACK (b. 1970) served as an Ethics Advisor to the Justice Department during the first terrorism prosecution following 9/11. Later, she served on the D.C. Bar Legal Ethics Committee and now represents whistleblowers as the National Security and Human Rights Director of the Government Accountability Project. Her 2012 book TRAITOR: The Whistleblower and the “American Taliban” became a best seller among human rights books.
SHAMI CHAKRABARTI BR ITAIN — L AW Y ER/ACTIV IST is from over a quarter of a century ago. I say “political” as if it were about a momentous demonstration or a general election, but it was actually much smaller and more personal—like most politics, in fact. It was evening, and I was watching the television news in my parents’ suburban semi. The hunt was on for the Yorkshire Ripper, a sadistic murderer who preyed on young women in the north of England in the late 1970s, and the dark story had run on the news for many nights on the trot. I don’t remember my precise words that evening. Perhaps I am now too ashamed of them. Something about what “they should do to an animal like that when they catch him.” I must have heard this kind of talk somewhere before, but that’s no excuse. The comment was not thought out or even really heartfelt, just something churned out to seem grown up and in control. My father’s response was uncharacteristic, for he has never struck me as a particularly reflective or nonjudgmental man. He had a quick temper, a loud voice and a big heart, but never in my experience had it been a bleeding one. “You can’t believe in the death penalty?” It was almost a whisper. “Why not?” I said. “I mean, for someone like that?” I felt wrong-footed and embarrassed by his response—that special adolescent feeling when you’ve gone a little out of your depth and don’t know a safe way back. “No criminal justice system in the world will ever be perfect,” he replied. “You have to imagine that you are the one innocent person in a thousand—no, a million. You’ve been convicted of the most heinous crime and you have to imagine your final walk to the gallows or the electric chair. ‘God!’ you think. ‘They say I’ve done this terrible thing. I know I haven’t, but even my family and friends won’t believe me and now they are going to kill me.’ ” This was how I learned about the presumption of innocence—the easy way. Not the way others of my generation held in Guantánamo Bay would learn about it, incarcerated without charge in a foreign land, but at home from a loving father—the accidental one-time evangelist for the cause of liberty. In later life, my dad heard this story and mentioned to me that he had no recollection of the incident whatsoever. He was no Atticus Finch—just this once. But sometimes once is enough. There are many arguments in favor of our evolved notions of justice, but human fallibility has long been my favorite—an individual frailty that can become systemic imperfection, and one that requires prompt charges, defense lawyers, presumed innocence, and proof beyond reasonable doubt to redress it. In England these essentials are older than running water and MY FIRST BIG POLITICAL MEMORY
should be undeniable. But the fear of terrorism has been like the fear of a thousand Yorkshire Rippers, and the political response has been more about effect than effectiveness. Professionally, I came of age at a time when Britain’s hardwon civil liberties and freedoms were under great pressure from within. The Blair legacy in Home Affairs was strangely contradictory. On the one hand, his government gave the United Kingdom its modern Bill of Rights by way of the Human Rights Act. On the other, the poorly labeled “war on terror,” sweeping police powers, and denigration of asylum seekers have threatened to poison our race relations. Lessons from Northern Ireland forgotten, Muslim terror suspects were subject to years of internment in Belmarsh prison and languish now under effective house arrest through the unfair, unsafe, control order regime. Our pre-charge detention period for terror suspects until recently was, at 28 days, the longest in the free world. And if there hadn’t been a parliamentary revolt against capitalizing on our fears, that period might have been three months. The most inexcusable act was the previous government’s willingness to turn a blind eye to torture. It refused to investigate reasonable suspicions that our airspace and airports have been part of the web of kidnap and torture called “extraordinary rendition.” It sought to rely on information gleaned from foreign torture in U.K. courts and to deport foreign terror suspects to countries known to employ torture rather than trying those suspects in Britain. The role of Liberty is to fight these authoritarian tendencies in British politics, to protect the vulnerable from becoming scapegoats for society’s suspicions and prejudices, and to broaden public understanding of the universality of human rights. We need to persuade politicians not to play politics with home affairs, law and order, anti-terror policy, and asylum. Populist policy doesn’t actually solve crime or terrorism, because it doesn’t deal with complex root causes. But it does leave us with an impoverished constitutional legacy and a statute book littered with corrosive laws that eat into our hard-won human rights and fundamental freedoms. SHAMI CHAKRABARTI (b. 1969) is a lawyer whose bold leadership is paving new roads for the well-established organization Liberty (officially known as the National Council for Civil Liberties). She has garnered media attention in the U.K. for her passion, quick wit, and articulateness. She was one of the main opponents of Gordon Brown’s plan to detain terrorist suspects for 42 days without charge and deserves substantial credit for the plan’s subsequent defeat.
118
HINA JILANI PAK ISTAN — L AW Y ER/ACTIV IST in Pakistan began in 1979 as a young lawyer struggling to uphold fundamental freedoms in the face of martial law. The policy of the so-called “Islamization” of the state—which this regime enforced as a measure to legitimize the unlawful derailment of the democratic order—proved to be extremely harmful for the right to equality for women and non-Muslim citizens. Special laws that reinforced social and cultural biases and imposed cruel, inhumane, and degrading punishments were used as a tool to instill fear in the population and silence dissent. The military regime solicited the support of religious groups and rewarded them with an influence over state policy that was totally disproportionate to their support amongst the population. These groups were then used to inflict violence on anyone who did not comply with their notions of morality or religion. It is in this environment that a few women and men launched a movement for human rights. On the one hand, we challenged religious precepts and the legitimacy of a regime that negated democracy; on the other, we educated the population on their rights and freedoms, which the state has a fundamental duty to protect. It was the first time in Pakistan that women’s rights became prominent in a movement for democracy, with women leading and having the opportunity to set the agenda. The military in Pakistan reacted by using violence on peaceful demonstrators; arbitrary arrests; trials by military courts; imprisonment and vilification of human rights defenders. These retaliatory measures became an unavoidable part of my life for several of the 11 years that the regime lasted. I had no illusions about the rule of martial law in Pakistan, however, which made such measures somewhat easier to endure. I had grown up in a house where politics was as intrinsic to life as food. I had learnt my lesson of “protecting justice and freedom at all cost” from a father who had been to jail repeatedly for his opposition to military and civil dictators. More remarkable for me was the courage and resilience of my fellow advocates, who were also bearing these tribulations—especially the women who had led lives relatively free of any direct repression. Looking back over these three decades of work, I consider every difficulty we faced and every action we took, whether in courts of law or in the streets, to be worth the struggle. Today, Pakistan can be proud of the human rights community and the vibrant civil society which the initiative of a few inspired. Human rights, particularly of women, are now an intrinsic part MY ENGAGEMENT WITH HUMAN RIGHTS
of the manifesto of all political parties. The defense of rights in Pakistan has given me a better understanding of how they can be promoted at the regional and international level. We not only forged durable outside support networks but also contributed a southern perspective to the development of global human rights policy. Lingering problems of our past are a continuing challenge. Poverty, bad governance, religious intolerance, terrorism, counterterrorism, increasing militarization, weak institutions, and ineffective systems of justice undermine the gains made by civil society. Many organizations—whether they are statecontrolled or adverse to it—find this an ideal environment to promote their agendas of hate, exploitation, and violence. Those who advocate economic justice, tolerance, and peace remain the first targets of these organizations. At the same time, the reinstatement of a political process and freedom of the media has given the public access to information and exposure to a variety of political views, which was not possible in the past. If these developments can promote human rights, and bring peace and security to the country, we may yet overcome the menace of terrorism and religious extremism that has become the major threat to stability and development in Pakistan. Of course, external factors also affect Pakistan’s prospects. The situation in Afghanistan, the strategic interests of countries such as the United States, the balance of power within South Asia, and the progress in Pakistan-India peace initiatives are all issues of current concern. It is in this context that regional and international initiatives on strengthening human rights, democracy, and peace have gained importance here. HINA JILANI (b. 1953) has been an Advocate of the Supreme Court of Pakistan since 1992 and was the Special Representative of the SecretaryGeneral on Human Rights Defenders from 2000 until 2008. Jilani was appointed Advocate of the High Court of Pakistan in 1981, and in the same year she established Pakistan’s first all-female law firm. Her cases have set the standard for human rights in Pakistan. Throughout her career, she focused on the rights of women, minorities, children, and prisoners. In 1999 she was honored with the Human Rights Award by the Lawyers Committee for Human Rights, and in 2000 she received the Amnesty International Genetta Sagan Award for Human Rights. As the Special Representative of the UN Secretary-General on Human Rights Defenders from 2000 to 2008, she has been part of critical human rights investigations undertaken by the UN in places like Darfur and Gaza. Her sister, Asma Jahangir, is President of the Supreme Court Bar Association of Pakistan and was the UN Special Rapporteur on Freedom of Religion or Belief from 2004 to 2010.
134
TAKNA JIGME SANGPO TIBET — POL ITICAL PR ISON ER/ACTIV IST Tibet was a country with a population of about six million people. We had a king, a bank, an army, and courts. The Chinese arrived in 1949. In 1959, the Chinese military attacked Chamdo, a region of eastern Tibet. On March 10, 1959, the Tibetans rebelled against the Chinese. But the uprising failed. One of Tibet’s two supreme leaders, his Holiness the Panchen Lama, wrote a 70,000-character petition to China’s Mao Zedong on behalf of the Tibetans, and as a result the Chinese branded him a separatist and sent him to prison. When I chose not to denounce him immediately, they imprisoned me as his follower. I was in prison for three years and released in 1968, at the beginning of the Cultural Revolution. I had been a teacher of Tibetan language and culture for children aged 7 to 12, and I was upset by China’s campaign to cleanse the schools and region of anything Tibetan. I became a spokesman for Tibetan freedom. This time I was put in prison for 10 years; the year was 1970. At Drapchi prison, I was treated very badly—they beat me, hitting my back and aiming right for my kidneys. The guards would stand on either side of me, holding me steady as one of their compatriots took a belt and whipped me hard. They also used a chain to tie my hands together so it was very difficult for me to lift up even a cup of tea to drink. They kept me bound that way for six months. For several years, they put chains around my upper arms and attached me to a wall. The chains were so tight they bit into my arms. They never killed me, because I was considered a political prisoner. I had done nothing wrong—committed no crime, killed no one—my only fault was to be an advocate for Tibetan freedom. I first heard about the concept of human rights in 1992. At that time there were also Chinese prisoners with us. Some of them would say to the police, “We prisoners are humans!” When I heard this I thought it was funny and wondered, “Well, of course we are humans!” The Buddhist religion taught us to love and have compassion for others, but not this political concept of “human rights.” That’s when I understood that the Chinese never considered me a person. Between 1959 and 1967, many of my fellow Tibetan prisoners had starved to death, committed suicide, or died of exhaustion from forced hard labor because they weren’t afforded basic human rights. China is intent on removing every remnant of Tibetan culture and religion. In Lhasa (the Tibet Autonomous Region in China), members of the Tibetan community are barred from using their own language, and Tibetan is not even taught in school. There are some colleges that claim to have Tibetan class, I WAS BORN IN 1932 .
but it’s all for show, as in a museum. These days the village schools are changing because Tibetan children are sent to China for higher education. They leave to study, and when they return as teachers they speak Chinese to the Tibetan children. The Chinese pay them what is considered a high salary for Tibetans in rural areas—two to three thousand yuan per month (about 300–500 U.S. dollars), to ensure the eradication of Tibetan culture and language. There is still hope that Tibet will be free one day, and it is because of this hope that I endured so many years in prison. Even if we don’t gain full independence, I believe if we follow the “Middle Way” approach of the Dalai Lama we will certainly gain more freedoms. Perhaps if China someday becomes a democracy, the people will then gain equality and power and Tibetans can live freely without fear. Altogether, I was in prison for 37 years. In 2001, I was told that I could go to America, but I had to promise that I would not return. I refused. I was subsequently locked in a tiny room measuring eight-by-four feet and kept there for a year under the constant observation of a Chinese guard. There was no air in the room; it had one small window that was always closed and covered with glass. It was hard to breathe. I often wondered if they were going to kill me or send me to China. In retrospect, they were probably watching me very carefully because an American named John Kamm was working on my release. John Kamm came to see me in June of 2002 accompanied by a policeman and a Chinese officer. They spoke about sending me to the United States, where the Americans would be kind to me. I was very excited because the chief of police of the Tibet Autonomous Region was there. The news spread all over Lhasa. I left Drapchi prison on July 10, with a new Chinese passport in hand. America was really famous among Tibetans at that time, and they talked about how cars there moved around like ants. As soon as I arrived in Chicago, I saw this for myself and was amazed. Even though in some ways I sacrificed my whole life for Tibet, in the end I feel that my life has turned out well. I’ve become a very happy person. I have gained freedom, and it is very good. TAKNA JIGME SANGPO (b. 1926) was first sentenced to three years of “re-education through labor” by the Chinese in 1964 for teaching Tibetan history, culture, and language to children. He spent 37 years as a political prisoner—the longest prison term served by a Tibetan—until he was released on medical parole in 2002 at the age of 76. He was known as “one of the most determined and intransigent political prisoners in Drapchi… highly respected by other political prisoners.” He now lives in Switzerland as a political refugee.
138
LOUISE ARBOUR CANADA — J U DGE/ACTIV IST It had the right mix of intellectual rigor, ethical grounding, and practical application. I became particularly interested in criminal law, and the work I do today to some extent reflects my lifelong interests in the fine lines between deviance and nonconformism—between confrontation and accommodation, power and abuse of power, liberty and security, good and bad. I have old French-Canadian roots; some of my ancestors are believed to have come off one of the early boats that touched the shores of the New World. This is why I always found it ironic, in my later international human rights work, to be described in some parts of the world as a neocolonial imperialist. If you overlook what we did to the earlier inhabitants of the continent, my story is that of a conquered, colonized people. I swear I don’t have a colonialist predisposition, but I concede that bad attitudes are not all inherited and most can be acquired. My career to some extent speaks of an era—not just of opening opportunities for women in the legal profession and in public life but also of greater opportunities within the law for everyone. My work in Canada, first as an academic, then as a judge, is largely a product of the feminist movement of the ’60s and ’70s and of the liberalization of society that followed. The impetus for the kind of change reflected in my professional life is rooted, I think, in The Canadian Charter of Rights and Freedoms, which in 1982 launched a culture of rights anchored in ideals of equality and fairness. The opportunities that presented themselves to me on the international scene were of the same nature. The prosecution of war criminals in the former Yugoslavia and in Rwanda in the mid-1990s was an unprecedented effort to see justice as a form of peacemaking. But there is still tension, internationally, between the aspirations of peace and of justice. In the common law system, a police officer is called a “peace officer.” A crime is a “breach of the peace.” Yet the prosecution of war criminals by international courts is often viewed as an irritant to peace processes. Many still argue that tyrants and dictators responsible for atrocities should be given amnesties if that is the price that must be paid for their peaceful departure. While it is true that war may be too high a price to pay for justice, peace built on unredressed grievances and real injustices is unlikely to be lasting. As elsewhere, the tensions between these two legitimate aspirations—to peace and to justice—can only be accommodated in a THE LAW WAS A GOOD FIT FOR ME FROM THE BEGINNING.
contextual fashion, and without elevating either as an exclusive absolute. Everything—peace, justice, truth—can be either pursued with too much zeal or abandoned at too high a cost. In my work in the courts of Canada, I dealt with controversial issues such as a prisoner’s right to vote, the integration of severely disabled children into mainstream public classrooms, and a wide range of protections for criminal defendants. I conducted a yearlong inquiry into what was at that time the only federal prison for women in Canada, uncovering profound failures in the administration of justice. I believe that the hallmark of a democracy is its ability to offer adequate protection to minority rights and interests, and to account publicly for its shortcomings. After moving from international criminal justice to the broader field of international human rights, I took a dramatic plunge into the unknown to join the International Crisis Group. The Crisis Group is a nongovernmental organization whose mission is the prevention of deadly conflicts. It has intellectual rigor, ethical grounding, and practical applications. Even though in that sense it is a comfortable and familiar environment, I am very conscious that I have now abandoned the law that had been my intellectual framework and my comfort zone. I have abandoned the formal institutional environments in which I had spent my entire life: the convent school, the courts, the United Nations. I wore a uniform until I was 20 years old and ready to go to law school. I swore I would never wear a uniform again. Then I became a judge, and wore a uniform again for the next 15 years. In retrospect, it is clear that I liked the anonymity of it all, and the sense of belonging. I travel broadly and frequently. When I am asked to fill out a customs and immigration form, I always pause at the question, “What is your occupation?” Although I am president of the International Crisis Group, somehow I find that “president” is both pretentious and nondescript. So I always write “lawyer.” LOUISE ARBOUR (b. 1947) was Chief Prosecutor for the International Criminal Tribunals in the former Yugoslavia and Rwanda, where she indicted then-Yugoslav President Slobodan Milosevic for war crimes—the first time a serving head of state was prosecuted before an international court. She was subsequently appointed UN High Commissioner for Human Rights. She has been a Justice of the Canadian Supreme Court, and writes extensively on human rights, gender issues, international law, and conflict. She is President of the International Crisis Group.
178 | https://issuu.com/marianacook/docs/justice-issuu | CC-MAIN-2016-50 | refinedweb | 8,858 | 60.65 |
Bug#340869: mpdscribble: No songs saved/submitted, only 'skipping detected' in /var/log/mpdscribble.log
Michal Čihař writes: Oops, this is caused by added patch. As temporary workaround you can set higher sleep interval in configuration (5 should be okay). Ah, yes, the default is 1 isn't it. Didn't think of that. I'll work out a better solution and get warp to approve it. Rebuild coming up!
Bug#321664: Update?
Anything going on with this? I just need one alternate added to the dependencies. I can prepare an NMU if needed. -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Bug#347417: Replace with pysyck?
Package: python-syck Version: 0.55-3 Severity: wishlist The bindings built from the syck source do not work very well at all. There is an alternative binding, with its own source, called PySyck. See here:
Bug#321664: Please do not depend on libxaw8-dev.
David Martínez Moreno writes: Please, Decklin, could you point what do you find in libxaw8 that you have not got in libxaw7? As far as I can tell, libxaw8 differs from libxaw7 in the print code, which is actually disabled. X Strike Force' plans are, among others, drop libxaw8 packages in
Bug#342638: typing in Custom box does not save crossfade offset
Package: bmp-crossfade Version: 0.3.9-1 Severity: normal If I set the crossfade type for a particular event to Advanced and select Custom(ms) for the offset, typing a new value into the input box and clicking OK does not save this value. Using the up and down adjustment buttons, or typing in a
Bug#342693: yafc: Ctrl-C behaviour is annoying
Andrew Ferrier writes: In bash, and most shells, Ctrl-C seems to kill the current line and open a new prompt. However, in yafc, pressing Ctrl-C also disconnects from the server one is connected to. My thought is that if something is open (running) in a shell, ctrl-C kills it, so I hadn't
Bug#342638: typing in Custom box does not save crossfade offset
Florian Ernst writes: Does this occur when using 0.3.10-1 as well? I expect it does, but I just want to make sure... Yep. :( I will look into the code if I get a chance... of the top of my head, I believe the prototype for gwhatever_connect_signal changed from GTK+ 1.2 to 2.x, but you'd
Bug#342747: randomly cuts out previous song when starting crossfade
Package: bmp-crossfade Version: 0.3.10-1 Severity: normal (This is also present in 0.3.9-1.) With bmp-crossfade set up to do an advanced crossfade on automatic songchange, it will sometimes, seemingly at random, stop the current song completely when it hits the point where it should start
Bug#342747: Acknowledgement (randomly cuts out previous song when starting crossfade)
Actually... I think it may just be happening when I start song 1 from the beginning. Or perhaps just let it play for a certain length of time before the fade starts. -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble?
Bug#337088: please --enable-xpm-background
Package: rxvt-unicode Version: 5.8-1 Severity: minor It would be nice if the regular (not -lite) packages of rxvt-unicode were built with --enable-xpm-background, for consistency with with regular rxvt. -- System Information: Debian Release: testing/unstable APT prefers unstable APT policy:
Bug#337842: ITP: pygmy -- PyGTK client for the Music Player Daemon (MPD)
Package: wnpp Severity: wishlist Owner: Decklin Foster [EMAIL PROTECTED] * Package name: pygmy Version : 0.45+svn60 Upstream Author : Andrew Conkling [EMAIL PROTECTED] * URL : * License : GPL Description : PyGTK client
Bug#338275: should use _NET_CLIENT_LIST in preference to _NET_CLIENT_LIST_STACKING in taskbar
Package: fbpanel Version: 4.1-2 Severity: normal Tags: patch For some reason, the taskbar plugin uses _NET_CLIENT_LIST to initialize itself but _NET_CLIENT_LIST_STACKING to update. It is possible that a window manager might set the client list but not stacking information (perhaps it is strictly
Bug#344915: allow building initrd's temp dir in /tmp, rather than /boot
Package: kernel-package Version: 10.026 Severity: wishlist (I am using yaird to build my initrds, although I don't think this matters.) I have a relatively small /boot partition, and as I'm testing some different hardware configurations I have more kernels than usual in there. Sometimes, in a
Bug#345349: [EMAIL PROTECTED]: Bug#345349: rawdog: Contains invalidly-licensed feedparser.py]
Adam, what do we have to do to merge the rawdog-specific changes into feedparser 4.0? Are all (any) of them still necessary? It would be nice to be able to depend on the python-feedparser package. - Forwarded message from Joe Wreschnig [EMAIL PROTECTED] - Subject: Bug#345349: rawdog:
Bug#332602: socks4-clients: should depend on libsocks4
Package: socks4-clients Version: 4.3.beta2-14 Severity: normal Subject says it all. rtelnet: error while loading shared libraries: libsocks.so.4: cannot open shared object file: No such file or directory -- System Information: Debian Release: testing/unstable APT prefers unstable APT
Bug#332637: config for xserver-xorg/autodetect_mouse broken
merge 332637 332369 kthxbye Steve Greenland writes: During the upgrade to -8, I was asked three times whether I wanted to attempt mouse device autodetection. I noticed this as well, but found it was already filed. :-) -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to
Bug#334921: patch to add a few more window operations
Package: xwit Version: 3.4-7 Severity: wishlist Tags: patch This implements a few more window management actions which are somewhat obscure, but useful to me. -- System Information: Debian Release: testing/unstable APT prefers unstable APT policy: (500, 'unstable'), (1, 'experimental')
Bug#336033: sponsor
Michal, is your sponsor back yet? I could upload this if you wish. I also have a one-liner to merge... warp's mail is bouncing at the moment, so it's not in upstream yet. -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble?
Bug#336033: sponsor
Michal Čihař writes: Upstream author's email is AFAIK Kuno Woudt [EMAIL PROTECTED]. What kind is one liner to merge? Yeah, MX isn't answering. Here's the one-liner, see attachment. If you could put it in your diff and upload the source somewhere I can build the .deb. Thanks. -- things
Bug#145798: netcat: openbsd's rewrite of netcat might help some ppl... or not
Sam Hocevar writes: Could you please elaborate on your tagging #145798 +wontfix? Debian users are stuck with a netcat from 1998 that isn't maintained while the OpenBSD netcat has support for IPv6, Unix sockets etc. If you don't have time to package a newer version, I can help; if you
Bug#390417: mpd --create-db fails with xmalloc assertion
Jonathan Wheelhouse writes: However, when it tries to load the music (via a mpd --create-db) it fails with the following: added Classical/Vivaldi, Antonio (1678-1741)/Vivaldi (Musici San Marco)/03 Vivaldi, K571 (F).mp3 mpd: /tmp/buildd/mpd-0.12.0/./src/utils.c:126: xmalloc: Assertion
Bug#390511: mpd: please add pause/resume/stop fades
Blue Beret writes: I did use XMMS with Crossfade plugin before switching to mpd. There was a feature to make a quick fadeout on pause/stop and a quick fadein on resume. Could this be added to mpd? There is crossfading between songs, but not on start and stop. Some sort of additional mechanism
Bug#390417: temporary work-around
retitle 390417 can't play certain mp3 files if maxFrames is not determined kthxbye I've uploaded 0.12.0-2, with the patch, but I'm leaving this open as playing the affected file does not actually work (Eric had the same result when I checked on IRC). You should be able to update your database,
Bug#381969: rxvt-unicode: /etc/X11/app-defaults/URxvt should set Rxvt.*, not URxvt.*
Reuben Thomas writes: I just spent a long time trying to work out why Rxvt.font didn't seem to work when all the other Rxvt.* resources did, and I finally discovered that this was because URxvt.font is set in /etc/X11/app-defaults, rather than Rxvt.font. Why can't you set Rxvt.* resources
Bug#381967: In fact, only explanation is needed, as this feature already exists
Reuben Thomas writes: So in fact my wishlist item has already been implemented; what is really needed is to update the update-alternatives list so that it mentions urxvtcd rather than urxvt (or maybe have both; some people prefer the stability of separate processes). Thanks; an
Bug#382634: mpd: install init script at startup fails
Julien Delange writes: MPD db at /var/lib/mpd/mpddb not found, creating. Starting Music Player Daemon: mpd. Could you explain what happens after this step? Either MPD should be running, or there should be more errors. -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL
Bug#488877: ITP: libtrollop-ruby -- command-line argument processing library
Excerpts from daniel's message of Sat Oct 11 06:11:21 -0400 2008: Just dropping a note to ask if you're getting anywhere on packaging Trollop? I have made a package, in the apparent absence of activity on your end, so I'll take over this ITP and get it uploaded 1 week from now if I don't hear
Bug#457174: FD_SETSIZE
Excerpts from Samuel Tardieu's message of Mon Oct 13 04:29:55 -0400 2008: Loic's patch is not so about the *number* of file descriptors but about the *largest* file descriptor that can be used in netcat. Yes, I know how select(2) works; since its usage was fixed in the other patch, I don't
Bug#457174: FD_SETSIZE
Excerpts from Samuel Tardieu's message of Mon Oct 13 18:13:08 -0400 2008: Agreed, it should be eliminated and the system default should be kept. Anyway, I withdraw my request, we switched to socat today after I had a look at the netcat code, and it fits its job perfectly, so we won't be using
Bug#488877: ITP: libtrollop-ruby -- command-line argument processing library
Uhm, sorry. Apparently this was overlooked in the round of library uploads for sup-mail. Uploading now. Excerpts from Daniel Watkins's message of Sun Oct 19 10:17:29 -0400 2008: owner 488877 [EMAIL PROTECTED] thanks Hi Decklin, Excerpts from daniel's message of Sat Oct 11 06:11:21 -0400
Bug#502875: returns wrong version number
Excerpts from W. Martin Borgert's message of Mon Oct 20 10:58:47 -0400 2008: mpd returns '0.13.0' instead of '0.13.2'. I installed python-mpd and typed in python: I have indeed noticed this writing Njiiri, it does look pretty silly :-) Next upstream release will fix this; since it's cosmetic I
Bug#499410: cannot properly read from stdin
tags 499410 +patch thanks Here is a patch to solve the issue. (I was a bit shocked to not be able to just run pastebinit and paste something in...) It makes pastebinit behave in a more standard manner: no filename is equivalent to -, not an error. I have had to adjust some of the messages (as
Bug#500703: urxvtcd: increments $SHLVL for daemon process
martin f krafft writes: Since /usr/bin/urxvtcd is a shell script, it will increase $SHLVL for urxvtd's environment Well, only if /bin/sh is bash. What is the problem caused by increasing $SHLVL? What is $SHLVL good for? (I don't use bash.) According to the documentation, it is incremented by
Bug#500703: urxvtcd: increments $SHLVL for daemon process
martin f krafft writes: Well, only if /bin/sh is bash. No, also with dash and zsh. And for the cases where $SHLVL is not set, my patch will just no-op. I tested dash here and it didn't (the man page also makes no mention of SHLVL either). Are you sure? As for zsh, I suppose I should have... I think... Well,
Bug#491367: Patch for the l10n upload of lastfmsubmitd
Thanks. I'll be uploading in a few hours (sorry, forgot you were in +0200 and might not see this until tomorrow.) Christian Perrier writes: diff -Nru lastfmsubmitd-0.37.old/debian/changelog lastfmsubmitd-0.37/debian/changelog --- lastfmsubmitd-0.37.old/debian/changelog 2008-09-28
Bug#432731: gmpc gives the same error (about new libmpd) after latest upgrade
Eran writes: Trying to run gmpc with a wrong libmpd version. This will be fixed (properly) with the next libmpd. -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Bug#358619: please prefetch the buffer for the next track
martin f krafft writes: I am sure it didn't at the time, so please close the bug with the appropriate version number; I don't use mpd anymore. Will do. -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL
Bug#500049: ITP: ears -- collection of MPD/Last.fm clients
Package: wnpp Severity: wishlist * Package name: ears Version : 1.0.0 Upstream Author : Decklin Foster [EMAIL PROTECTED] * URL : * License : MIT Description : Last.fm plugin for MPD and CD ripper Ears contains
Bug#493480: excessive dependencies in rxvt-unicode-lite
Hans Ekbrand writes: This seems like a mistake, since the description of the package has not changed, and explictly says that the lite version is built without freetype support. Someone requested Xft, I believe, but I have no idea why GTK is in there; that is definitely a mistake. (I don't
Bug#498911: fixed in mpd 0.13.2-2
Julien Cristau writes: Well that's not quite correct. If start-stop-daemon fails, the init script is supposed to fail if mpd isn't running after start, or it's still running after stop... Adding '|| true' to s-s-d invocations is wrong, IMHO. You're right. Since #478018 was fixed by fixing
Bug#495066: rxvt-unicode: embedding perl needs PERL_SYS_INIT3()
Niko Tyni writes: As described in the 'perlembed' document, programs embedding Perl must use the PERL_SYS_INIT3() and PERL_SYS_TERM() macros to provide system-specific tune up of the C runtime environment necessary to run Perl interpreters. I'd like to do this, but I'm currently getting:
Bug#460453: xbase-clients: xgc has gone missing,
Bug#460453: xbase-clients: xgc has gone missing
Brice Goglin writes: Assuming that we find some time to re-package xgc, in which package would you like to see it? Since it seems to be a demo program, I guess x11-apps would be the best? x11-apps sounds appropriate to me. Thanks. -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE,
Bug#460560: rxvt-unicode-ml: Invalid memory reference
merge 460560 460561 460563 thanks Yair Mahalalel writes: /usr/bin/urxvtcd -u8 -bg #00 -fg #eecc44 -fa bh-courier:size=12:bold This doesn't appear to be a valid set of options. Could you please describe exactly what you did? Under what other circumstances does it crash or not crash? (no
Bug#460560: rxvt-unicode-ml: Invalid memory reference
(Cc'ing bug...) Yair Mahalalel writes: It isn't a valid option set for urxvt, but for xterm. I just launched it like that to see what will happen. I am not even sure this is a bug, except for under DebReaper's broad definition of the term. :-) It would also be helpful if you could build
Bug#145798: netcat: openbsd's rewrite of netcat might help some ppl... or not
retitle 145798 ITP: netcat-openbsd -- TCP/IP swiss army knife reassign 145798 wnpp thanks Due to feature requests (UNIX domain sockets, SOCKS) that are difficult to implement in the current, aging netcat code base, I have decided to once again look into packaging OpenBSD's version. At the present
Bug#461335: hmm
Joey Hess writes: The system didn't have alsa-base installed either. When I installed that, apt configured mpd afterwards, and it configured ok then, with the USB sound device still not present. Can you run mpd --no-daemon --stdout without alsa-base installed? Detection should work this way
Bug#463739: vidir: fails if filesystem is full
Package: moreutils Version: 0.26 Severity: grave Tags: patch If TMPDIR lives on a filesystem that is full, vidir will be able to open a temp file, but not write to it. The user will then be presented with an empty file, and if they leave their editor, vidir will act as if all lines were deleted,
Bug#463901: mpd needs 'shout' audio output plugin compiled in package - Lenny
Brian Millan writes: Supported outputs: alsa ao oss pulse jack Hmm. Unfortunately, this is not surprising. See #453746; we don't build with libvorbis on arm, but rather libvorbisidec (Tremor, the integer decoder); e.g. the NSLU2 doesn't have a FPU so regular libvorbis is unacceptably slow.
Bug#452295: lastfmsubmitd: unable to submit songs due to a missing import in client.py
Sorry, it totally slipped my mind that I should have cut a release soon after fixing these. I will do so for tomorrow. -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Bug#460123: Cannot upgrade mpd - package tries to restart mpd but bombs out if mpd is not running
merge 460123 460016 thanks Nigel McNie writes: I am assuming that if the initscript was converted to use that, then me removing the /etc/rc*.d symlinks would mean that upgrading mpd wouldn't try and stop/start it. I would expect similar behaviour for START_MPD=false too. This appears to be
Bug#452295: lastfmsubmitd: unable to submit songs due to a missing import in client.py
Adeodato Simó writes: Thanks, and sorry I didn't find time to test lastfmsubmitd before it migrated to testing. I should have had something to test with that *doesn't* already use the marshaller... oops. What are you working on, anyway? (Feel free to reply off-bug.) -- things change. [EMAIL
Bug#439211: Updated patch
Adeodato Simó writes: Here's a patch that applies to lastfmsubmitd 0.36. Thanks for the reminder. I've implemented this in slightly different form, since at least lastmp needs it as well. Should be out shortly. -- things change. [EMAIL PROTECTED]
Bug#452849: lastfmsubmitd: please package lastfm python bindings separately
Teemu Ikonen writes: Some player packages (like quodlibet-plugins) depend on lastfmsubmitd, but only use the included python bindings to directly submit to last.fm when online. Installation of lastfmsubmitd itself is not really needed in these cases, and the debconf questions about last.fm
Bug#453746: build with tremor support on arm
Joey Hess writes: The attached patch builds --with-tremor on all arm architectures. Many thanks. Uploading fix presently. (Actually, looking into a strange dpkg-shlibdeps warning first, but it'll be done later today.) I have tried looking at the select()/poll() bugs again, but even though your
Bug#454626: (no subject)
giggzounet writes: But it doesn't explain why when I do '/etc/init.d/mpd stop' there are 2 others mpd processes at each time. When MPD is actually running, this is normal. It seems that you actually have an ALSA problem here. I'm adding an additional note to the readme about standard practices
Bug#454626: (no subject)
Giggz wrote: Euh sorry I'm a newbie... How do I run mpd under strace ?... You will need to stop mpd normally and then run the mpd binary directly with --no-daemon. i.e.: sudo invoke-rc.d mpd stop sudo strace /usr/bin/mpd --no-daemon -- things change. [EMAIL PROTECTED] -- To
Bug#454626: [Fwd: Bug#454626: mpd: crash when I pause the song then I play it]
giggzounet writes: Sorry to email you directly... No problem. I am assuming that you experience the hang at the same time that this starts: select(0, NULL, NULL, NULL, {0, 1000}) = 0 (Timeout) select(0, NULL, NULL, NULL, {0, 1000}) = 0 (Timeout) select(0, NULL, NULL, NULL, {0, 1000}) = 0
Bug#447709: rxvt-unicode: the meaning of `-fg' and `-bg' options is inverted
Valery V. Vorotyntsev writes: `urxvt -fg gray90' makes _background_ gray, while `urxvt -bg gray90' changes font color (foreground). I cannot reproduce this. Are you sure you didn't turn on reverseVideo? `urxvt -rv -fg gray90' behaves as you describe. -- things change. [EMAIL PROTECTED] --
Bug#431497: rxvt-unicode: cutchars resource is not honored
Sebastien Delafond writes: I have the following in my ~/.Xdefaults: URxvt.cutchars: `'()*,;[]{|} URxvt.font: xft:Bitstream Vera Sans Mono:pixelsize=13 While the font resource is honored, the cutchars one is not: double-clicking on foobar only selects half of the string. The problem
Bug#415849: rxvt-unicode: url parsing of mark-urls appears to be suspect
Reuben Thomas writes: The problem I noticed is that in the following text: (). this URL is highlighted:) which is unlikely to be right, yet omits a potentially valid character, .. (I'm not sure whether parentheses, on the other hand, are legal.)
Bug#457658: rxvt-unicode 8.7-1 segfaults in ppc, merged to testing despites a previous bug report
Nicolas Trecourt writes: urxvt: ./../libev/ev.c:1094: void timers_reify(): Assertion `(inactive timer on timer heap detected, (0 + ((ev_watcher *)(void *)(w))-active))' failed. Aborted The problem was reported in sid, and the package was still merged. While I am sorry that my bumping the
Bug#457172: Patches for portability of netcat package
Loic Fosse writes: -#define HAVE_BIND/* ASSUMPTION -- seems to work everywhere! */ +//#define HAVE_BIND /* ASSUMPTION -- seems to work everywhere! */ I'm not going to include this one; I think -UHAVE_BIND would be more appropriate on systems where this would otherwise
Bug#457171: Netcat does not provide an esay way to chech its version
Loic Fosse writes: Version of Netcat can only be check with the -h option, which exits netcat with an error. It It is not very convenient for scripting. Attached to this email you will find a patch to fix this. I have chosen to reduce the impact of this patch by only correcting the exit
Bug#457174: Fix fd value check in netcat
Loic Fosse writes: @@ -48,7 +48,7 @@ #ifdef FD_SETSIZE/* should be in types.h, butcha never know. */ #undef FD_SETSIZE/* if we ever need more than 16 active */ #endif /* fd's, something is horribly wrong! */ -#define FD_SETSIZE 16
Bug#450676: netcat: Add examples to manpage [patch]
James R. Van Zandt writes: I suggest some examples be added, such as the following. This first one is already included in README, which is pointed to by the man page. I don't want to duplicate it. (The man page is pretty hairy as it is...) I've added the second one to README.Debian; hopefully
Bug#463117: mpc: please add a command to query the playlist as unique objects (like filenames)
Helmut Grohne wrote: mpc playlist outputs the playlist as: entrynumber) artist - title With a bad collection artist - title doesn't have to be a unique, so it is impossible to find out what some entries really are. It would be cool if there was some option to make mpc output the playlist as
Bug#393457: Reproduced in mpd 0.13.0-5
John Sullivan wrote: Symptoms are the same as reported earlier -- resuming with mpc play hangs, mpc doesn't give status and times out, but killall mpd and restarting with the init script starts the music again. Apologies this is a brief report, I'll try to provide more info if it would help.
Bug#291298: should rawdog depend on python-xml?
Could you follow up on this bug please? sgmllib is included with python, and xml.sax is imported within a try block. It still works with or without python2.3-xml for me. -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble?
Bug#299828: ITP: python-mpdclient -- Python interface to MPD (Music Player Daemon)
Package: wnpp Severity: wishlist Owner: Decklin Foster [EMAIL PROTECTED] * Package name: python-mpdclient Version : 0.10.0 Upstream Author : Nick Welch mack at incise dot org * URL : * License : LGPL Description
Bug#299830: ITP: python-beautifulsoup -- error-tolerant HTML parser for Python
Package: wnpp Severity: wishlist Owner: Decklin Foster [EMAIL PROTECTED] * Package name: python-beautifulsoup Version : 1.2+cvs20041017 Upstream Author : Leonard Richardson [EMAIL PROTECTED] * URL : * License
Bug#290640: attempts to rotate logs as `mpd' even when this user does not exist
Package: mpd Version: 0.11.5-2 Severity: normal When installing mpd I told debconf not to run it from an init script (see below). Accordingly, it didn't create a user to run system-wide mpd as. Now I'm getting this every day from cron. /etc/cron.daily/logrotate: error: mpd:8 unknown user
Bug#291298: should rawdog depend on python-xml?
Graham Wilson writes: I wasn't able to get rawdog to work without python-xml installed for the few feeds that I tried it with. Does it need python-xml for all feeds? Actually, feedparser does. Oversight on my part. I'll upload a fix right away. -- things change. [EMAIL PROTECTED] -- To
Bug#291298: should rawdog depend on python-xml?
Graham Wilson writes: If so it should probably depend on it, and if not, it should probably recommend it at least. Wait, ignore what I said before. What is the actual error you're getting? -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of
Bug#434292: gmpc: assertion `column-tree_view == NULL' failed
severity 434292 important thanks Mykola Nikishov writes: Gmpc dies with failed assertion: Gtk-CRITICAL **: gtk_tree_view_append_column: assertion `column-tree_view == NULL' failed aborting... Could you provide the steps to reproduce this? -- things change. [EMAIL PROTECTED] -- To
Bug#432731: gmpc: Not linked against libmpd 0.14.0-2 but 0.13.0 witch is not installed.
Jimmy Olsson writes: Version: 0.14.0-5+b2 Followup-For: Bug #432731 Please use 0.15.1. I have freed this up to enter testing momentarily. -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of unsubscribe. Trouble? Contact [EMAIL PROTECTED]
Bug#439517: mpd should start earlier
reassign 439517 lastfmsubmitd thanks LastMP should start later, if this is actually a problem; 30 is really rather early already. Clearly mpd needs to start before lastmp and lastfmsubmitd I note that * MPD does not have to even be running on the same machine (this is the whole point)
Bug#411139: mpd: Please consider adopting my various improvements at debian.jones.dk
Jonas Smedegaard wrote: Please consider adopting some or all of my various improvements at my unofficial patched mpd package here: Hi, Thanks for this. I apologize for being MIA. I will review these, merge and upload sometime this week. --
Bug#392763: mpd: Another request for pulse audio support
Steve Greenland wrote: Just AOLing to indicate interest in having pulse support. This will be included as soon as I am ready to rebuild -- should just be a few days. My apologies for being MIA for so long. -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL PROTECTED]
Bug#363472: rawdog: cannot use feeddefaults in config file
Thijs Kinkhorst writes: If I include the feeddefaults option in the config file, I get the following when running rawdog -u: In config: Bad line in config: feeddefaults I can confirm this, and it's especially annoying because this directive is in the example config file. Hi, and
Bug#396134: wtf
reopen 396134 severity 396134 wishlist thanks There is no ESD plugin. Please disregard the incorrect close message (I thought I had merely disabled it). I guess this bug can be left as a someone wants an ESD plugin to be written bug instead, although this probably isn't going to happen. --
Bug#407812: should check whether data is waiting instead of just reading
martin f krafft writes: retitle 407812 deadlock due to read() without select() Thanks, guys; my apologies for being MIA. I haven't gotten a handle on this yet, but I am able to reproduce it (consistently) without hitting any of the network code -- my library on this installation is mounted via
Bug#407812: should check whether data is waiting instead of just reading
Eric Wong writes: Warren made a patch that should fix the problem with HTTP below, OK, the inputStream_file.c does in fact fix the NFS case (at a very cursory test, anyway). For the HTTP case I will need to make a patch to pull in the changes to inputStream_httpRead in SVN before this one can
Bug#416552: mpd: fails to start with an user error
giggz writes: cannot setgid for user mpd at line 35: Operation not permitted This should be because of the --chuid mpd:audio in /etc/init.d/mpd line 46. Can you remove those arguments and confirm that it works? -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL
Bug#365632: netcat -c doesn't work for outbound connections
Piotr Engelking writes: Package: netcat Version: 1.10-32 Severity: normal For outbound connections, netcat -c is treated as netcat -e. Hi; my apologies for being MIA for a long time. I haved fixed this by removing the extra code from the original -c patch, and reducing the changes to
Bug#407812: should check whether data is waiting instead of just reading
FYI: 0.12.2-2 has some older HTTP fixes from SVN merged, but I have not included the peek code because I can't fix the following issues: - Ogg over HTTP sometimes deadlocks again - All MP3s are reported with a length of 0 when playing; changing this breaks MP3s over HTTP in some way I don't
Bug#412209: German debconf translation lost again?
Helge Kreutzmann writes: Somehow 0.35-1 only contains the Czech and the French translation, no German translation in sight. If there are issues with the German debconf translation please let me know so we can resolve them. Hmm-- it looks like another build problem. I am going to figure out
Bug#311343: poor sound quality when using a fixed sample rate
Guus Sliepen wrote: Upstream has included our patch to support libsamplerate. However, mpd does not Build-Depend on libsamplerate0-dev. Thanks for the update. This will be made explicit in whatever is the next upload. -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL
Bug#387038: Infinite recursion bug
David wrote: Package: python-beautifulsoup Version: 3.0.1-2 Severity: normal If you load this webpage into a BeautifulSoup object: I apologize for not being able to save a copy of this before, but this page has changed and, at least for me, is not
Bug#6439: Bug#6772: These bugs should be closed.
Nathanael Nerode writes: I am closing them now. Maintainer, if you really really want to have three of the oldest ten bugs in Debian, you can reopen them, but I wouldn't if I were you. No, I have no desire to leave these open. I just didn't want to upset anyone who felt it was more
Bug#418954: rxvt-unicode: mouse selection in vim is not visibe when dragging
Leo Moisio writes: On a fresh installation of debian etch, when using vim 7.0-122+1etch2 with set mouse=a and otherwise default settings on rxvt-unicode with default settings, dragging the mouse while holding left mouse button should select an area visually, and hilight the selected area on
Bug#325504: better patch
Here is a revised version of the patch which replaces the bash substitution with a POSIX substitution that will work in both bash and dash. --- glibc.sh.orig 2005-08-29 13:29:42.0 -0400 +++ glibc.sh2005-08-29 13:33:19.0 -0400 @@ -97,7 +97,7 @@ # Note that parisc64
Bug#315488: more info
I ran into this as well. I do not know the correct fix, or if this is really even a bug in beep (could be glib), but removing the G_INLINE_FUNC macro from both function definitions fixes it. -- things change. [EMAIL PROTECTED] -- To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of
Bug#202475: Replace old netcat with GNU netcat?
retitle 202475 RFP: gnu-netcat -- reimplementation of netcat reassign 202475 wnpp thanks Florian Ernst writes: As further eleven months have passed since then, may I ask what your current plans regarding netcat.sf.net are? I apologize for letting this sit, but I have not had time or interest
Bug#322446: rawdog should suggest python2.3-xml or another parser
Michael Scherer writes: Installing rawdog on a system without any python xml packages result in a error : [EMAIL PROTECTED] misc] $ rawdog -u Feed: Error parsing feed. The debugger show the error comes from feedparser.py, when parsing the xml feed.
Bug#322583: uninstallable due to C++ transition
Package: xmms-scrobbler Version: 0.3.8.1-3 Severity: normal xmms-scrobbler needs to be recompiled against libmusicbrainz4c2. Currently, attempting to install it yields: The following packages have unmet dependencies: xmms-scrobbler: Depends: libmusicbrainz4 (= 2.1.1) but it is not installable
Bug#323157: FTBFS: needs build-dep on libselinux-dev
dann frazier writes: gcc -o 9wm -g -O2 -fno-strict-aliasing -L/usr/X11R6/lib main.o event.o manage.o menu.o client.o grab.o cursor.o error.o -lXext -lX11 -lselinux /usr/bin/ld: cannot find -lselinux This was due to to an imake bug, actually. Should be fixed in X.org -5 (I'll let
Bug#317583: whois fails on Dotster-registered domains when WHOIS_HIDE set
Package: whois Version: 4.7.5 Severity: normal In my environment, I have WHOIS_HIDE set to 1 to reduce annoying legal messages from whois. Today I noticed that this causes whois lookups to fail when requesting information from the Dotster (dotster.com) whois servers. I can only assume that | https://www.mail-archive.com/search?l=debian-bugs-dist@lists.debian.org&q=from:%22Decklin+Foster%22 | CC-MAIN-2022-40 | refinedweb | 5,660 | 62.58 |
22 July 2010 07:12 [Source: ICIS news]
SHANGHAI (ICIS news)--China has suspended operations at its southern Guangdong port following forecasts that a tropical storm has intensified into a typhoon and may hit the province on Thursday afternoon, sources said.
Guaongdong province has been put on high alert as typhoon Chanthu was expected to make landfall between the coastal regions of Dianbai and Leishou according to information from ?xml:namespace>
Chanthu, the second storm to hit south China this week, packs a wind speed of about 126 km/hour at its centre, and was moving north-westward at a speed of 15 km/hour, sources said.
More than 28,000 fishing boats had returned to port on 21 July, and 22 flights had been cancelled, they added.
Maoming Petrochemical, which owns two crackers and several related petrochemical plants in the province, would continue normal operations, a source closed to the company said.
“The two crackers, with capacity of 640,000 tonnes/year and 380,000 tonnes/year, are running normally currently, and [there is] no shutdown information for relevant petrochemical plants,” the source. | http://www.icis.com/Articles/2010/07/22/9378329/china-suspends-operations-at-guangdong-port-on-typhoon-warning.html | CC-MAIN-2013-20 | refinedweb | 184 | 50.7 |
Basic questions regarding Obj-C + jitter dev.
Hello
Forgive the basic questions. I am finally trying my hand at some jitter external dev so bare with me:
Are there any examples of using Obj-C with Jitter (or Max) available for me to peruse and wrap my head around? I’ve not been able to find any officially with the SDK, but I may be overlooking something.
Is it within best practices to include an Obj-C/Cocoa Framework within the MXO bundle to keep everything self contained? Will Max/MSP & the mxo respect the @loader_path to load my Obj-C Framework?
Does Max have an NSRunloop (or CFRunloop) equivalent, or do I need to provide my own thread with one in my framework? Some of the Cocoa classes I use in the framework (which I wish to leverage in Jitter) require a main, NSApplication style run loop. So far I have been firing things off to the main run loop which seems to work ok in Cocoa apps where rendering (and thus my framework) happens in a thread sans a run loop (but I know apps like that have main NSRunLoop to fall back on). This is a ‘planning for the future’ sort of a question, and I have no idea about the nuances of Jitter external dev, or deep Max internals.
Now for a *really* basic question. I’ve set my project up using the xcconfig and changed the paths, and set my build target to be based on my xcconfig. I am getting an error when trying to build:
/../c74support/max-includes/ext_proto.h:600:0
/../c74support/max-includes/ext_proto.h:600: error: expected declaration specifiers or ‘…’ before numeric constant
for :
#ifndef WIN_VERSION
int sprintf(char *, const char *, …);
int sscanf(const char *, const char *, …);
#endif //WIN_VERSION
as well as
/../c74support/jit-includes/jit.gl.procs.h:965:0
/../c74support/jit-includes/jit.gl.procs.h:965: error: expected ‘)’ before ‘x’
/../c74support/jit-includes/jit.gl.procs.h:966:0
/../c74support/jit-includes/jit.gl.procs.h:966: error: expected ‘;’ before ‘void’
for
void (APIENTRY *Vertex2hNV) (GLhalfNV x, GLhalfNV y);
void (APIENTRY *Vertex2hvNV) (const GLhalfNV *v);
Im assuming this is a basic oversight for the compilation errors, but Im failing to find it. My project (right now basically a slightly tweaked jit.gl.simple seems to not have syntax or basic errors in the c files).Thanks for any help!
Hey Vade,
The prototypes for sprintf() and sscanf() are in ext_proto.h for ancient historical reasons. I would just comment them out, since they really don’t belong there anymore. Not sure about the Jitter stuff though…
best,
Tim
First, I would recommend sand boxing the Obj-C and the C code, and avoid including any of the max headers in your Obj-C files. Then build C functions which the C part of your code can call into the Obj-C code. This is what we do in jit.gl.imageunit for example.
Second, There’s no easy way to automatically load an Obj-C framework which is not in the standard Library/Frameworks or application bundle locations. You will need to load the framework and link to individual functions dynamically in such a case. A third option, if possible, would just to include all the framework source in your object’s xcode project rather than using an external framework.
We have a CFRunLoop, but to avoid complications I’d recommend designing your code so it can be called explicitly rather than via the run loop if possible. If you encounter specific troubles please let us know.
Unfortunately it seems the run loop issue is ‘required’, since i am using distributed objects (for IPC) and distributed notifications (for announcing availability), and those, best I can tell require a run loop on the thread they are instantiated on. So for now, all I am doing is initting on main thread and releasing on the main thread, everything else happens ‘in place’ wherever its needed. The framework isolates the rest of the Obj-C, so thats ‘done’ per se.
Ill check out the bundle issue when I get there, so I’m sure ill be back. Thanks for the help Tim and JKC :)
Hi, question regarding best practices for OB3D, and objects that just use OpenGL but do not draw.
So, my object in question takes in a texture and does stuff with it, but does not strictly draw it. It does not need a large list of OB3D inherited attributes, like inherit_transform, depth, drawto, capture, blend_mode (etc etc).
I am attempting to ‘opt out’ of the OB3D attributes in my jitter class init method:
// setup our OB3D flags to indicate our capabilities.
long ob3d_flags = JIT_OB3D_NO_MATRIXOUTPUT; // no matrix output
ob3d_flags |= JIT_OB3D_NO_ROTATION_SCALE;
ob3d_flags |= JIT_OB3D_NO_POLY_VARS;
ob3d_flags |= JIT_OB3D_NO_FOG;
ob3d_flags |= JIT_OB3D_NO_MATRIXOUTPUT;
ob3d_flags |= JIT_OB3D_NO_LIGHTING_MATERIAL;
ob3d_flags |= JIT_OB3D_NO_DEPTH;
ob3d_flags |= JIT_OB3D_NO_COLOR;
But it seems there are some I cannot opt out of (see above). What would be the recommended method of handling this?
At the end of the day, what my internal object really needs is access to the jitter context fro the OB3D, and a valid texture id. I plan on eventually being able to handle "jit_matrix" methods and produce my own internal jit_gl_texture object from it to handle internally, but im not there just yet.
Any advice would be appreciated. Thanks!
you pretty much have to live with the attributes not suppressed by the ob3d_flags.
not sure how much of this you already know, but to get the texture id of a texture bound to your object:
// in your draw method t_symbol * tex = jit_attr_getsym(x, gensym("texture")); if(tex && tex != _jit_sym_nothing) { void * texture_ptr = jit_object_findregistered(tex); if(texture_ptr) { const long glid(jit_attr_getlong(texture_ptr, gensym("glid"))); const long gltarget(jit_attr_getlong(texture_ptr, gensym("gltarget"))); ...
Question.
The jit.gl.videoplane example in the SDK does not include a handler for the message jit_gl_texture, but does have a texturename attribute set up, and struc variable, as well as an internal texture (not typed t_jit_obj).
How is it that the jit.gl.videoplane is able to handle jit_gl_texture messages from a jit.gl.texture object? I would like similar functionality, and according to the jit.gl.imageunit sample excerpt that JKC posted elsewhere, handling jit_gl_texture messages is explicitely handled via an addmethod call to jit.gl.imageunit.
jit.gl.videoplane example does handle jit_matrix messages. Does that encapsulate a jit_gl_texture message, or is jit.gl.videoplane example incomplete for brevities sake?
Thanks for any clarification.
Right now my object uses an internal jit.gl.texture object which I create via the same code prototype as the jit.gl.videoplane, but I also seem to have to explicitly handle jit_gl_texture messages via my own method. Im having one odd issue where when I start my object up fresh, I have to send an emtpy ‘texturename’ message in order for it to look at the internal message. I guess Im looking for a way to easily handle both jit.gl.texture and matrix input, and I dont care if I am forced to have an internal jit.gl.texture object within my object, I just want it to work and be sane.
Thanks.
Wait…we can use obj-c in max?
I, too, would greatly appreciate examples.
very interesting indeed!
@vade: a very simple(possibly lame) question: are the QC plug ins made with objective-c?,do you think it would be possible to port some quartz technologies to max by using that language?.
as a kind of request(christmas is far away, i know!): it would be very nice if the developer documentation(java or SDK) could bring some light to the dark corners of max/msp like the use of c++(or objective-c) or implementing special language features(like interfaces on java or OOP with c++).
Emmanuel
efe: If you want QC in Max, check out DIPS. Yes, QC plugins are typically programmed using Obj-C, or Obj-C++.
As for Obj-C in Max, you literally just include cocoa.h, change your object from a .c to a .m, which invokes GCC via XCode to compile as Obj-C, and call Obj-C wherever you want to, keeping in mind you need to create/dispose of NSAutoReleasePool where appropriate. As far as I can tell it pretty much just works.
So, back on topic about the Jitter SDK, how does jit.gl.videoplane example in the SDK download handle messages from jit.gl.texture (aka "jit_gl_texture"? Is this something inherited from OB3D? Why is it that the jit.gl.imageunit code JKC posted explicitly calls ‘addmethod’ for that message?
Thanks.
texture binding and handling of the jit_gl_texture message is handled internally by the ob3d object.
this is the case with jit.gl.videoplane.
however, if the flag JIT_OB3D_IS_SLAB is set, the ob3d will not handle the jit_gl_texture message, and you can handle it yourself in your external. this is the case with jit.gl.imageunit. this allows certain externals to do things like adapt texture dimensions of output textures, from multiple inlets.
unless you are trying to handle streaming textures from multiple inlets, i would think its preferable to let the ob3d handle that message for you.
Hi Rob. Thanks. I had inadvertently set the JIT_OB3D_IS_SLAB mask on my OB3D. Removing it now my object is able to handle jit_gl_texture messages.
If OB3D will handle binding/texture state for me, is there a way I can set the incoming jit_gl_texture message to point to my internal jit.gl.texture object, so I can reference it internally *all the time*, So I dont have to do glGets ont he bound texture? Or do I need to use the ob3d_draw_info struct? It seems like there is no way to introspect the OB3D and query it to return the bound texture, its settings, type, etc. I know I can do that with a texture "i own", something like:
if(jit_gl_syphon_server_instance->texture)
{
// get our latest texture info.
GLuint texname = jit_attr_getlong(jit_gl_syphon_server_instance->texture,ps_glid);
GLuint width = jit_attr_getlong(jit_gl_syphon_server_instance->texture,ps_width);
GLuint height = jit_attr_getlong(jit_gl_syphon_server_instance->texture,ps_height);
//TODO: intuit texture target / 2D vs Rect
BOOL flip = jit_attr_getlong(jit_gl_syphon_server_instance->texture,ps_flip);
// all of these must be > 0
if(texname && width && height)
{
post ("jit.gl.syphonserver: recieved texture object: %i %i %i", texname, width, height);
if(jit_gl_syphon_server_instance->syServer)
{
// These context calls are probably redundant now.
// try and find a context.
t_jit_gl_context jit_ctx = 0;
// jitter context
jit_ctx = jit_gl_get_context();
jit_ob3d_set_context(jit_gl_syphon_server_instance);
if(jit_ctx)
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
// output our frame
[jit_gl_syphon_server_instance->syServer publishFrameTexture:texname
context:CGLGetCurrentContext()
textureTarget:GL_TEXTURE_RECTANGLE_EXT
imageRegion:NSMakeRect(0.0, 0.0, width, height)
textureDimensions:NSMakeSize(width, height)
flipped:flip];
[pool drain];
}
}
}
}
else
{
post("No texture!?");
}
Im assuming that means I would have to manually handle the jit_gl_texture message and do the jitter object call equivalent of patching the external texture into my internal one ? Currently I init my own internal jit.gl.texture object similarly to the videoplane to handle matrix input, and would like to re-use that texture internally wherever I can. Whats odd is, right now, I *can* use my texture, but only if I send a ‘texturename’ message that is empty to my object.
My jit_gl_texture handler looks like:
t_jit_err jit_gl_syphon_server_jit_gl_texture(t_jit_gl_syphon_server *jit_gl_syphon_server_instance, t_symbol *s, int argc, t_atom *argv)
{
post("texture input");
t_jit_object *texture;
t_symbol *name = jit_atom_getsym(argv);
if (name)
{
texture = (t_jit_object*)jit_object_findregistered(name);
if (!texture)
{
post ("jit.gl.imageunit: couldn't get texture object!");
return JIT_ERR_GENERIC;
}
// draw our texture the texture
jit_object_method(jit_gl_syphon_server_instance->texture, s, s, argc, argv);
// add texture to ob3d texture list
jit_attr_setsym(jit_gl_syphon_server_instance,ps_texture,jit_gl_syphon_server_instance->texturename);
}
return JIT_ERR_NONE;
}
Sorry, I’m having major issues with this API, it feels really rather opaque, and seems to dislike me, I must have offended it somehow. I’m happy to send sources off list/forum to someone. Thanks again for all the help
I’m not sure. There are two approaches that may be relevant:
1. handle your own jit_gl_texture messages like the sample code I sent you offlist. Potentially copying them to your internally managed texture if you need to do things like guarantee rectangular textures or format type or whatever. This is probably important if you need complete control over how/when any textures are bound.
2. Ask your object what its texture name is using standard attribute functions and then look up the texture object with jit_object_findregistered.
t_symbol *texsym = object_attr_getsym((t_object *)x,gensym("texture"));
if (texsym&& texsym!=_jit_sym_nothing) {
t_object *texobj = jit_object_findregistered(texsym);
if (texobj) {
// do what you want here
}
}
Hope this helps.
Hi
I’m working with vade on this. I’m new to Max in general and the Jitter API, and still finding my way around. I have a couple of questions already.
I’m stumped by the handling of texturename in the jit.gl.videoplane sample code.
t_jit_err jit_gl_videoplane_texturename(t_jit_gl_videoplane *x, void *attr, long argc, t_atom *argv) { t_symbol *s=jit_atom_getsym(argv); x->texturename = s; if (x->texture) jit_attr_setsym(x->texture,_jit_sym_name,s); jit_attr_setsym(x,ps_texture,s); return JIT_ERR_NONE; }
This sets the name of the internal texture to the name of the referenced texture, then sets ob3d’s ps_texture to that name (and as it works as expected, I presume ob3d looks up the name and finds the referenced texture rather than the same-named internal texture).
Setting the internal texture’s name to that of the referenced texture just seems weird, and that’s backed up by the error that gets posted if you do this in Max – "name xxx already in use. ob3d does not allow multiple bindings". Can someone explain what’s going on here?
My second question is… what happens when you set the ps_texture property? I can’t find reference for ob3d beyond the basics in the SDK docs, which do not cover this. If we handle jit_gl_texture messages ourselves and don’t set ps_texture in the handler, can we still use the texture at draw-time if we bind it ourselves? Right now, whatever we do, we draw black unless we set ps_texture to _jit_sym_nothing *after* rendering has started, with some more weirdnesses thrown in.
Cheers, T
This sets the name of the internal texture to the name of the referenced texture, then sets ob3d’s ps_texture to that name
actually, i think you are slightly mistaken. this message is intended merely to set the name attribute of the internal texture to the argument given. if that name argument is already bound to an existing jitter object, you will get the "name already in use" warning.
the ob3d does not store and manage an internal texture object. it simply stores a t_symbol name reference to an existing texture object. each draw frame, ob3d checks it’s texture attribute and binds the texture before the jitter object’s draw method.
you should be able to handle binding the texture yourself, but i’m not quite sure what your problems are without seeing the code.
this message is intended merely to set the name attribute of the internal texture to the argument given
This seems crazy.
My understanding is that the function of the @texturename attribute is to allow the use of a thus-named texture which exists elsewhere as an input, without the need for a direct connection. I can name a texture elsewhere in my patch Daisy, set the @texturename attribute of another object to Daisy, and have Daisy used as input for that object.
Is that right?
In which case, my point is that setting the name of the internal texture to that passed in is usually going to lead to a naming conflict and the reason for
if (x->texture) jit_attr_setsym(x->texture,_jit_sym_name,s);
remains unclear.
To my mind, a correct version of the above would be
t_jit_err jit_gl_videoplane_texturename(t_jit_gl_videoplane *x, void *attr, long argc, t_atom *argv) { t_symbol *s=jit_atom_getsym(argv); x->texturename = s; jit_attr_setsym(x,ps_texture,s); return JIT_ERR_NONE; }
you should be able to handle binding the texture yourself, but i’m not quite sure what your problems are without seeing the code.
Any pointers to useful documentation or examples beyond those in the SDK for handling textures with ob3d would be fantastic.
This (semi-redundant) attribute exists to rename the internal texture so that it can be used by other objects. It does not exist to reference an external texture (which would result in the error message you describe). For that use the texture message. Make sense?
If you can get us a better example of what you want to do, how you are trying to do it, and what the difficulties you are experiencing, we can offer more assistance. I assume you are simply confusing the texturename attribute with the texture attribute.
Ah, it is crazy, many apologies robtherich for my scepticism.
This (semi-redundant) attribute exists to rename the internal texture so that it can be used by other objects.
Yuck! Right well that’s weird object encapsulation but OK… but then why does the jit.gl.videoplane object then do jit_attr_setsym(x,ps_texture,s) after it has set the name of its internal texture? That is not part of renaming the internal texture so that it can be used by other objects. That is setting the texture attribute… perhaps you can see where my confusion arose? Apologies if I’m just being very slow…
I assume you are simply confusing the texturename attribute with the texture attribute.
Sadly not that simple. Will persevere.
So jit.gl.videoplane has an internal texture, which then is exploited by the standard jit.gl.ob3d infrastructure with the standard texture attribute name. If we rename the internal texture, we need the standard ob3d infrastructure to know what its new name is, so that the texture is bound in the standard setup.
If the jit.gl.videoplane object were doing all the work with texture binding and so forth, this wouldn’t be necessary, but the way it is designed is that *either* an external texture or an internal texture can be used, and all the drawing code works the same–i.e. binds the texture from the texture attribute.
I can’t imagine that this is at all related to your issues, for which you should really be looking at the jit.gl.imageunit examples. jit.gl.videoplane isn’t a texture processor, or a render to texture example. It’s just an example of how to create an internal texture for use on the geometry.
Forums > Dev | https://cycling74.com/forums/topic/basic-questions-regarding-obj-c-jitter-dev/ | CC-MAIN-2015-27 | refinedweb | 3,062 | 62.88 |
On Mon, Jun 1, 2015 at 12:25 PM, u8y7541 The Awesome Person <surya.subbarao1 at gmail.com> wrote: > > I will be presenting a modification to the float class, which will improve its speed and accuracy (reduce floating point errors). This is applicable because Python uses a numerator and denominator rather than a sign and mantissa to represent floats. > > First, I propose that a float's integer ratio should be accurate. For example, (1 / 3).as_integer_ratio() should return (1, 3). Instead, it returns(6004799503160661, 18014398509481984). > I think you're misunderstanding the as_integer_ratio method. That isn't how Python works internally; that's a service provided for parsing out float internals into something more readable. What you _actually_ are working with is IEEE 754 binary64. (Caveat: I have no idea what Python-the-language stipulates, nor what other Python implementations use, but that's what CPython uses, and you did your initial experiments with CPython. None of this discussion applies *at all* if a Python implementation doesn't use IEEE 754.) So internally, 1/3 is stored as: 0 <-- sign bit (positive) 01111111101 <-- exponent (1021) 0101010101010101010101010101010101010101010101010101 <-- mantissa (52 bits, repeating) The exponent is offset by 1023, so this means 1.010101.... divided by 2²; the original repeating value is exactly equal to 4/3, so this is correct, but as soon as it's squeezed into a finite-sized mantissa, it gets rounded - in this case, rounded down. That's where your result comes from. It's been rounded such that it fits inside IEEE 754, and then converted back to a fraction afterwards. You're never going to get an exact result for anything with a denominator that isn't a power of two. Fortunately, Python does offer a solution: store your number as a pair of integers, rather than as a packed floating point value, and all calculations truly will be exact (at the cost of performance): >>> one_third = fractions.Fraction(1, 3) >>> one_eighth = fractions.Fraction(1, 8) >>> one_third + one_eighth Fraction(11, 24) This is possibly more what you want to work with. ChrisA | https://mail.python.org/pipermail/python-ideas/2015-June/033789.html | CC-MAIN-2022-40 | refinedweb | 344 | 64.61 |
Setup PostgreSQL with Sequelize PostgreSQL database with Sequelize as ORM. If you haven’t installed PostgreSQL on your machine yet, head over to this guide on how to install PostgreSQL for your machine. It comes with a MacOS and a Windows setup guide. Afterward come back to the next section of this guide to learn more about using PostgreSQL in Express.
PostgreSQL with Sequelize in Express Installation
To connect PostgreSQL Sequelize as ORM, as it supports multiple dialects, one of which is PostgreSQL. Sequelize provides a comfortable API to work with PostgreSQL databases from setup to execution, but there are many ORMs (e.g. TypeORM, Objection.js) to choose from for a Node.js application if you want to expand your toolbelt.
Before you can implement database usage in your Node.js application, install sequelize and pg, which is the postgres client for Node.js, on the command line for your Node.js application:
npm install pg sequelize --save
After you have installed both libraries:
const user = (sequelize, DataTypes) => { const User = sequelize.define('user', { username: { type: DataTypes.STRING, unique: true, }, }); return User; }; export default user;
As you can see, the user has a username field which is represented as string type. Also we don’t want to have duplicated usernames in our database, hence we add the unique attribute to the field. Next, we may want to associate the user with messages. Since a user can have many messages, we use a 1 to N association:
const user = (sequelize, DataTypes) => { const User = sequelize.define('user', { username: { type: DataTypes.STRING, unique: true, }, }); User.associate = models => { User.hasMany(models.Message); }; return User; }; export default user;:
const user = (sequelize, DataTypes) => { const User = sequelize.define('user', { username: { type: DataTypes.STRING, unique: true, }, }); User.associate = models => { User.hasMany(models.Message); }; User.findByLogin = async login => { let user = await User.findOne({ where: { username: login }, }); if (!user) { user = await User.findOne({ where: { email: login }, }); } return user; }; return User; }; export default user;
The message model looks quite similar, even though we don’t add any custom methods to it and the fields are pretty straightforward with only a text field and another message to user association:
const message = (sequelize, DataTypes) => { const Message = sequelize.define('message', { text: DataTypes.STRING, }); Message.associate = models => { Message.belongsTo(models.User); }; return Message; }; export default message;
Now, in case a user is deleted, we may want to perform a so called cascade delete for all messages in relation to the user. That’s why you can extend schemas with a CASCADE flag. In this case, we add the flag to our user schema to remove all messages of this user on its deletion:
const user = (sequelize, DataTypes) => { const User = sequelize.define('user', { username: { type: DataTypes.STRING, unique: true, }, }); User.associate = models => { User.hasMany(models.Message, { onDelete: 'CASCADE' }); }; User.findByLogin = async login => { let user = await User.findOne({ where: { username: login }, }); if (!user) { user = await User.findOne({ where: { email: login }, }); } return user; }; return User; }; export default user;
Sequelize is used to define the model with its content (composed of
DataTypes and optional configuration). Furthermore, additional methods can be added to shape the database interface and the associate property is used to create relations between models. An user can have multiple messages, but a Message belongs to only one user. You can dive deeper into these concepts in the Sequelize documentation. Next, in your src/models/index.js file, import and combine those models and resolve their associations using the Sequelize API:
import Sequelize from 'sequelize'; const sequelize = new Sequelize( process.env.DATABASE, process.env.DATABASE_USER, process.env.DATABASE_PASSWORD, { dialect: 'postgres', }, ); const models = { User: sequelize.import('./user'), Message: sequelize.import('./message'), }; Object.keys(models).forEach(key => { if ('associate' in models[key]) { models[key].associate(models); } }); export { sequelize }; export default models;
At the top of the file, you create a Sequelize instance by passing mandatory arguments (database name, database superuser, database superuser’s password and additional configuration) to the constructor. For instance, you need to tell Sequelize the dialect of your database, which is postgres rather than mysql or sqlite. In our case, we are using environment variables, but you can pass these arguments as strings in the source code too. For example, the environment variables could look like the following in an .env file:
DATABASE=mydatabase DATABASE_USER=postgres DATABASE_PASSWORD=postgres
Note: If you don’t have a super user or dedicated database for your application yet, head over to the PostgreSQL setup guide to create them. You only have to create a superuser once, but every of your applications should have its own database.
Lastly, use the created Sequelize instance in your Express application. It connects to the database asynchronously and once this is done you can start your Express application.
import express from 'express'; // Express related imports // other node package imports ... import models, { sequelize } from './models'; const app = express(); // additional Express stuff: middleware, routes, ... ... sequelize.sync().then(() => { app.listen(process.env.PORT, () => { console.log(`Example app listening on port ${process.env.PORT}!`), }); });
If you want to re-initialize your database on every Express server start, you can add a condition to your sync method:
... const eraseDatabaseOnSync = true; sequelize.sync({ force: eraseDatabaseOnSync }).then(async () => { PostgreSQL Database?
Last but not least, you may want to seed your PostgreSQL; sequelize.sync({ force: eraseDatabaseOnSync }).then(async () => { if (eraseDatabaseOnSync) { PostgreSQL with Sequelize:
... const createUsersWithMessages = async () => { await models.User.create( { username: 'rwieruch', }, ); };
Each of our user entities has only a username as property. But what about the message(s) for this user? We can create them in one function with the user:
... const createUsersWithMessages = async () => { await models.User.create( { username: 'rwieruch', messages: [ { text: 'Published the Road to learn React', }, ], }, { include: [models.Message], }, ); };
We can say that our user entity should be created with message entities. Since a message has only a text, we can pass these texts as array to the user creation. Each message entity will then be associated to a user with a user identifier. Let’s create a second user, but this time with two messages:
... const createUsersWithMessages = async () => { await models.User.create( { username: 'rwieruch', messages: [ { text: 'Published the Road to learn React', }, ], }, { include: [models.Message], }, ); await models.User.create( { username: 'ddavids', messages: [ { text: 'Happy to release ...', }, { text: 'Published a complete ...', }, ], }, { include: [models.Message], }, ); }; PostgreSQL PostgreSQL in this section yet.
- Explore:
- What else could be used instead of Sequelize as ORM alternative?
- What else could be used instead of PostgreSQL as database alternative?
- Compare your source code with the source code from the MongoDB + Mongoose alternative.
- Ask yourself:
- When would you seed an application in a production ready environment?
- Are ORMs like Sequelize | https://www.robinwieruch.de/postgres-express-setup-tutorial/ | CC-MAIN-2019-35 | refinedweb | 1,093 | 51.75 |
If you've been on any sort of social media this year, you've probably seen people uploading a recent picture of themselves right next to another picture of what they'll look like in 30 years.
This has become possible due to an application called FaceApp, which went viral across the world. Although there have been different attempts at approaching face-aging in the past, they confronted limitations like needing a lot of data, producing ghosting artifacts (not looking natural), and an inability to do the inverted operation, i.e. reverting from old to young. Simply put, the results fell short of our expectations.
With the recent success of GAN-based architectures, we can now generate high-resolution and natural-looking output. In this tutorial we will train CycleGAN, one of today's most interesting architectures, to do forward aging from 20s to 50s and reverse aging from 50s to 20s. Let's get started.
Bring this project to life
Generative Algorithms
If you've ever trained a neural network such as a simple classification network, you probably trained a discriminative network whose only task is to differentiate between classes (like a dogs vs. cats classifier). Popular neural network architectures such as VGG and Resnet fall under this category.
Generative algorithms, on the other hand, are an interesting set of algorithms which can do much more than a simple classification task. They can generate data which looks similar to the domain on which the model was trained. For example, if the model is trained on pictures of horses, a generative algorithm can create new horses which look real yet different from the training examples. Think of this like how humans can imagine anything in the world, just by closing their eyes and thinking about it.
How GANs Work
Generative Adversarial Networks (GANs) are one of the most popular generative algorithms. They have many interesting applications (some of which are explored here). A GAN consists of two neural networks: a generator and a discriminator. The task of the generator network is to create realistic images, while the discriminator network must differentiate between real images and the fake ones created by the generator.
Both the generator and discriminator compete with each other in a minimax game until a stage comes when the generator creates images so realistic that the discriminator cannot determine which image is real, and which is artificially generated. At this stage equilibrium is reached, and the training is stopped.
Both networks are trained simultaneously until reaching equilibrium. Since both networks compete with one another and try to better themselves on every iteration, the loss won't decrease continuously like in a general classification network. We'll discuss how to monitor the network's performance below.
There are many new architectures being developed constantly to achieve different use cases, the popular ones being DCGAN, StyleGAN, CGAN, BigGAN, etc. For the case of face aging, we are interested in one particular architecture which specializes in domain transfer, known as CycleGAN. It can take an image from one domain (for example, a horse) and can convert it to another domain (like a zebra), while keeping the features of the input domain (i.e. looking similar to the input horse).
How CycleGAN Is Different
CycleGAN is a variant of the general GAN architecture we discussed above, with the difference being that it has two generator and discriminator pairs. It was developed to solve the problem of requiring a huge number of images when trying to translate from one domain to another. For example, if we want a general GAN to modify a horse image to look like a zebra, it would need a lot of labelled horse images and the corresponding similar zebra images. This kind of data collection is not only cumbersome, it's almost impossible since you cannot always obtain paired images across different domains.
CycleGAN solves the problem of needing a data set of labelled images from both domains. It does this by proposing a simple yet clever trick. Instead of having a single network for converting from horse to zebra, it has two networks: one which converts from horse to zebra, and another which converts from zebra to horse. This is demonstrated in the figure below.
Consider the two generator-discriminator pairs as G1-D1 and G2-D2. G1 takes the input horse image and converts it into an image which should look like a zebra. The task of D1 is then to consider whether the image from G1 is a real zebra, or a generated zebra from the generator network. The generated image from G1 is now passed to generator G2. The task of G2 is to convert the generated zebra image to a horse-like image. So we are taking a horse, converting it to zebra with G1, and then converting it back to a horse with G2. The task of D2 is then to discriminate the image from G2 as a real horse, or a generated one.
Now the network is trained using multiple losses. We use the losses of the two generator-discriminator pairs, just like a general GAN, but we also add a cyclic loss. This loss is used when the image is cycled back after passing through both generators; the final image should look like the original input image (i.e. when going from Horse → Zebra → Horse, the final horse should look like the original horse). The need for this cyclic loss comes from our requirement that the image translated from one domain to another should retain the distinguishing features from the original domain.
If a zebra is generated from a horse using CycleGAN, it should not only look like a zebra, but should also give the same feel as the original horse which was modified to look like a zebra.
Now we can see that there is no need for a labelled data set to map each horse to a corresponding similar-looking zebra. We just need to provide a set of horse images and a set of zebra images, and the network will learn by itself how to do the translation. Since the domain transfer is bi-directional, we can also convert these zebra images back to horse images with the second generator, G2.
Using CycleGAN to Alter Faces
With this theory in mind let's dive into building the application. By looking at the architecture discussed above, we should have an idea of how we'll approach this problem. We'll take a set of face images from people in their 20s-30s, and another set from people in their 50s-60s. We will then use CycleGAN to do the domain transfer to convert a 20-year-old to a 50-year-old, and vice versa.
For the full notebook, please refer to the GitHub repository CycleGAN for Age Conversion.
We'll use the UTKFace data set, which contains over 20,000 face images of people of various races and genders, ranging from 0 to 116 years old. Since we are only concerned about people in their 20s-30s and 50s-60s, we'll filter the images and remove those falling in other age groups.
We'll use the CycleGAN Keras base code, and modify it to suit our use case. The discriminator is a simple network with 4 convolutional layers, each of stride 2, and a final aggregation convolutional layer. So if we provide an input image of size (256 x 256), we will get an output of (16 x 16). This incorporates one of the suggestions proposed by Pix2Pix, namely the PatchGAN discriminator. The output of PatchGAN maps to a patch of the input image, discriminating whether or not that patch of the input image is real or fake. The expected output would be (16 x 16) matrix of numbers with each number equal to 1 in the case that the image is determined to be real, and 0 if it is determined to be artificially generated.
This is more advantageous since now instead of classifying the entire image as one class, we are classifying multiple patches of the image as belonging to the same class or not. Hence we are providing more signal/gradient/information during training, and can produce sharper features as compared to using a softmax output for the entire image.
def build_discriminator(self): def d_layer(layer_input, filters, f_size=4, normalization=True): """Discriminator layer""" d = Conv2D(filters, kernel_size=f_size, strides=2, padding='same')(layer_input) d = LeakyReLU(alpha=0.2)(d) if normalization: d = InstanceNormalization()(d) return d img = Input(shape=self.img_shape) d1 = d_layer(img, self.df, normalization=False) d2 = d_layer(d1, self.df*2) d3 = d_layer(d2, self.df*4) d4 = d_layer(d3, self.df*8) validity = Conv2D(1, kernel_size=4, strides=1, padding='same')(d4) return Model(img, validity)
The code which we have taken from Keras GAN repo uses a U-Net style generator, but it needs to be modified. We're going to use a ResNet-style generator since it gave better results for this use case after experimentation. The input to the generator is an image of size (256 x 256), and in this scenario it's the face of a person in their 20s.
The image is downsampled by 4 times (i.e to 64 x 64) by passing through 2 convolutional layers of stride 2, followed by 9 residual blocks which preserve the size. Then we upsample back to the original size of (256 x 256) by performing transposed convolution. The final output we get should be a transformed image of the same person, now looking as if they were in their 50s.
# Resnet style generator c0 = Input(shape=self.img_shape) c1 = conv2d(c0, filters=self.gf, strides=1, name="g_e1", f_size=7) c2 = conv2d(c1, filters=self.gf*2, strides=2, name="g_e2", f_size=3) c3 = conv2d(c2, filters=self.gf*4, strides=2, name="g_e3", f_size=3) r1 = residual(c3, filters=self.gf*4, name='g_r1') r2 = residual(r1, self.gf*4, name='g_r2') r3 = residual(r2, self.gf*4, name='g_r3') r4 = residual(r3, self.gf*4, name='g_r4') r5 = residual(r4, self.gf*4, name='g_r5') r6 = residual(r5, self.gf*4, name='g_r6') r7 = residual(r6, self.gf*4, name='g_r7') r8 = residual(r7, self.gf*4, name='g_r8') r9 = residual(r8, self.gf*4, name='g_r9') d1 = conv2d_transpose(r9, filters=self.gf*2, f_size=3, strides=2, name='g_d1_dc') d2 = conv2d_transpose(d1, filters=self.gf, f_size=3, strides=2, name='g_d2_dc') output_img = Conv2D(self.channels, kernel_size=7, strides=1, padding='same', activation='tanh')(d2)
We will have two such pairs of generator and discriminator: one for forward aging, and one for backward aging.
The Loss Function
We've finally arrived to the loss function. The discriminator loss is the mean square error of the patch that we discussed above. The generator loss will be the negative of the discriminator loss, since the generator tries to maximize discriminator error.
As mentioned previously, with CycleGAN we have the addition of the cyclic loss. We take the mean square error between the original image and the recycled image as the loss term.
A generator which does age conversion from 20s to 50s shouldn't change/convert an image, if an image of age 50 is provided as input. Since the input is already of the desired age, the network should act as identity in this case.
Of course, if the input image is already of the desired age, the network should know to return that image as the output without any modifications. To make sure the network behaves this way, an identity loss is added to the loss function. This is again the mean square difference between output image and input image. Both the forward and backward generators have this additional loss term.
In summary, we have the general generator and discriminator losses just like a conventional GAN. In addition, we have the cyclic loss for matching the input when converted from domain A to B, and then back to domain A. We also have the identity losses to ensure that the network does not change the input if it's already of the proper domain (in this case, age).
\\Loss = discriminative_loss + Λ1 * cyclic_loss + Λ2 * identity_loss\\
Here Λ1, Λ2 are hyperparameters
valid = np.ones((batch_size,) + self.disc_patch) fake = np.zeros((batch_size,) + self.disc_patch) fake_B = self.g_AB.predict(imgs_A) fake_A = self.g_BA.predict(imgs_B) dA_loss_real = self.d_A.train_on_batch(imgs_A, valid) dA_loss_fake = self.d_A.train_on_batch(fake_A, fake) dA_loss = 0.5 * np.add(dA_loss_real, dA_loss_fake) dB_loss_real = self.d_B.train_on_batch(imgs_B, valid) dB_loss_fake = self.d_B.train_on_batch(fake_B, fake) dB_loss = 0.5 * np.add(dB_loss_real, dB_loss_fake) # Total disciminator loss d_loss = 0.5 * np.add(dA_loss, dB_loss) g_loss = self.combined.train_on_batch([imgs_A, imgs_B], [valid, valid, imgs_A, imgs_B, imgs_A, imgs_B])
We take a batch of pair of images from age 20's(Image A) and age 50's(Image B) while training. Generator g_AB converts age 20 to age 50, discriminator d_A classifies it as real or generated image. g_BA and d_B do similar work for age 50 to age 20 conversion. Image A is passed to g_AB and reconstructed via g_BA and vice-versa for Image B.
We train the combined model of discriminator and generator together and try to reduce all the 3 losses i.e discriminative loss, cyclic loss and identity loss at the same time.
Hacks to Stabilize Training
- Follow advice from Jeremy Howard and use progressive resizing while training. I couldn't stress more on the importance of this. When I started out training with size 256 × 256 I had to use batch size 1 since otherwise my GPU would die. It took a lot of time to see the results and believe me you need to tinker a lot. If you wait hours for every experiment it would take ages. So start with a smaller size say 64 × 64 and gradually increase the input image size. This helped me to run at batch size 32 (32 times faster). This trick works since initial feature layers of network learns the same concepts irrespective of image size.
- Keep a close tab on each of discriminator, generator, cyclic , identity loss. If one loss is dominating other, try to play around with the coefficients Λ1, Λ2. Otherwise model might concentrate on optimizing one loss at the expense of other. For example if cyclic loss dominates then the cyclic image looks same as input image but the generated image wouldn't be as we desired i.e age progression might not have happened since the network kept more focus on cyclic loss.
Debugging
Unlike a traditional classification task one can't say the performance of the network by looking at the loss and stating the model has improved if the loss went down since in GAN the loss wouldn't always decrease. There is discriminator which is trying to reduce the loss and then generator which works opposite and tries to increase the discriminator loss and hence the loss goes in a topsy-turvy path.
But then how do we know the networks are getting trained ? We do this by observing the output of the generators over the course of the training. At every few iterations sample few images and pass it through generator to see what results are being produced. If you feel that the results doesn't look appealing or if you feel only loss is getting optimised, you can try tinkering few parts, fix it and restart training again.
Also this way of looking at output and inspecting it is much more rewarding and addictive than looking at a plain number in a classification task. When I was developing the application I couldn't stop waiting for every few iterations to complete so that I can see the output getting generated all the while cheering for the generator to win(Sorry discriminator).
After training for around 50 epochs by using the above techniques and hacks, the results look like below which is pretty decent
Usage in real-world
As you can see above the images used for training are perfectly captured headshots but in real-world it might not always be possible to get such images to use our Cyclegan for face-aging. We need to be able to find where a face is present in an image and modify that part of the image.
For this we will run a face detector before passing the image to cyclegan. The face detector gives bounding boxes of the various faces in an image. We will then write a script to take crops of those boxes to send it to our network. We will then take the outputs to place it back on the input image. This way we can deal with any image from real world
For this we will be using opencv face-detector from here which is based on resnet-ssd architecture.
def detectFaceOpenCVDnn(net, frame, ctype): frameOpencvDnn = frame.copy() frameHeight = frameOpencvDnn.shape[0] frameWidth = frameOpencvDnn.shape[1] blob = cv2.dnn.blobFromImage(frameOpencvDnn, 1.0, (frameHeight, frameW]) if not(x1<30 or y1<30 or x2>frameWidth-30 or y2>frameHeight-30): y1, y2 = y1-20, y2+20 x1, x2 = x1-20, x2+20 else: continue crop_img = frameOpencvDnn[y1:y2, x1:x2] crop_img = cv2.cvtColor(crop_img, cv2.COLOR_BGR2RGB).astype("float32") cv2.imwrite("cropped"+str(i)+".jpg", crop_img) inp = np.array([gan.data_loader.get_img(crop_img)]) case1 = np.ones(gan.condition_shape) case2 = np.zeros(gan.condition_shape) if ctype==0: case = case1 else: case = case2 case1stack = np.array([case]*1) old_img = gan.g_AB.predict([inp, case1stack]) new_img = revert_img(old_img[0], (y2-y1, x2-x1)) new_img = cv2.cvtColor(new_img, cv2.COLOR_RGB2BGR).astype("float32") frameOpencvDnn[y1:y2, x1:x2] = new_img scipy.misc.imsave("old"+str(i)+".jpg", new_img) return frameOpencvDnn, bboxes conf_threshold = 0.8 modelFile = "opencv_face_detector_uint8.pb" configFile = "opencv_face_detector.pbtxt" net = cv2.dnn.readNetFromTensorflow(modelFile, configFile) frame = cv2.imread("big3.jpg") outOpencvDnn, bboxes = detectFaceOpenCVDnn(net,frame,0) cv2.imwrite("big3_old.jpg", outOpencvDnn) outOpencvDnn, bboxes = detectFaceOpenCVDnn(net,frame,1) cv2.imwrite("big3_black.jpg", outOpencvDnn)
Original Image
Age converted
As we can see the results are pretty decent for the limited data and image size we trained on. Also the image from above looks much different from the data the model is trained on but still the model works pretty decent, hence the model isn't overfitting. The results can further be improved by training the network on bigger images(UTKFace is 256x256) and on more real-world images like above and then we will have a production-ready Faceapp like application.
Summary
We have gone through what is a GAN and how we can use a variant CycleGAN to build an application like FaceApp. Similarly we discussed few hacks to stabilize the training. We devised an experiement to make the generator capable enough to perform multiple tasks.
Where to go from here ?. We can experiment more on the conditional part to try and see if we can achieve things like performing multiple tasks at the same time, try and see how the generator behaves with different conditional input. There is a lot of scope for experimentation and improvement.
Also you can have a look at this where similar results are achieved by using a variant of Variational AutoEncoder (another popular Generative Algorithm).
Add speed and simplicity to your Machine Learning workflow today | https://blog.paperspace.com/use-cyclegan-age-conversion-keras-python/ | CC-MAIN-2022-21 | refinedweb | 3,220 | 55.64 |
Access MATLAB Functions and Workspace Data in C Charts
State.
In charts that use C as the action language, you can call built-in MATLAB functions and access MATLAB workspace variables by using the
ml namespace operator or the
ml function.
Caution
Because MATLAB functions are not available in a target environment, do not use the
ml namespace operator and the
ml function if you
plan to build a code generation target.
ml Namespace.function_name(arg1,arg2,...)
For example, the statement
[a, b, c] =
ml. passes the return values from the
MATLAB function
function(x, y)
function.
Examples
In these examples,
x,
y, and
z are workspace variables and
d1 and
d2 are Stateflow data:
a = ml.sin(ml.x)
In this example, the MATLAB function
sinevaluates the sine of
x, which is then assigned to Stateflow data variable
a. However, because
xis a workspace variable, you must use the namespace operator to access it. Hence,
ml.xis used instead of just
x.
a = ml.sin(d1)
In this example, the MATLAB function
sinevaluates the sine of
d1, which is assigned to Stateflow data variable
a. Because
d1is Stateflow data, you can access it directly.
ml.x = d1*d2/ml.y
The result of the expression is assigned to
x. If
xdoes not exist prior to simulation, it is automatically created in the MATLAB workspace.
ml.v[5][6][7] = ml.f(ml.x[1][3],ml.y[3])
The workspace variables
xand
yare arrays.
x[1][3]is the
(1,3)element of the two-dimensional array variable
x.
y[3]is the third element of the one-dimensional array variable
y
The value returned by the call to
fis assigned to element
(5,6,7)of the workspace array,
v. If
vdoes not exist prior to simulation, it is automatically created in the MATLAB workspace.
ml Function.
Examples
In these examples,
x is a MATLAB workspace variable, and
d1 and
d2 are
Stateflow data:
a = ml("sin(x)")
In this example, the
mlfunction calls the MATLAB function
sinto evaluate the sine of
xin the MATLAB workspace. The result is then assigned to Stateflow data object
a. Because
xis a workspace variable, and
sin(x)is evaluated in the MATLAB workspace, you enter it directly as the string
"sin(x)".
sfmat_44 = ml("rand(4)")
In this example, a square 4-by-4 matrix of random numbers between 0 and 1 is returned and assigned to the Stateflow data object
sf_mat44. you must define this data object as a 4-by-4 array before simulation. Otherwise, a size mismatch error occurs during run-time.
a = ml("sin(%f)",d1)
In this example, the MATLAB function
sinevaluates the sine of
d1in the MATLAB workspace and assigns the result to Stateflow data object
a. Because
d1is Stateflow data, its value is inserted in the string argument
"sin(%f)"using the format expression
%f. If
d1= 1.5, the expression evaluated in the MATLAB workspace is
sin(1.5).
a = ml("f(%g,x,%f)",d1,d2)
In this example, the expression is the
shown in the preceding format statement. Stateflow data
evalString
d1and
d2are inserted into the expression
"by using the format specifiers
f(%g,x,%f)"
%gand
%f, respectively.
ml Expressions
For C charts, you can mix
ml namespace operator and
ml function expressions along with Stateflow data in larger expressions. The following example squares the
sine and
cosine of an angle in workspace variable
X and adds them:
a = when you
update or simulate the model. Because the return values for
ml
expressions are not known until run time, Stateflow software must infer the size of their return values. See How Charts Infer the Return Size for ml Expressions.
Which
ml Should I Use?
In most cases, the notation of the
ml namespace operator is more
straightforward. However, using the
ml function call does offer a few
advantages:
Use the
mlfunction to dynamically construct workspace variables.
The following flow chart creates four new MATLAB matrices:
The
forloop creates four new matrix variables in the MATLAB workspace. The default transition initializes the Stateflow counter
ito 0, while the transition segment between the top two junctions increments it by 1. If
iis less than 5, the transition segment back to the top junction evaluates the
mlfunction call
ml("A%d = rand(%d)",i,i)for the current value of
i. When
i
mlfunction with full MATLAB notation.
You cannot use full MATLAB notation with the
mlnamespace operator, as the following example shows:
ml.A = ml.magic(4); B = ml("A + A'");
This example sets the workspace variable
Ato a magic 4-by-4 matrix using the
mlnamespace operator. Stateflow data
Bis then set to the addition of
Aand its transpose matrix,
A', which produces a symmetric matrix. Because the
mlnamespace operator cannot evaluate the expression
A', the
mlfunction is used instead. However, you can call the MATLAB function
transposewith the
mlnamespace operator in the following equivalent expression:
ml.A = ml.magic(4); B = ml.A + ml.transpose(ml.A)
As another example, you cannot use arguments with cell arrays or subscript expressions involving colons with the
mlnamespace operator. However, these can be included in an
mlfunction call.
ml Data.
Rules for Using
ml Data Type
These rules apply to Stateflow data of type
ml:
You can initialize
mldata from the MATLAB workspace just like other data in the Stateflow hierarchy (see Initialize Data from the MATLAB Base Workspace).
Any numerical scalar or array of
mldata in the Stateflow hierarchy can participate in any kind of unary operation and any kind of binary operation with any other data in the hierarchy.
If
mldata participates in any numerical operation with other data, the size of the
mldata must be inferred from the context in which it is used, just as return data from the
mlnamespace operator and
mlfunction are. See How Charts Infer the Return Size for ml Expressions.
You cannot define
mldata with the scope Constant.
This option is disabled in the Data properties dialog box and in the Model Explorer for Stateflow data of type
ml.
You can use
mldata to build a simulation target but not to build an embeddable code generation target.
If data of type
mlcontainsis a Stateflow data of type
ml,
ws_num_arrayis a 2-by-2 MATLAB workspace array with numerical values, and
ws_str_array*/
mldata cannot have a scope outside a C chart; that is, you cannot define the scope of
mldata as Input from Simulink or Output to Simulink.
Place Holder for Workspace Data.
How Charts Infer the Return Size for
ml Expressionsnamespace operator or the
mlfunctionis a MATLAB workspace variable of any size and type (structure, cell array, character vector, and so on).
An assignment in which the left-hand side is a data of type
ml
For example, in the expression
m_x = ml.,
func()
m_xis a Stateflow data of type
ml.
Input arguments of a MATLAB function
For example, in the expression
ml.,
func(m_x, ml.x,
gfunc())
m_xis a Stateflow data of type
ml,
ml.x
mlin its prototype statement
Note
If you replace the inputs in the preceding cases with non-MATLAB numeric Stateflow data, conversion to an
mltype occurs. | https://fr.mathworks.com/help/stateflow/ug/calling-built-in-matlab-functions-and-accessing-workspace-data.html | CC-MAIN-2022-33 | refinedweb | 1,197 | 53.71 |
Details
- Type:
Bug
- Status:
Closed
- Priority:
Major
- Resolution: Fixed
- Affects Version/s: JRuby 1.6RC1
- Fix Version/s: JRuby 1.6RC2
- Component/s: None
- Labels:None
- Number of attachments :
Description
For example, the output of `ruby --profile.graph -rubygems -e'require "bundler"'`
Note the entries for 'Date.new!' and 'Gem.searcher', and the definition of Gem.searcher:
def self.searcher MUTEX.synchronize do @searcher ||= Gem::GemPathSearcher.new end end
It seems clear that where 'Date.new!' appears in the profile output, it should actually be 'Gem::GemPathSearcher.new'.
Activity
Ok, this might be tricky to fix, but it would be nice. I think what we need to do is expand the profile gathering to consider both the target class's ID and the method serial number. The issue is something like this:
Given the following code
class Foo def something; end end class Bar < Foo; end class Baz < Foo; end
calls to Bar#something or Baz#something will show up in profiles as always being Foo#something. In this case, it's not as misleading, but in the case of core methods inherited by user-created classes, it can be very strange.
Consider, for example, the following:
~/projects/jruby ➔ jruby --profile -e "class Foo; end; class Bar; end; 10000.times { Foo.new; Bar.new }" Total time: 0.03 total self children calls method ---------------------------------------------------------------- 0.03 0.02 0.01 1 Fixnum#times 0.01 0.01 0.00 20000 Class#new 0.00 0.00 0.00 20000 Object#initialize 0.00 0.00 0.00 147 Class#inherited
Here, there are two different classes' objects being constructed: Foo and Bar instances. But they both use the default "new" implementation from JRuby, which results in only that method class+name showing up in profiles.
Now this may actually be appropriate, if sometimes confusing. It's most tricky in the case of class methods like "new", since they're almost always shared across many different classes. But there's really only one method, and so profiles showing different methods could also be misleading.
It also occurs to me as I write this that we may be unconditionally redefining the class+name for a given method, which causes Date.new! to get used for several other "new" calls. I'll look into that now as well.
Ok, as neat as it might be to see the actual class against which a method is being called, I've decided that's out of scope for this bug.
In the original case, the method being called is actually the default "new", indicated by Class#new normally. Because Date aliased that new to new!, it took over the serial number we use to identify that unique method, and all subsequent calls to the default new showed up as Date::new!.
I made a minor modification to the name-gathering part of profiling to only use the first name encountered for a given serial number, since subsequent uses of the same serial number are all still the same method body. With this change, profiles are now making a lot more sense, and the Date.new! that was reported as a problem shows up properly as Class#new.
commit 04ce8b7d9d93135fcf274389be392875a5b2d8cb
Author: Charles Oliver Nutter <headius@headius.com>
Date: Tue Jan 25 18:19:09 2011 -0600
Fix
JRUBY-5356: --profile.graph sometimes shows wrong methods
- Only use the first name encountered for a given method serial, since aliases/etc will re-use them.
I think the problem here is that the the new! method for Date and the new method for GemPathSearcher are resolving to the same actual method object in-memory in JRuby. As a result, we go with the first one defined, and report all future results with that method's name.
Looking into it. | http://jira.codehaus.org/browse/JRUBY-5356?focusedCommentId=252888&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel | CC-MAIN-2013-20 | refinedweb | 630 | 66.03 |
Portable Global JNDI names
By Mahesh Kannan on Dec 11, 2009
The introduction of dependency injection in JavaEE5 did reduce the need for doing a JNDI lookup. However, there are times when the users / clients had to rely on the good old JNDI lookup to acquire EJB references. Typical examples of such clients performing lookup of EJBs include (a) a JavaEE component from a different application and (b) a Java SE client.
The problem was such clients had to use “global” jndi name to lookup the target bean. All along the ejb specifications had been silent about portability of such global jndi names. This allowed each vendor to assign a global jndi names to EJBs in a vendor specific way. This meant that the client code that performed a lookup using global JNDI names were inherently non portable across appserver vendor implementations.
For example, the following code (part of a non JavaEE client) assumes that FooBean has been mapped to the global jndi name: "_app1_mod1_FooBean"
This code might break if the target bean was deployed to a different JavaEE server.
Portable Global JNDI name in EJB 3.1EJB 3.1 solves the above problem by mandating that every container must assign (at least one) well defined global JNDI names to EJBs.
The general syntax of a (portable) global JNDI name of an EJB is of the form:
java:global/[<application-name>]/<module-name>/<bean-name>!<fully-qualified-bean-interface-name>
In addition to the above name, if the EJB exposes just a single client view (that is it implements just one interface or the no interface view), the container is also mandated to map the bean to
java:global/[<application-name>]/<module-name>/<bean-name>
Where
- <aplication-name> defaults to the bundle name (.ear file name) without the bundle extension. This can be overridden in application.xml. Also, <application-name> is applicable only if the bean is packaged inside a .ear file.
- <module-name> defaults to bundle name (.war or .jar) without the bundle extension. Again, this can be overridden in ejb-jar.xml.
- <bean-name> defaults to the unqualified class name of the bean. However, if @Stateful or @Stateless or @Singleton uses the name attribute, then the value specified there will be used as the bean name.
Example 1:
Assuming
that the following classes and interfaces are packaged inside hello.jar
and
deployed as a stand alone module
The
following portable jndi names are then made available by the
container to the clients:
Note:
- Since MyEJB implements more than one interface, the global jndi names must include the implemented interface
- For HelloBean, the value specified in the name() attribute is used as <bean-name>
- Since HelloBean bean exposes a no interface view, the qualified bean class name is used as <fully-qualified-bean-intf-name>
- Since ShoppingCart bean exposes a no interface view, the qualified bean class name is used as <fully-qualified-bean-intf-name>
- Since, the application is deployed as a standalone module, <app-name> is not used in the global jndi name.
Client code:
You can also use the portable jndi names in injection too
More name spaces
In
addition to the java:global namespace, the container is also required
to make the bean(s) available under two other name spaces:
java:app and java:module
Why do we need these two? In the case of java:global, the name contains a hard coded <app-name> and (or) <module-name>. Assuming, that <app-name> and <module-name> are not specified in .xml, re-packaging the bean and client into a different module breaks the client. For example, if FooBean was originally packaged inside foo.jar, the client that looked up using ic.lookup("java:global/foo/FooBean") will break if FooBean is re-packaged inside module2.jar
Since, most of the time the beans and the clients are colocated in the same application or even within the same module, EJB 3.1 allows accessing these colocated beans in a easier way. The spec defines two more name spaces called java:app and java:module.
java:module allows a component executing within a Java EE application to access a namespace
rooted below the <module-name> portion of the namespace corresponding to its module.
You can think of java:module as the jndi sub-context that is rooted under the "current module" in which the client is located. java:module differs from java:global in the sense that the client can access only those beans that are packaged inside the same module as the client. If a component in module1 has to lookup a component in module2, then it has to use java:global (or java:app).
Similarly, can think of java:app as the jndi sub-context that is rooted under the "current app" in which the client is located.
The java:app and java:module names are of the form:
java:app/<module-name>/<bean-name>!<fully-qualified-intf-name>
and
java:module/<bean-name>!<fully-qualified-intf-name>
In our example, the Util class can access other components as follows:
Running the sample application
- Save and unzip portable-jndi-app.zip
- cd portable-jndi-name
- mvn install will build the application. The .war file will be under target directory
- <v3-install-dir>/bin/asadmin deploy --force=true target/portable-jndi-app.war
- Open a browser and access localhost:8080/webejb/Example1Servlet
Also, I have used mvn as the build / packing tool.
References
[1] EJB 3.1 Specification
[2] Ken Saks' note on portable jndi name | https://blogs.oracle.com/MaheshKannan/tags/java%3Aglobal | CC-MAIN-2015-22 | refinedweb | 920 | 53.1 |
.
Since Ext JS 5.0.1, we've been hard at work adding exciting new features and responding to all the great feedback from the Sencha Community. Ext JS 5.1 comes with an entirely new selection mode for our grids (the spreadsheet model), along with other new components, and enhancements including:
You can get started with Ext JS 5.1 by visiting the product page.
For information about updating to Ext JS 5.1, please read our Ext JS Upgrade Guide.
Now let's take a look as some of the new features in Ext JS 5.1!
Note: Ext JS 5.1 does require the newest version of Sencha Cmd, which is Sencha Cmd 5.1.
The Ext JS Grid has always been the centerpiece of the framework. With Ext JS 5.1, we're adding a brand new selection model that mimics the experience of a spreadsheet. The spreadsheet model. Using this model, users can select cell ranges as seen below.
Users may also select cell ranges as entire columns, rows or the entire data set.
You can even enable row check-boxes such that spreadsheet may be the only selection model you'll ever need.
When using the spreadsheet selection model, you can also add the new clipboard plugin. This plugin enables exchange between your grid and other applications running outside the browser. Users can select a range of data, then press CTRL+C (or Command+C on Mac) to copy those cells to the system clipboard. Users may then switch to an application such as Microsoft Excel and paste their data.
Of course, the reverse also works. Users can copy data to the clipboard in an external application and then select the target cell in the grid and press CTRL+V (or Command+V on Mac) to paste.
All of this functionality can be added to a grid like so:
requires: [ 'Ext.grid.selection.SpreadsheetModel', 'Ext.grid.plugin.Clipboard' ], selModel: { type: 'spreadsheet', columnSelect: true // replaces click-to-sort on header }, plugins: 'clipboard'
By default, the clipboard plugin uses your system clipboard. However, you may also use an internal buffer to exchange custom data formats between grids within your application.
The sencha-charts package now provides a "bar3d" series and a "numeric3d" axis. These new additions combine to produce some beautiful results like the following stacked column chart.
By providing a custom renderer method, you can simply adjust the fillStyle of a column and still get all the proper gradients to maintain the 3D appearance:
And let's not forget bar charts:
Stacked charts have two new configs in addition to 3D support:
These configs allow the chart to have any data in the store and instruct the series to dynamically scale the data at display time to fit a specified range (typically 0% to 100%).
To enable full stacking, just set the series fullStack config to true. By default, all y fields of the series are stacked with a total of 100, to represent percentages. Using fullStackTotal, you can, however, scale the axis to any range.
Finally, with charts, you can now wire up item-level events such as itemtap and itemmousemove by adding the new "chartitemevents" plugin to your chart.
You may recall the color picker component we introduced in a previous article:
Now, there are actually three color picker components. The above example shows the colorfield and colorselector. The colorfield component is the form field that displays the color value and a sample swatch. The colorselector is presented in the popup window.
The third color picker is the colorbutton which is just the color swatch that reacts to clicks to display a colorselector.
These components are part of the Ext.ux namespace and now live in the framework's "ext-ux" package. More on "ext-ux" package below..
One of the frequently requested features for Direct subsystem was support for
passing metadata with CRUD operations in a Proxy. Previously this was implemented
only for Read operations using
extraParams property on the Proxy; unfortunately
that approach made it near impossible to support CUD operations as well.
Starting with Ext JS 5.1, any Direct method invocation can be supplied with metadata
that will be passed to the server side separately from method arguments. This
feature is immediately available with Direct proxy as well via the new
metadata
property that can be used instead of
extraParams with full range of CRUD operations.
Previously the only pattern available to use with Direct Remoting providers was to include a link to the Provider's API declaration in application's HTML boilerplate and create a Provider instance manually. That approach was often cumbersome, prone to race conditions, and hard to fit in an application built to MVC standards.
The new
loadProvider method of the
Ext.direct.Manager singleton helps to make
using Direct providers easier by handling the complexity behind the scenes.
The old Direct examples have been moved to KitchenSink to showcase Direct enabled MVC application and new features described above.
In previous versions of the framework, the Ext.ux namespace was developed in the "examples/ux" folder. This has always been a challenge for theme interaction, so with Ext JS 5.1 we have added an "ext-ux" package to contain these components. Over time, the existing members of Ext.ux will either be migrated to "ext-ux" or promoted to the framework proper.
To use "ext-ux" package in a Sencha Cmd application, you simple add it to your app.json file:
"requires": [ "ext-ux" ]
As a standard package, the ext-ux build outputs are available to those not using Sencha Cmd as well. The "build" folder looks like this:
The JavaScript files "ext-ux.js" and "ext-ux-debug.js" are in the top-level build folder. Based on your application's theme, you would then select from the three theme subfolders with compiled CSS and resources.
The Ext.draw package in "sencha-charts" also has some exciting new features for those going beyond simple charts.
You can now process sprite events such as itemtap or itemmouseover by adding the "spriteevents" plugin to the Ext.draw.Container.
We've added new APIs to allow you to hit test points against complex paths: pointInPath and pointOnPath. Also, here are a couple of examples to show the new APIs at work:.
As you may already know, with Ext JS 5.x, we've been working on a shared "sencha-core" package. In this release, we are moving Ext.app (our MVC and MVVM classes) to the core and finalizing the event system.
Originally found in Sencha Touch, Ext.app.Profile is now in sencha-core along with the rest of the Ext.app namespace. In other words, the unified MVC/MVVM feature set is now in the shared code arena. So now that Ext JS 5.1 applications have access to Ext.app.Profile, the logical questions are "how does it work" and "what does it provide".
If you've never used Sencha Touch profiles before, they are basically like miniature applications. Applications then list the desired profiles in their profiles config. At launch time, the framework will create an instance of all of these profiles. It will then iterate the list in order and call the isActive method. The first profile instance to return true is considered the active (or current) profile.
One obvious use for a profile (say for "tablet" or "desktop") is to control the top-level view to present to the user. With Ext JS 5.1, there is a new mainView config that the application or profile can specify. This config supersedes the "autoCreateViewport" config for older Ext JS applications.
Prior to Ext.app.Profile, Ext JS 5.0 applications could use responsiveConfig (via a plugin or mixin) for run-time choices or Sencha Cmd build profiles to generate target-specific builds. Application profiles sit in the middle of these two options.
Application profiles are executed at load time and hence can do whatever is needed. They aren't limited to setting config properties like a responsiveConfig. Because they must be included in the build, however, they will add to the size and space requirements of your application regardless of the device on which it is run. Using a build profile, however, you would be able to remove Android-specific content from an iOS-only build for the Apple App Store.
With Ext JS 5.0, we introduced the new multi-device, touch-enabled event system derived from Sencha Touch. This supported the momentum scroller and gesture recognition system and the delegated event model of Ext.Element. The entry point of the new event system was Ext.mixin.Observable. The original Ext JS event system, however, was provided by Ext.util.Observable. The APIs for these two classes were mostly the same, but they differed on some of the less common uses cases.
The unified event system in Ext JS 5.1 still provides these two classes (for compatibility reasons), but now the only difference between them is that Ext.mixin.Observable calls initConfig in its constructor whereas Ext.util.Observable uses the legacy Ext.apply approach to copy config object properties onto the instance.
In the process of completing the unification, we were able to optimize event listening and firing, thereby reducing overhead in these critical areas. Be sure to check the Ext JS Upgrade Guide for known compatibility issues.
Ext JS 5.1 continues to expand on the major accessibility support delivered in Ext JS 5.0.1. In particular, handling of various popup elements (from ComboBox to various menus) has been improved. The way cascades of such popups process focus and blur events has also been hardened.
With many touch-enabled devices, special logic is needed to efficiently manage scrolling. To normalize all this device-specific behavior, Ext JS 5.1 adds Ext.scroll.Scroller. An instance of this class is created by the framework when using configs like autoScroll, overflowX and overflowY configs, but it can now be more fully controlled using the new scrollable config.
If you are familiar with Sencha Touch, you will likely recognize this config. With Ext JS 5.1, however, it can now be a config object for the Scroller. To retrieve the Scroller, you call getScrollable. This object provides useful APIs like scrollTo and scrollBy, so you no longer need to worry about how the scrolling is managed on the current device.
If you have configs like these in your application...
autoScroll: true // or perhaps just horizontal: overflowX: true // or maybe just vertical: overflowY: true
The above notation will continue to work. However, the following would be equivalent and preferred in Ext JS 5.1:
scrollable: true // equivalent to autoScroll: true scrollable: 'x' // equivalent to overflowX: true scrollable: 'y' // equivalent to overflowY: true
Last but not least, Sencha Cmd 5.1 is also now available. This release is focused on performance and introduces a new compiler optimization. The new optimization, called "cssPrefix", optimizes framework code that supports using multiple versions of Ext JS on the same page. Called "sandboxing", it requires code like this:
rowCls: Ext.baseCSSPrefix + 'grid-row',
The new optimization replaces the above with something like:
rowCls: 'x-grid-row',
This eliminates hundreds of such concatenations in a normal app (over a thousand for the entire framework). To take advantage of this optimization, you should see something like this in your app.json:
"output": { "js": { "optimize": true } }
To expand all the optimizations available at present, you would have this:
"output": { "js": { "optimize": { "callParent": true, "cssPrefix": true, "defines": true } } }
If you use Sencha Cmd, you will need this version to work with Ext JS 5.1. As always, Sencha Cmd 5.1 supports all the previous framework versions from
In addition to all the new features mentioned above, there are numerous bug fixes and other enhancements. Let us know what you think by submitting comments on the forums. | http://docs.sencha.com/extjs/5.1.0/guides/whats_new/whats_new.html | CC-MAIN-2017-09 | refinedweb | 1,988 | 57.27 |
Leverage the tools in the .NET Framework to create a simple installation process.
ASP.NET makes it easier than ever to build killer Web applications and Web services. But building the app is only part of the battle. Hopefully you'll ship that application someday and put it into production. One of the great capabilities the .NET Framework brings to the table is Xcopy deployment -- the ability to copy your files into a directory where they're ready to run. That works great for simple applications and deploying patches and updates, but enterprise applications usually have a more complex architecture, requiring a few (or many) more steps to get the application fully deployed to the target server.
At a minimum for a Web application, you need to have the installation process create a virtual directory for you and copy the application files into it. But for enterprise-class Web apps, you likely need to perform additional steps. For example, you might need to register shared components in the Global Assembly Cache (GAC), install databases, add event logs, gather information from the administrator performing the installation to customize configuration parameters of the install, or run other installers, scripts, or programs as part of the installation process.
To accomplish these tasks you need to do two things. First, plan for deployment early in the design process. Second, package your application for deployment as a Windows Installer project, which will perform all the additional steps needed to deploy your application successfully. In this article, I'll discuss some common considerations for deploying ASP.NET applications and some easy solutions.
Deployment starts with design
If your application has any complexity whatsoever, early in your design you need to be thinking about how you plan to deploy it. Know what pieces and parts will make up your application, and what the target production environment will be, both from a hardware and sof
The tasks you need your .NET Framework application install process to perform generally fall into several categories. The easy part is getting a set of files into the appropriate directories on the target machine. You could accomplish this any number of ways, including simply copying the files over the network or using FTP, or by deploying a compressed file (using WinZip or Microsoft Cabinet) and uncompressing it on the target server.
For ASP.NET, you also need to create a virtual directory or site in IIS. There also might be some form of registration step, which will require you either to register shared assemblies in the GAC or register COM components that will ship with your application. Most real-world applications have you create or update one or more databases and populate them with runtime or configuration data. Finally, you might have other custom processing steps that need to be part of your installation process to execute other installer applications, run administration scripts, create event logs, or countless other tasks.
The most robust way to deploy applications on the Windows platform is to use Microsoft's Windows Installer technology. This means creating a setup program or Microsoft Installer (MSI) file that encapsulates all the steps of the installation process into a single procedure that needs to run on the target machine. MSI files actually are a form of database file, although it has a very complex schema and API for interaction. Using Windows Installer, you also can get automatic support for installation failure and rollback, repair, and uninstall through the Control Panel Add/Remove Programs applet. Visual Studio Setup projects allow you to create an MSI file easily to encapsulate the installation process completely. Web setup projects also handle the creation of the virtual directory in IIS for you.
To register files once they're placed on the target machine, command-line batch files or scripts work nicely if you're performing the install procedures manually; but a Windows Installer package can automate that process for you as part of the installation. Windows Installer packages also let you detect errors in the install process, and you can choose whether to report them to the user or to roll back the installation if the problem is more serious.
Deciding which assemblies should be made shared assemblies can be difficult. If you plan to take advantage of the version-enforcement capabilities in the .NET Framework, you'll need to apply strong names to your assemblies whether you make them shared assemblies (by placing them in the GAC) or keep them private (by deploying them in the local application folders). If you go with strongly named assemblies, you might want to use your application configuration file to specify what versions of which assemblies are supported.
Use Visual Studio setup projects
Visual Studio .NET includes a fairly powerful and easy-to-use capability to create setup projects that you can use to design and compile installation packages for your applications. To create one for an ASP.NET application, simply create a new project and select Web Setup Project from the Setup and Deployment Projects folder in the Project Wizard. If you do this from within a Visual Studio .NET solution that contains your Web project, the wizard will pick up some default settings automatically for deploying the Web application contained in the solution. Once the project is created, you can get to all the views containing the various setup steps, properties and configuration through the context menu for the project. Simply right-click on the project in Solution Explorer and expand the View menu (see Figure 1). For a standard ASP.NET deployment, you should include content files and the primary output in the Web Application folder at a minimum, but you also can include source files, documentation, debug files, and localization resources.
[IMAGE]
Figure 1. The Project menu for Setup Projects provides access to all the parts of the project you need to manage, including viewing the files installed, Custom Actions, User Interface, Registry settings, and Launch Conditions.
When you place the primary output from a Web application in the Web Application Folder, the setup project creates the bin subfolder and places the compiled output from the Web application there. It also detects dependencies and places any dependent assemblies that aren't shared into the output bin folder. Through the views of a setup project and the properties for items in those views, you can fully customize the way the installation behaves and what actions are performed (see Figure 2). You can create a setup project in its own solution, but it works much better if you create a solution that contains both the application you're deploying and the setup project because the setup project can include categories of files from the application project (such as primary output, documentation files, content files, and so on).
[IMAGE]
Figure 2. You can manage many aspects of your setup project through the Properties window for the objects that compose the setup project, and you can manipulate those objects through one of several views available in a setup project.
Deploying assemblies to the GAC is a simple matter of placing the file in the GAC folder in the File System view of a Visual Studio .NET setup project. Remember that the assemblies you deploy there will require a strong name. If you manage the project that creates the shared assembly separately from the main Web application, you should create a Merge Module setup project for that shared assembly. Then, incorporate the merge module into the main setup project for the Web application so the merge module can be included in other setup projects with minimal configuration. For COM components, there's a Register property for files added to the project so you can have COM components registered on installation automatically.
You'll want to gather additional information frequently from the person performing the installation so you can customize aspects such as which database server to use, account information and perhaps information to place in an application configuration file. Figure 3 shows you how Visual Studio .NET setup projects let you add dialogs to the setup process using one of many template dialogs. You can name and label the input fields in the dialogs as desired, then pass the values from these fields to custom build steps for further processing.
[IMAGE]
Figure 3. You can select from one of many form templates to add custom dialogs to the setup process, then you can use the information collected in these forms either to set predefined installer variables or pass information to your custom actions as parameters.
Empower your installation project
The key to a complete installation requires a combination of the ability to specify custom build steps and some form of code to specify what happens in those steps. Visual Studio .NET projects let you create Custom Actions that run for the actions Install, Uninstall, Rollback and Commit. You could simply execute Windows script or batch files from these actions if you want to code your custom actions as such, but this approach doesn't allow tight integration into the installation process because the scripts or batch file will run outside the transacted environment of the Windows Installer.
There's a very powerful way to accomplish just about anything you might need your installation to do and, unlike many commercial installer products, it doesn't require you to learn any special scripting languages or macros. The .NET Framework includes many classes in the System.Configuration.Install namespace that let you implement Installer classes using .NET Framework languages that can integrate directly into a Windows Installer project.
The code download for this article includes four projects in a solution to demonstrate an example deployment of a Web application (see the Download box for details). First is a simple Web application (DeployTestApp) that has a single Web page that displays a list of customers from a database. Second, there's a class library project (DeployTestBLL) that contains the code that gets the data from the database, representing a business-logic layer for a typical Web application. Third is a Web setup project (DeployTestSetup) that creates the Windows Installer package for creating the Web application on a target machine as well as all the resources it needs. The fourth project (DBInstallerLib) contains the custom installer class that gets called by the Windows Installer package to perform the custom build step.
This application's setup requirements include the ability for the person running the installation to specify the name of the database server, the name of the database to be created, and optionally a username and password if the connection to the database isn't a trusted Windows Authentication connection. The setup program then needs to create the database, populate a table in that database with runtime data, and update the web.config file to include the appropriate connection string for the database once it's created.
To accomplish these steps, you need to create a custom installer class that can run from the Windows Installer process created by the setup project. To create a custom installer class, first create a class library project and include a reference in that project to the System.Configuration.Install.dll library. Then, add a class to the project that derives from the Installer class. You need to place a RunInstaller attribute on this class as well; Figure 4 provides the code. The Installer base class includes the virtual methods Install, Uninstall, Commit, and Rollback, which correspond to the parts of a Windows Installer process. You can override these methods to add custom installation steps to be executed during the overall installation process.
Figure 4. By creating a class derived from Installer, you can include any kind of custom processing in a Windows Installer setup process that you can code in your .NET language of choice.
This article's sample code uses a SQL script for creating the database generated by SQL Enterprise Manager. It reads in the script and executes each command in the script using the SqlCommand class. It then uses the Bulk Copy Program (bcp.exe) utility to import a set of sample data exported from the development database as its deployed runtime data. In this case, it's the Customers table from the Northwind database, but it's created in its own database on the target machine so as not to interfere with your own copy of Northwind.
To run the Bulk Copy Program, you could use the Process class from the System.Diagnostics namespace to execute bcp.exe on the command line. But instead, you can hijack some convenient capability out of the System.VisualBasic namespace -- specifically the Interaction class' Shell method. Note that I'm calling this from a C# class library; behold the power of cross-language compatibility in the .NET Framework! The Shell method makes it easy to run an application as a fully constructed command line, specify the behavior of the window in which it'll run, and run the application as the interactive user so it can pick up the Windows Authentication identity of that user for something such as logging into SQL Server.
Once the class library with your installer class is built, you can add a custom action to the install process for your setup project and point it to the output of your installer class library. To do this, go to the File System view in the setup project and add the primary output of the class library to a folder in the output of the installation process. (In the code download, I created a Setup subfolder of the Web application and required the setup project to place the output of the installer class library project there.) Now go to the Custom Actions view, right-click on the Install folder, and select Add Custom Action from the context menu. You are presented with a dialog to select executable files and scripts from the output folders of the installation, and you simply can point the action to the class library containing the installer class. Once you've done this, you can set properties for the action, including the CustomActionData property to be passed to the installer or script file as parameters (see Figure 5).
[IMAGE]
Figure 5. The CustomActionData property for a custom action lets you pass parameters into the custom action. These parameters can be gleaned from the user from custom dialogs in the setup or standard properties such as TARGETDIR.
Using this technique of creating custom actions through Installer-derived classes means you can incorporate any actions you need in your installation process if you can determine how to code it in the .NET Framework. You even can throw in Windows Forms to gather further information from the user or to show progress or information regarding your custom actions. The VS .NET setup projects automate the most common actions for you, such as when you place files in locations on the target machine, register shared libraries or COM components, and create virtual directories. There are also some prebuilt installer components for creating Event Logs, Performance Counters, Message Queues, and Services. If you use Visual Studio .NET Setup projects with custom actions, built-in installer components and your own Installer-derived classes, there shouldn't be any installation hurdle you can't tackle.
Additional deployment options
Deployment is a huge topic and there are countless variations on what the requirements and solutions might be. If you're going to be creating installation packages frequently and allowing end users to install them, you might want to purchase a dedicated installation tool such as one from InstallShield or Wise for Visual Studio .NET. For most situations, however, you can get by with the tools in Visual Studio and the .NET Framework -- if you know where to look and don't mind writing a little extra .NET code.
Brian Noyes is a consultant, trainer, and writer with IDesign Inc. (). Brian specializes in architecture, design, and coding of .NET data-driven Windows and Web applications, and office automation and desktop productivity applications. He's an MCSD with more than 12 years of programming, design, and engineering experience, and he is a contributing editor for asp.netPRO and other publications. E-mail him at brian.noyes@idesign.net.
Please let other users know how useful this tip is by rating it below. Do you have a tip or code of your own you'd like to share? Submit. | http://searchwindevelopment.techtarget.com/tip/0,289483,sid8_gci945897,00.html | crawl-002 | refinedweb | 2,737 | 50.46 |
.
How about events? Objects with ‘event’:something are treated differently than you explain in 4, right? Otherwise I could not send one event (maybe with a different label but everything else equal) on the same page twice… I always get confused and just hold my thumbs pressed that that’s how it works :-)
Nope, ‘event’ is just a property of the pushed object like anything else. In terms of JavaScript code, there’s nothing spectacular about it. You can push the same event multiple times, and each time the dependent tags will fire. If you look at your dataLayer after the page has loaded, you’ll see at least three different events: gtm.js, gtm.dom and gtm.load. If you push ‘event’: ‘gtm.js’ again, all {{url}} matches regex .* fire again, for instance.
It’s really quite logical. The only difference with ‘event’ is that GTM uses it as a trigger, but if you refer to {{event}} in your tags, it always returns the most recent value of the property, which is always the value that fired the tag from where the {{event}} macro was called :)
Thanks for the answer.
How does the “trigger” actually work? When I add 2 events in the head (before the GTM Code) both events make it into GA. So it seems not have anything to do with timing…
Hey Jonas,
An ‘event’ can only ever be one thing at a time. So if you have ‘event’ pushes in the HEAD of your document, they will be replaced with ‘event’: ‘gtm.js’ once the container script loads.
The first ‘event’ to fire is always {{event}} equals gtm.js, since that’s the initiator event for GTM (also it’s the underlying event in all rules without an explicit {{event}} rule, e.g. the default All Pages rule).
So you shouldn’t have ‘event’ pushes in the head of your document. Whatever you have in the head of your document, once the container snippet loads, all that data will be available, so you can’t really “separate” it into different tags.
Worth reading. You make me regret dropping the JavaScript course on CodeAcademy and CodeAvengers every few months.
On a side note, have you seen any good resources regarding GTM+GA on responsive web sites? Until now I only found this
Hi Mateusz!
Analytics Pros have a good guide as well:
Wow! Thanks alot. I’m pretty new to GTM and this is the best tuto i’ve come across so far (and I’ve been looking for something this good for awhile!)
Hi Simo,
Great blog once again. I have only recently started looking into working with the dataLayer for GTM, and would like to use it for ecommerce tracking. I know you have to declare certain variables from the purchase page for it to enable to push that through to GA. I have a javaScripting / dataLayer question regarding this –
There are 4 steps until the user makes a purchase, on the 2nd step they choose different options they would like to add onto the product and then the 4th step shows them a “confirmation page” on what they purchased with all the details. The source code will look something like this:
Group B
Car name or Similar
id=”updated_price” class=”ban_title”>Total: R
298.68 for 1 day/s (made the variables up)
I would like to pass some of that information to the datalayer. I would like to get the first line that tells me in what group did the user purchase and then in line two I would like to know what the car’s name is. In the third line I would like to capture the total cost (298.68). There are many more things I would like to capture within ecommerce, but I am not too strong in the JavaScripting part. Where do I start with such information and how to structure the dataLayer and make sure as a beginner that I get to track everything?
Pretty long post, sorry about that. I hope I have provided you with enough information.
Thank you so much.
Tiaan
Hi,
First of all, sorry but adding code directly to WP comments just doesn’t work, since the platform turns your markup into actual HTML :)
Anyway, from what I gather this isn’t really a JavaScript thing but rather something you should do server-side. dataLayer does not persist, in that it’s renewed with every page refresh. Thus whatever you push in step 2 will not survive to step 4, unless you use a cookie or some other method.
I suggest you take a look at Enhanced eCommerce for Universal Analytics and Google Tag Manager:
It has a number of options you can use to add extra data about purchases. If the options aren’t good enough, you can just create custom events with more details about the purchases (perhaps send the transaction id with the event as well, so that you’ll have a quick view to which transactions and events are related).
All transaction-related pushes should always be written with server-side code. Relying on client-side code and scraping the page for details is very error-prone, and you’ll risk losing a lot of valuable information about transactions on your site. The server-side code (eCommerce platform or CMS should be able to produce it) must add the details into dataLayer before the container snippet, so that you can then utilize the Transaction tag type in GTM’s Universal Analytics tag.
These day Java script becomes more popular in Web programming culture, and it plays a major role in web design and content.
I need to learn the fundamental of JAVA script carefully. Currently I am using and learning the basic HTML and some CSS, but I still need to improve on my PHP, MySQL and JAVA script knowledge.
Thanks for sharing the useful information. It helps a lot.
Hi Simo,
I would like to start tracking what “high value customers” are doing on the site. The way to do this is by adding a dataLayer declaring a value of a users once they registered or logged in?
Does the dataLayer declare automatically if I tag it through a custom HTML tag or would I need to sit with a developer to help me with some coding on the backend?
I would like to track the differences between how a logged In user navigates the site compared to non-logged in – same goes for registered users.
Best regards,
Tiaan
Hey Tiaan,
The dataLayer is declared automatically if you don’t have an explicit declaration (dataLayer = []) before the container snippet. This means that in your Custom HTML tags you should use dataLayer.push(); instead of another declaration. Redeclaring a JavaScript variable overwrites its previous content.
The best way to track logged in users, however, is definitely to use server-side variables, since that way you can use your pageview tag to send the logged in status as a session-scope custom dimension. If you use a dataLayer.push() for example upon a successful login, there’s always the risk that this data won’t get sent if there’s a delay in the script, for example.
A Custom HTML Tag with a dataLayer.push() should work fine if you don’t want to bother the developers.
Thank you for the reply and information – What I can take from this is that if I bother the developers, I need to declare the data layer before the gtm script such as in this example (on the logged in page):
dataLayer = [{ ‘VisitorType’: ‘logged-in’}]
or
I could use a custom HTML tag and fire it on the logged in page with a dataLayer.push({‘VisitorType’: ‘logged-in’})
Thank you
Tiaan
Exactly!
Hello Simo,
I’m working with an enhanced ecommerce enabled website and i’d like to retrieve values contained into the ecommerce part of the dataLayer which use a structure that is a bit different than other variables (see here )
For instance in the purchase exemple i’d like to retrieve the id within actionField within purchase within ecommerce, but after trying various things i wasn’t able to get good results.
Thanks for the great article anyway, helped me a lot !
Just to be sure – when I declare a variable in Custom JS macro – it doesn’t mess up with other global variables in the document because Custom JS var is live only in this macro’s function scope. Right?
If you declare the variable using the var keyword then yes, it is scoped only to the execution context of the Custom JS function.
wrong link in the blog post:
Joe Zim’s JavaScript Blog – Actionable tips and guides for JavaScript and related frameworks.
Hi!
I noticed GTM automatically adds things in the dataLayer object for example when I click on link.
The problem is that in this object, is keeps a reference to the clicked DOM node. That means for a single page application, when you move from page to page, these DOM nodes can get removed, but a reference is kept in dataLayer, and so these DOM nodes leak :( Not a huge deal, but I was wondering if there is something that can be done? Does dataLayer get cleared from time to time ? I’m unsure how GTM uses dataLayer
Hi,
dataLayer is a global JavaScript structure just like any variable in the global namespace. Furthermore, GTM actually utilizes an internal data model, which treats the dataLayer structure simply as a message bus.
When working with single-page sites, a good idea is to always remember to flush variables you don’t need. | http://www.simoahava.com/analytics/javascript-101-gtm-part-1/ | CC-MAIN-2016-44 | refinedweb | 1,616 | 68.7 |
OpenCV is a popular library for Image processing and Computer Vision. Using python with OpenCV combines the simplicity of python with the capabilities of the versatile OpenCV library.
Using the Windows platform to foray into data science and computer vision is a popular choice especially among beginners. Anaconda is the first choice distribution for scientific python particularly on Windows. If a more portable setup is required to say run on a pendrive then I recommend using the WinPython distribution. Both setups allow for installing OpenCV in a straightforward way although it could be misleading for an absolute beginner. The first part explains the step-by-step process of installing OpenCV on Anaconda, the second part explains installing OpenCV on WinPython.
Step 1: Installing Anaconda
Download the latest Anaconda graphical installer for Windows from and check for the Windows architecture on your computer. If its 64-bit then choose the 64 bit graphical installer or else choose the 32-bit installer. Choose Python 3.7 for working with Python 3. This is the preferred option as python 2.7 is reaching its End-Of-Life by 2020.
By default the website prompts us to download the macOS installer so click Windows before clicking Download.
Launch the graphical installer and we will be prompted to choose for which user to install.
choosing the user under whom to install.
Choosing ?Just Me? is recommended as choosing All Users would require administrator privileges whenever we are modifying Anaconda(as will be illustrated later).
choosing the destination folder.
If we chose ?Just Me? then the above dialog will be displayed with the default location being ?C:Users<username>Anaconda3? whereas choosing ?All Users? would display the following dialog:
default location for ?All users? would be ProgramData.
The key is to use a path without spaces between folder names as this can create conflicts for Anaconda later( as it will prompt us when we try to choose such a name).
Anaconda installation options
Continue to install with the default option of ?Register Anaconda as the system Python 3.7? if we don?t have other versions of python or other distributions installed.
It takes a few minutes for installation to complete. Once completed we may be prompted to optionally install VSCode as an IDE. We may skip this option if we wish to do so.
Step 2: Installing OpenCV
Right. Lets now come to the actual goal of installing OpenCV for python.
Launch the Anaconda prompt from the start menu:
launching Anaconda prompt
We should see a similar prompt if we went according to instructions.
prompt for normal user.
if you chose ?All users? while installing then you have to launch the prompt by Right-clicking and choosing ?Run as Administrator? to execute with administrator privileges. This is critical.
If we wish to install OpenCV in a separate environment, we need to create an new environment( replace opencv with any name in the command below, note the symbol ? ? ? is a double hyphen, best to copy-paste followed by editing ?opencv? to a name you prefer):
conda create ? name opencv
activate opencv
To install the OpenCV we need to type the following command at the prompt:
conda install -c conda-forge opencv
installing OpenCV through anaconda prompt.
We can alternatively choose to install through anaconda navigator graphical interface. type in ?opencv? in search packages search bar. choose to install all the listed packages.
The prompt will show that it is ?solving environment?. It takes quite a bit of time if you are on slower Internet connection.
solving environment
Try to use faster Internet, preferably a wired connection for uninterrupted and best results. if you are in a work or institution based Internet connection then it is likely that an HTTP timeout will occur and we need to enter the command once again and restart the procedure.
proceed to install by entering y when prompted as shown.
Once the environment is resolved by conda it will list the packages that will be installed, namely: opencv, libopencv, py-opencv.
Enter y to proceed with the installation.
conda downloads and installs all required packages.
If you chose ?All Users? then ?executing transaction? will fail with the message ?PermissionError(13,?Access is denied?)?
access denied error is generated if the prompt is not run with administrator privileges.
installation is successful.
We can verify if the installation was successful by launching the python interpreter. opencv is referred to as cv2 in python. Type at the prompt:
import cv2
if the prompt is displayed then opencv then python has successfully imported the opencv library. But we should also verify the version of opencv so we need to type:
print(cv2.__version__)
as of March 2019 the version displayed is 3.4.1 which is the officially supported version of opencv by anaconda environment. If we want to work with a different version then while installing we can specify the version as ?opencv=3.4.1″ as shown below
conda install -c conda-forge opencv=3.4.1
verify the version of opencv.
Similar steps can be followed to install OpenCV on anaconda for MacOS.
Installing through WinPython
Step 1: Install WinPython
Winpython is a more portable way to work with python projects on windows. We can visit the homepage at. We can download the latest release for up to date packages.
WinPython homepage.
It is preferable to download from the github Releases page of WinPython:. The reason being the default link from the homepage redirects to sourceforge.net which restricts the download speed quite considerably(around 200KBps). like in Anaconda choose the correct version for the target architecture(64 bit vs 32 bit). The Zero version is the minimalistic version with pretty much bare python without most of the other extra packages( no Spyder, Jupyter etc.)
Github release page offers many options to download.
Install to desired folder.
the different apps available in WinPython folder.
Step 2: Installing OpenCV
Installing OpenCV in WinPython is quite easy. launch the WinPython Command Prompt.exe to get the prompt. Enter the command.
pip install opencv-python
verify the installation like in anaconda with
import cv2
print(cv2.__version__)
Thats it! We have successfully installed openCV for python on Windows using Anaconda as well as WinPython.
Hoping this helps you to explore different computer vision algorithms available in OpenCV!
To install Tensorflow especially for GPU I found an article by Harveen Singh which was helpful for me : | https://911weknow.com/installing-opencv-for-python-on-windows-using-anaconda-or-winpython | CC-MAIN-2021-04 | refinedweb | 1,070 | 59.7 |
Code:import java.util.Scanner; public class EnteredNames { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter Name1: "); System.out.println("Enter Name2: "); System.out.println("Enter Name3: "); System.out.println("Enter Name4: "); System.out.println("Enter Name5: "); }
I'm really new to programming and have been struggling with this forever. I'm supposed to have a user enter five names and then have those names printed out and stored in an array. This is what I have so far. If I could get just a heads start it would be greatly appreciated, I'm not asking for the entire project to be done, I just have no idea where to go from here.
Thanks. | http://cboard.cprogramming.com/tech-board/152301-beginner-help-java-code.html | CC-MAIN-2014-35 | refinedweb | 122 | 60.41 |
How to: Pre-Generate Views to Improve Query Performance
Before the Entity Framework can execute a query against a conceptual model or save changes to the data source, it must generate a set of local query views to access the database. The views are part of the metadata which is cached per application domain. If you create multiple object context instances in the same application domain, they will reuse views from the cached metadata rather than regenerating them. Because view generation is a significant part of the overall cost of executing a single query, the Entity Framework enables you to pre-generate these views and include them in the compiled project. For more information, see Performance Considerations (Entity Framework).
In addition to generating and validating Entity Framework model and mapping.
You could also use the Text Template Transformation Toolkit to generate pre-compiled views. For more information, see How to use a T4 template for View Generation.
Pre-generated views are validated at run time to ensure that they are consistent with the current version of the model and mapping files.
The procedures in this topic use the School model. You can generate this model by completing the Quickstart. You can skip the first procedure if the build process is already generating model and mapping files in the output directory.
To generate model and mapping files for the School model in the output directory.
To add view generation to a Visual Basic project
In Solution Explorer, select the project for which you want to specify the build event.
On the Project menu, click ProjectProperties.
In the Properties page, click the Compile tab.
Click the Build Events button.
In the Build Events dialog box, add the following pre-build event, without line breaks:
Click OK.
Close the Project Properties page.
Build the solution.
This generates the view file School.Views.vb.
In Solution Explorer, right-click the project name and select Add Existing Item.
In the Add Existing Item dialog box, navigate to the project's root folder and select the School.Views.vb file.
Click Add.
Build the solution.
To add view generation to a C# project
In Solution Explorer, select the project for which you want to specify the build event.
On the Project menu, click Properties.
Select the Build Events tab.
In the Pre-build Event Command Line window, add the following pre-build event, without line breaks:
Build the solution.
This generates the view file School.Views.cs.
In Solution Explorer, right-click the project name and select Add Existing Item.
The Add Existing Item dialog box appears.
Navigate to the project's root folder and select the School.Views.cs file.
Click Add.
Build the solution.
To re-add mapping and model files as embedded resources for ASP.NET projects://*/<resourceName>;
Metadata=res://*;
The
resourceNamemay include the project namespace. For more information, see Connection Strings. | https://msdn.microsoft.com/en-us/library/bb896240(v=vs.100) | CC-MAIN-2017-09 | refinedweb | 479 | 58.58 |
23 August 2007 08:44 [Source: ICIS news]
BANGKOK (ICIS news)--By 2017, Asia will contribute nearly a third of global oil demand, up from about a quarter currently, largely to due to growth in emerging markets in the region, an industry expert said on Thursday.
?xml:namespace>
Increased orders for petrochemical feedstocks would drive demand for oil products in Asia, said Bakhtiar Talha, a director of consultant PFC Energy based in ?xml:namespace>
Demand for naphtha would be the main driver of growth, jumping to nearly 9m bpd (barrels per day) by 2017, from about 6m bpd last year, he added.
Naphtha demand would comprise about a third of total oil product demand in
The recent spike in oil prices led to a rise in feedstock costs for many petrochemical firms and OPEC seemed intent on defending $60/bbl on the world markets, he said.
"The bottom line is that governments want to see more money from oil," he said.
Demand could drop if countries insisted on switching to alternative fuels like ethanol, he added. However, improvements in fuel efficiency would do more to reduce oil demand in the future than simply switching to alternatives, he said.
Oil refining capacity remained tight right now, he said, adding it should ease in the future as operators boosted capacity to produce more light products like | http://www.icis.com/Articles/2007/08/23/9055211/asia-to-contribute-third-of-oil-demand-expert.html | CC-MAIN-2015-22 | refinedweb | 224 | 52.12 |
im_insert - insert one image into another
#include <vips/vips.h> int im_insert(in, ins, out, x, y) IMAGE *in, *insub, *out; int x, y;
im_insert() inserts one image into another. ins is inserted into image in at position x, y relative to the top left hand corner of in. out is made large enough to hold all of both in and ins. Any areas of out not coming from either in or ins are set to black (binary 0). If ins overlaps in, ins will appear on top of in. Both images must have the same number of bands and the same BandFmt.
The function returns 0 on success and -1 on error.
im_extract(3), im_lrjoin(3), im_lrmerge(3)
J. Cupitt,
J. Cupitt - 11/04/1990 11 April 1990 | http://huge-man-linux.net/man3/im_insert.html | CC-MAIN-2018-05 | refinedweb | 129 | 76.11 |
Sometimes existing templates tags are not enough for rebellious developers. They need to create custom template tags to use.
In this article, we are discussing step by step process to create and use custom template tags in Django.
__init__.pyfile inside this newly-created directory.
custom_template_tag.py.
template.libraryinstance.
register = template.library().
randint.
from django import template from random import randint register = template.Library() @register.simple_tag def random_number(): return randint(0,999)
Load the tag class in your template before using any template.
{% load custom_template_tags %}
Now use custom tag anywhere in your HTML.
{% random_number %} .
This will print a random number at the same place. you can store the output of tag in some variable can use to anywhere in the template.
{% random_number as rnd %}. Now anywhere in template use
{{rnd}} .
__init__.pymust be present in the directory.
If it is still not working for you, please comment. | https://pythoncircle.com/post/42/creating-custom-template-tags-in-django/ | CC-MAIN-2021-43 | refinedweb | 147 | 60.82 |
NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.
Microcontroller Programming » Binary Clock
Ok, I know I'm gonna have a couple of little questions regarding my latest little project, so I thought I'd start a thread rather than hijack another one.
Basic plan - based from the real time clock demo, adapt it to initially light up leds to show the time in binary form, 4 leds for hours, six for minutes (maybe 6 for seconds), I may also add functionality to set the time as well, but initially I'm not worrying about that.
My first thought was how to get the time displayed in binary format, so I thought I'd knock up a little function to test my binary conversion.
All works, but when I put this in context to my project, I dont think it's any good. First off, heres the function :
void conv_bin(int i)
{
if (i > 0)
{
bin(i / 2);
printf("%d", i % 2);
}
}
Quite simple so far. It simply displays the binary number, but does not store it anywhere.
Now to progress, I think it would be a good idea to store the output in an array. But I'm having trouble getting it to work.
My plan is then to (somehow - not thought this far ahead yet) use the array to turn the pins connected to my LEDS on.
First question, does this idea seem feasible, or is there a better way to do it?
If it is feasible, how can I get this to store the result in an array? I suppose I could not do it recursively, but this just seems the easiest way.
Any thoughts/tips would be appreciated.
Thanks
Re-wrote the code, and it seems to work, but if I'm doing this a daft way, please let me know - thanks
Code :
#include <stdio.h>
int bin(int i, int a[])
{
int count=0;
while (i > 0)
{
a[count]=(i % 2);
count++;
i = (i/2);
}
}
int main()
{
int c, i, ary[8]={0};
for (i=0; i<11; i++)
{
bin(i, ary);
for (c=7; c>=0; c--)
{
printf("%d", ary[c]);
}
printf("\n");
}
}
Also, is there an easier way of posting code... adding 4 spaces could be a pain if the code snippet is of any length.
Bye
oops - typo in first post - the function should be called 'bin' NOT 'conv_bin'
I have something similar in the Nixie Tube clock project Im working on since the output time needs to be done in BCD for the Nixie driver.
Easiest way to do this, have a structure defined that stores the time, and have that time updated based on an interrupt. Then, you should be able to just output directly to PORTX, where X is what you initialize for your output.
I had to hack and slash the below example because the Nixie pin setting is a lot more complicated due to decimal to BCD conversion and I actually have another interupt that is sampling the input from a atomic clock radio reciever, but this "should" work since you just need turn on/off the pins on the output port. Just keep an eye out for syntax errors in the example, its untested, and just an approximation based off of working code. There are also some examples in the NErdKit code folder that show how to turn on and off individual pins using bit masks
//define type structure to keep track of time
typedef struct{
unsigned char second; //enter the current time, date, month, and year
unsigned char minute;
unsigned char hour;
}time;
time t;
ISR(TIMER1_COMPA_vect)
{
//this isn't going to allow for an accurate clock, will lose accuracy over time
//But we will sync off the atomic clock, so thats OK
//changed, if the clock counter is 16 bit, we can compare with the correct value
//and trigger the interupt at the right interval
if (++t.second >= 60) //keep track of time, date, month, and year
{
t.second=0;
if (++t.minute >= 60)
{
t.minute=0;
if (++t.hour >= 24)
{
t.hour=0;
}
}
}
}
void SetupTimer1()
{
TCCR1A = 0x00;
TCCR1B = (1 << CS12) | (1 << WGM12);
OCR1A = 57652; //this should be 57600, but I changed the divider math wise to 255 instead of 256
//and rounded up the result. The clock was slightly fast in my case, and over an 8 horu period was about half a minute
ahead of where
//it should have been. (57600, 57650 and clock was too fast, 57826 and 57712, 57660, 57654 and clock was too slow.
//Timer1 Overflow Interrupt Enable
TIMSK1 = (1 << OCIE1A);
int main() {
// LED as output
DDRB |= 0xFF;
initPins();
//general initialization for time
t.hour = 0;
t.minute = 0;
t.second = 0;
//setup the timer interupt and enable global interupt
SetupTimer1();
sei();
while(1)
{
//whatever, output time, something like....
//lets say PORTB is outputting the hours, this SHOULD light up the
//hours leds
PORTB = t.hour;
...
}
return 0;
Thanks digiassin, that looks good. I like the time structure - never thought of that! And it seems quite simple to set the leds to light or not.
I'm a bit confused with some bits, but I'll probably understand more when I start coding it, anything I'm not sure of, don't worry there will be questions.
I'm still thinking of how the final things going to work, but it all seems quite promising at present. I should get more time to work on this on Friday.
Thanks again, greatly appreciated.
No problem. I actually had this working as a prototype in the Nixie project running off LED's since I didn't have the driver chips in at the time, but I changed that code, but in theory it should work as long as your LED's are 0 based (bit 0 of your output is on B0, bit 1 on B1, etc). If not, you will just need to do some bit shifting, just be careful, not all the ports are 8 bits, and some of the pins are used for other things by default.
Thanks for the help. I only need 6 bits for minute (and seconds if I decide to implement seconds), and 4 bits for the hours (12 hr clock).
I noticed that some of the ports where not 8 bits when I did the marquee project (and wired it up wrong - I really should pay more attention).
So am I right in thinking, if say it's 3 hours, and I'm using PORTC, I can simply set 'PORTC = 3;', in other words, there is no need to convert the number to binary - it will just be done [000011]. (note to staff here) This is one of the things I was wondering when first running through the nerdkits tutorial - if I could just set a number and it would turn on the bits respectively. I thought it was implied in the guide, but I wasn't sure.
I'm gonna rough it all out this weekend, once it all works I can start the design of the housing to make it look pretty in the end.
Cheers
Wow, I haven't seen someone working with NIXIEs for years. Last time I touched one, was for a DEC PDP8, running a nuclear fuel - handling machine in a reactor here in the USA.
BCD can be confusing until you realize it's based on hex (base 16). It's nothing more than how decimal is normally represented in binary, except that the max value a nybble can represent is 09 and the next 6 values are used for sign (10-15 aka 0xA-0xF).
NOTE: LSB is on the right
8 + 4 + 2 + 1 Bit Position
-------------
0 + 1 + 1 + 0 6 Decimal = 6 BCD = 6 hex.
If you want sign represented (like '-9' or '-324', you need to use one of the higher order BCD equivalents, A-F. You're working in hex for 0-F (base 16).
0xA = 10 dec = 1010 in Binary/BCD (not the 1-bit is actually used for sign) 0 = '+', and 1 = '-'.
0xB = 11 dec = 1011 in Binary/BCD (so this is a minus)
0xC = 12 dec = 1100 in Binary/BCD (so this is a plus)
0xD = 13 dec = 1101 in Binary/BCC (so this is a minus)
0xE = 14 dec = 1110 in Binary/BCD (so this is a plus)
0xF = 15 dec = 1111 in Binary/BCD (so this actually means *unsigned* in BCD parlance).
Using 0xC and 0xD are the preferred BCD values for displaying sign.
So '9-' (aka '-9') would be: 0x9D in hex, 10011101 in Binary/BCD.
One of the main reasons I introduce hex in this discussion is because if you use hex as your intermediary between decimal and binary, it becomes very easy and straightforward to convert between the 3 bases (2, 10, and 16). Just be thankful you're not working in octal. :P
Finally, someone who realizes how rare and cool Nixies are :) I scored mine from Russian surplus. I have the circuit working already for the clock, or at least prototyped on a breadboard, im in the process of putting it together physically with wire wrap and such. I think in the future Ill just pay the money and get the circuit etched through Sparkfun or something. I can see after doing this why these things are so expensive to buy :)
Alrighty - this is the first free day I've had to play around with this. So far all I've done is take thr origional clock example from the nerdkits tutorial, built the board and got the display counting up on seconds. Then I set all the pins for PORTC to be outputs via
DDRC |= (1<<PC0);
DDRC |= (1<<PC1);
...
DDRC |= (1<<PC5);
Then to get them to light up showing the binary repersentation of the seconds (I'll use minutes in the end, but seconds follow the same idea)...
PORTC = the_time / 100;
And all works.
First question, is this the correct method for setting all of PC0-PC5 as outputs - or is there a one-line way that sets all (or some) of the pins?
My next question concerns the other pins I want to use to display the hours.
I need 4 pins to display up to '12' - I'd like to use PB1-PB4 as this keeps all the output on one side (although I'm not really bothered). But I notice PB0 is used to set the chip into programming mode. So I'm not sure what to do. I could use PD0-3, but I'd like to keep these free for the programming header.
Any advise?
Ok - I think PB0 only goes into programming mode initially (at power on), after that I think it's safe to use for anything. So that (might) solve that.
Next... why does the sample realtime clock program initialise the serial port? I don't really get the stream things - I think I have a basic idea, but I'm probably wrong.
Since eventually I'm gona be running 'headless' (no LCD), I can remove
//;
and all should still work the same?
Using PB0 seems to be a bad idea - it always goes into programming mode when you power on (pretty obvious really).
Is there a way around this - eg. if I have my hours number - could I just do "PORTB = hours * 2^n;" where n is the number of bits I wish to shift (in this case 1)... so to ignore PB0 I could simply do "PORTB = hours * 2;"
Is this a bad idea, should I just use PORTD?
Final post for the day...
All seems to be working - It has been mentioned to me that I should really push current to the chip rather than drain it - ie set the pins high for off and low for on and reverse the LEDs- is this true?
Another point I'm using an old charger 8V 200mA - all seems fine but the regulator is warm - not hot enough so you can't touch it, but warm. I never noticed it with the battery. Is this gonna cause problems, I assume they turn the excess voltage into heat to give you the nice 5V, but I want to check, don't fancy waiting another couple of week for the replacments :)
But in general all seems to be going well. The basic idea works - at the minute it counts up in seconds then increases the minutes section when it should. Im using PC0..5 for the seconds (that I'll acually use for minutes when everythings ok), and PB1..4 for the minutes (that will be hours - only need to go up to 12).
Tomorrow I'll add some buttons so I can set the time (haven't thought about this yet, but I'm sure it can't be too difficult), then get rid of the LCD and clean up the code a little. Then all thats left is to make an external housing to mount the LEDs in and look good, then that will be my first 'real' project complete (the marquee was the Nerdkits guys work, so I can't include that).
mcai8sh4, it's great watching you work through this project for yourself. I don't have answers for your questions, but it looks like you're learning lots of things as you go along. Please keep posting your progress for us.
Since you ask... I have progressed today :
Funny thing, I never thought my maths approach to ignore PB0 was 'bit shifting' until I'd done it!
Any way I've used that method, and it seems to work with no ill effects.
I'm still driving the LEDs from the pin to GND - still need to know if thats a good idea or not - but it seems to work.
I've not looked into the stream issue yet (I just don't quite understand it) but I've removed all that as I'm now running it 'headless'.
I've added a push switch so I can set the time.
Basically - It all seems to work, I'm still running off the battery - and the power regulator does get warm, so I guess the old charger I found will be ok, but I'll wait for clarification before I use it again.
I've not checked how accurate the time keeping is yet, but I've run it for about 15mins and it seemed ok. If the power adaptor is ok, I'll take it to work and run it all day (I'd like to keep my eye on it).
I Just need to clean up the code, but for anyone interested, it will be stored temporarily here
Once everythings done, I'll post the code somewhere more permanent.
So if the tests continue ok, and I'm happy with it, I can make the housing then I'll post a pic.
Watch this space (for my next problem with it :) )
As an aside, sadly, my binary reading skills aren't as good as they where 10 years ago, so it still takes me a few seconds to work out the time... so I thought I'd have something to help me.
I'm using Ubuntu Linux, and on my desktop I have conky running (to display... well, stuff) so I thought it'd be handy to have a binary representation of the time on my desktop, to 'train' my reading skills up a little - so I wrote a little bash script to display the current time in binary, then I use this script to display it on my conky setup (and it works!!! - yeah, I was surprised as well)
For anyone with Linux, who wants it here's the (very basic) script :
#!/bin/bash
#
# display the current time in binary format
# can be used with conky
let h=$(echo "ibase=10;obase=2; $(date +%I)" | bc)
let m=$(echo "ibase=10;obase=2; $(date +%M)" | bc)
echo "$h $m"
No use to most people, but someone might want it.
If your worried about the heat, just put a heat sink on it. They sell them at Rat Shack pretty cheap, just be sure to get the thermal glue also.
It will lose perfect sync over time, but almost all clocks do. Once I'm done with the Nixie clock, Ill post the schematic and the code to sync the time off the Atomic Clock module.
You should be fine driving the LED from PIN to GND. If your worried about it, you can add a small current limiting resistor in series with them, or use PWM to drive the LED at like a 75 duty cycle.
Thanks digiassn, I'm going to look into the PWM (try and get my head around it), as I imagine it would conserve the battery life a little.
I'm looking forward to seeing a photo of your nixie clock, I saw a picture of one this weekend, and was very jealous (I think it may be a number of years before I'm ready to even think about attempting one though).
Whilst I'm only playing around with very simple things at the minute, I must admit, I'm really enjoying it. Not sure what my next project will be, but I think I have a way to go before I will consider this one finished.
Right, so here's a little update on where I'm up to. It's been a busy couple of weeks, so I haven't progressed as much as I wanted to.
I've played around with the code - making slight changes here and there and, on the whole, I think the changes are improvements. These include changing the set_pins() function (simply shortened it from 1 line to set each pin to output, to 2 lines to set all the pins (the 10 that I need) to output. This was after reading waywards explanation. I've also altered the timing on the button to set the time (still not perfect - but usable). And probably a few minor other changes.
Today during my lunch I machined a quick prototype for the housings that will be my clock, and built a quick circuit to see how it looks.
I think it looks quite good - but I'm not 100% happy with it. It just doesn't seem bright enough (but looks cool now it's dark over here and I usually have the lights dim!
I've took a few pics with my phone (so the quality's not that good) but you get the idea.
Pictures and code can be found HERE
One thing I notice, one of the hour LEDs did not work, I checked the LED - fine, I checked the voltage - fine... then I got worried that I'd fried something. Turns out I'd forgot that I was ignoring PB0 and starting the hours on PB1 so I set DDRB |= 0x0F when it should be 0x1E (I think).
So basically I didn't set that pin to output, but (here's the question...) why did I still get +4.89V between the pin and the GND, when I tried to turn the pin on, but it didn't light the LED?
hey mcai,
if your pin was set to input mode with pull-up enabled (DDRBx 0, PORTBx 1) then you would read close to 5V on it, but the current through the pull-up resistor (typically 50k-100kΩ) would be too low to drive the LED. Or at least I think that's the reason. :)
I'm still not happy with the brightness of the LEDs I've got, I just bought standard cheap ones. They look great, until I put them in the housing (the light rods up - kinda total internal refraction style, but not quite). I swapped on of the ones I bought for one of the red ones that came with the Nerdkit - much better. I guess these may be ultra bright (or just not cheap nasty ones) - the quest continues
quick update - I've found some cheap (as in cost, hopefully not in quality) LEDs from a uk company (£0.99 delivery) -
I've order some and should get them this week, hopefully they'll be bright enough for what I want.
I've looked at using a pin change interrupt for the switch to set the time. I haven't implemented this yet because everything seems to work ok. I'll give it a go, but I'll still need the if statement and probably the delay_ms() so there doesn't seem to be much benefit at present. Thanks to Humberto who helped me understand the interrupt via IRC.
If the new leds are bright enough, I'm going to try and use PWM to lower the brightness slightly and reduce the power consumption. Having tried to read the datasheet - and looked at a few example pieces of code (Valentines heart amongst others) - I still don't really get it. If anyone knows how to do this on pins PC0..5 and PB1..4, any advise would be appreciated.
Other than that, nothing else has really progressed. Once I've implemented the switch interrupt, I'll post the code snippets - it could be useful for others.
New LEDs have arrived - massive improvement from that last ones. I've not added any resistors yet (naughty me), but it seems to work (for the minute at least). One thing that's confused me though - when I was using the cheap nasty leds (from maplin) the power regulator was getting rather warm, but now I'm using these brighter ones it's not getting as warm (barely any heat coming off it) - is this because the LEDs are using all that power to light up and before the power was being shed by the regulator?
Since I'm a happy bunny at the minute, I'll share a picture of my prototype (still only using my phone - so the quality is poor) but things are coming on :
The colours don't come out too well in the picture, they are really clear IRL, but you get the idea.
I'm going to leave it as it is for the time being, and have it run for a few hours tomorrow to see how it keeps time. I'll also be playing with the code - trying to add the switch interrupt and possibly PWM if I can.
Thats all for now! (...and I know it doesn't look that impressive - but I am really chuffed that I made that :D )
... added 100ohm resistors to each LED (hope thats right so stuff doesn't go bad), ran it for about 3 hours and kept perfect (as far as I could tell) time. Now I just need to figure out how to cut a bit of the power down - I'd like to be able to run it (for at least 24hrs) on a battery. Does anyone think I stand a chance? I think PWM may be the answer (lights are on for less time - so less power consumption? and longer LED life).
By putting the resistors in, excuse the stupid question here, am I making the LEDs run at the correct power, and therefore not die and short something? Here's the what I think I'm doing.... thanks to Mike's comments on the Nerdkits Unofficial IRC channel(TM) :
BLUE :
Forward Voltage (V): 3.0-3.2
Forward Current (mA): 20-30
So... (5-3)/0.030 = 66.667 ohms - so I went bigger and used 100 ohm resistors
GREEN :
Forward Voltage (V): 2.8-3.2
Forward Current (mA): 20-30
So... (5-2.8)/0.030 = 73.333 ohms - so again I went bigger and used 100 ohm resistors again
I don't know if I can use a software hack for PWM due to the whole loop idea (I still don't really understand it), and the hardware PWM... well the datasheet just confuses me - I'm not even sure if I can use it with the pins I'm using. This area needs a lot more study.
But on the whole - still happy, although I think this things gonna eat batteries faster than I can earn the money to buy them (and although I have used it with no issues - I'm still not satisfied with using the AC adapter I have).
And so todays little missive comes to an end :D
Please log in to post a reply. | http://www.nerdkits.com/forum/thread/60/ | CC-MAIN-2020-05 | refinedweb | 4,104 | 75.95 |
And, while I was otherwise engaged, another luminary of the digital age has left us to continuously look for ways around this valley of tears we inhabit (and no, I do not mean the Silicon variety). To stop beating around the bush - and especially stop trying to mint horrible metaphors - let's all stop for a monet and reflect on dmr.
If you thought the death of St Steve left the world poorer for a giant then you either think the same of Dennis Ritchie - or you have well and truly lived in a cave (or care only about how shiny and Fisher-Price like is your tech kit). Because, and if you didn't know you should really look it up now, a huge amount of the computing kit and software we use today rests on the shoulder of another giant - Dennis Ritchie, dmr.
No need to say more, really, so let me finish with the canonical "Hello, World!" program written in correct C (unlike elsewhere):
#include <stdio.h>
int main(void)
{
printf("Hello, World!\n");
exit 1;
}Oh, and if you are wondering why I chose exit value reflecting not everything went well with my little program, it is, of course, because there is something a little less well with the world with no dmr in it. | http://gnoughts.blogspot.com/2011/10/exit-1.html | CC-MAIN-2017-26 | refinedweb | 219 | 61.5 |
/* Prototype.
For further information on mount namespaces, see namespaces(7).
Only a privileged process (CAP_SYS_ADMIN) can employ CLONE_NEWNS. It is not permitted to specify both CLONE_NEWNS and CLONE_FS in the same clone() call.
For further information on PID namespaces, see namespaces(7) and pid_namespaces(7)
Only a privileged process (CAP_SYS_ADMIN) can employ CLONE_NEWPID. This flag can't be specified in conjunction with CLONE_THREAD or CLONE_PARENT.GID. Starting with Linux 3.8, no privileges are needed to create a user namespace.
This flag can't be specified in conjunction with CLONE_THREAD or CLONE_PARENT. For security reasons, CLONE_NEWUSER cannot be specified in conjunction with CLONE_FS.
For further information on user namespaces, see user_namespaces(7). processes in other UTS namespaces.
Only a privileged process (CAP_SYS_ADMIN) can employ CLONE_NEWUTS.
For further information on UTS namespaces, see namespaces(7).
This flag was deprecated from Linux 2.6.25 onward, and was removed altogether in Linux 2.6.38.).
If CLONE_VFORK is not set, then both the calling process and the child are schedulable after the call, and an application should not rely on execution occurring in any particular.
#include <syscall.h> pid_t mypid; mypid = syscall(SYS_getpid);
); } | https://www.commandlinux.com/man-page/man2/clone.2.html | CC-MAIN-2017-17 | refinedweb | 191 | 52.46 |
The method I'm currently using works just dandy but requires an upper bound of roughly 100-1000 elements in the series calculation to be approximately within 10 decimal places of accuracy. The question I have is would altering/changing the expression used for a converging series (i.e. rather than 2^k, say 10^k ?) give a "quicker" way of approaching the same output value but in shorter iterations and how?
The code in question:
def logN(val, base): #logarithm of base 'N' list_series = [] inc, integer, partial_sum = 0, 0, 0 bound = 1000 val = float(val) while val >= base: integer += 1 val /= base partial = val while inc < bound: partial *= partial if partial >= base: list_series.append(1) partial /= base elif partial < base: list_series.append(0) inc += 1 for var in range(len(list_series)): expr = ((list_series[var])/2.0)**(var+1) partial_sum = expr + partial_sum log_val = integer + partial_sum return log_val | http://www.dreamincode.net/forums/topic/304658-question-on-optimizing-logarithm/ | CC-MAIN-2016-26 | refinedweb | 147 | 55.24 |
JS Error Message i can't find anything aboutParagraphix Sep 5, 2016 11:53 PM
Hello,
iam getting a Error-Message from my script but i can't find anything on google about it - maybe because it's german.
Maybe someone can still help me? or knows what's going on?
created a new InDesign Menu where i call a Script like this:
main(); function main(){ var myMenu = app.menus.item("$ID/Main").submenus.add("$ID/Skripte").submenus.add("JavaScripts").submenus.add("PDF Export"); var myAction = app.scriptMenuActions.add("Page Exporter"); var myEventListener = myAction.eventListeners.add("onInvoke", jsPE); var myMenuItem = myMenu.menuItems.add(myAction); } function jsPE(){ #include "Scripts/JavaScripts/PDFExport/PageExporter/PageExporter.jsx" }
PageExporter.jsx = InDesign Page Exporter Utility Script | RR Donnelley
Iam trying to implement a few Scripts into the Menu - it's working pretty well for some scripts.. but a few (yes also others) throw up this error.
And i couldn't figure it out yet.
thanks in advance! o/
1. Re: JS Error Message i can't find anything aboutLoic.Aigon Sep 6, 2016 1:14 AM (in response to Paragraphix)
Hi,
I understand nothing about german but the "Ereignis-Handler" word let me think of event listeners typical error messages. Looking at your code reinforce my feeling so I will presume it's an event listener code error problem.
Basically, InDesign caught an event and tried to execute the handler which contains a code error. And indeed, your code seems to contain non valid code:
- function jsPE(){
- #include "Scripts/JavaScripts/PDFExport/PageExporter/PageExporter.jsx"
- }
#include instructions are expected to be placed at the beginning of code and not inside function (unless I am wrong). So you may try to either place it at the global level (i.e. not inside a function). Or if you want to load code depending the context, you should rather use the $.evalFile( someFileReference ) call.
HTH
Loic
Ozalto | Productivity Oriented - Loïc Aigon
2. Re: JS Error Message i can't find anything aboutParagraphix Sep 6, 2016 2:17 AM (in response to Loic.Aigon)
Hmm that's strange - it's working for almost every other script in the Code.
I chosed "#include" in this case because it always has a fixed path from where the file is located.
Iam still learning JavaScript - if there is a better way iam more than willing to try it =)!
So I will try to play with the $.evalFile( someFileReference ) command you mentioned once i get a free minute for this again!
At the beginning of the Script i have this:
#targetengine "session"
#include "REMOVE.jsx";
(Remove.jsx makes sure the Menu get's removed before it's being added again to avoid double entries during development)
It's a Menu that will hold some usefull scripts + other functions because i want to make the use of scripts and some easy grep functions as simple as possible for my colleagues.
As i already mentioned - most of the scripts DO work as i want them to (almost all of them) - without any problems.
So iam not sure if using #include inside a function is a Problem - but you might be right.
Maybe someone else knows more about this?
Thanks you for your response!
Kind regards
3. Re: JS Error Message i can't find anything aboutDirk Becker Sep 6, 2016 2:21 AM (in response to Paragraphix)
For launching other scripts, you should also have a look at InDesign's app.doScript() method ...
4. Re: JS Error Message i can't find anything aboutLoic.Aigon Sep 6, 2016 2:26 AM (in response to Dirk Becker)
To complete Dirk's answer and refine mine:
$.evalFile may be used preferably to load dependancies similarly to #include
app.doScript will be used to actually execute some code possibly from a file
5. Re: JS Error Message i can't find anything aboutMarc Autret Sep 6, 2016 2:30 AM (in response to Loic.Aigon)
@Loic
The directive #include can work fine anywhere in your code, provided it imports something valid. (Consider it a copy-paste of the included file.)
My guess is rather that the include path, which is relative, may point out to nothing. Paragraphix should use an absolute path to make sure it actually reaches the jsx file.
Also, a #targetengine directive is probably required to make the jsPE function persistent in the current session, since it is used as an event handler.
@+
Marc
6. Re: JS Error Message i can't find anything aboutMarc Autret Sep 6, 2016 2:36 AM (in response to Marc Autret)
And do no forget to restart InDesign when you are in testing persistent engines!
7. Re: JS Error Message i can't find anything aboutLoic.Aigon Sep 6, 2016 2:39 AM (in response to Marc Autret)
@Loic
The directive #include can work fine anywhere in your code, provided it imports something valid
So I was wrong . Happy to know that.
8. Re: JS Error Message i can't find anything aboutParagraphix Sep 6, 2016 2:46 AM (in response to Marc Autret)
Thanks for allt he replys so far!
As i meantioned above iam using
#targetengine "session"
and yes i also thought tat using #include would be like copy and pasting the script part into the main script.
Which is then called by the function.
Also this can't use an absolute path because this script will be used on multiple machines later on and i want to make sure that the path is not going to be a problem.
But the path is 100% correct i've tripple checked; and if i change the file name or the path so it can't be found i get a different script error - so it can't be due to a wrong path.
But iam open for any suggestions - I'll make sure to test everything once i get a free minute to do so!
9. Re: JS Error Message i can't find anything aboutVamitul Sep 6, 2016 4:41 AM (in response to Paragraphix)
Have you tested that the script you are calling actually works?
Try debugging the handler by actually calling the jsPE() function from a different script running in the same target engine. | https://forums.adobe.com/thread/2204966 | CC-MAIN-2017-34 | refinedweb | 1,037 | 72.05 |
80. Re: What PC to build? An update...mmconti Feb 10, 2012 1:31 PM (in response to jedwards2325)
I recently upgraded my editing computer, actually I built a new (my first) after following comments on the board since the original specs were presented by our friend in Holland. I would agree that you should skip the Quadro 4000 card and go with something else too. I had a Quadro 2000 card in my previous system.
Here are the parts that I purchased locally at which makes it really handy if you have something to return (which I did multiple times as I live near Denver). I have yet to try to overclock the memory as the motherboard comes with that kind of gamer support option, but it is something I will try when I don't have deadlines looming.
Asus Maximus IV Extreme-Z LGA 1155 Z68 eATX Intel Motherboard
XMS3 8GB DDR3-1600 (PC3-12800) CL9 Desktop Memory Kit (4 x 4GB Memory Modules)
Intel Core i7 2600 LGA 1155 Boxed Processor
GeForce GTX 580 1536MB GDDR5 PCIe 2.0 x16 Video Card
Performances Series P3-64 CSSD-P364GB2-BR 64GB SATA 6Gb/s 2.5" Solid State Drive (SSD) with Marvell Controller
Enthusiast Series TX750M 750 Watt High Performance Modular ATX Power Supply
HAF932 High Air Flow Full Tower Computer Case
Optical Drive
RAID drives
Etc.
Having had a new system only three years ago, the power is clearly more evident in comparison with rendering which is cut more than in half. I also find that the SSD card really speeds up the OS when starting up among other things.
In terms of overclocking, I am open to suggestions on how to properly proceed with benchmarking my results.
81. Re: What PC to build? An update...JEShort01 Feb 11, 2012 9:51 AM (in response to mmconti)
Michael,
You don't really need to worrry much about OC'ing memory, that doesn't help PPro performance in any noticable way.
However, if you could possibly trade your 2600 cpu in for the "unlocked" 2600k model, you would gain significant noticable performance by OC'ing your CPU. The 2600 cannot overclock nearly as easy or as high as the 2600k.
Jim
82. Re: What PC to build? An update...FlannelAndrew Feb 12, 2012 10:26 PM (in response to Harm Millaard)
To all,
I just read I neat article about two mysterious switches on my Asus mobo, the TPU and EPU. This may be of interest to people who don't know how to overclock their systems like myself, but are building the system to do it. Seems like you can get most of the gains with an ounce of the effort thanks to some clever engineering on Asus' part. Possibly something to consider when shopping for mobo's. Though, perhaps this is also sacrilige to the resident gurus.)
First I must give appropriate props to Harm......thanks for taking the time to lay down all this info in one place..........its much appreciated.
I would like some input on the type of system I need for my client...my knowledge is advanced in hardware but I have really none in the adobe suite, particularly AFTER EFFECTS 5.5 and video rendering. Any advice on the grade of system ( BUDGET,ECONOMICAL,WARRIOR) …and specifics on RAID, CPU, RAM…..would be greatly appreciated.
The client will be working mostly in AFTER EFFECTS…..here is the info I was given:
We use a DSLR Camera that only shoots in 1080p with an h264 codec usually Also we need a Mac computer so we can edit videos in After Effects and render big projects like ten greenscreen videos over night. We also have to backup 6TBs and I thought getting externals would be the way to go but is it cheaper or possible to put that into the Mac computer plus like an extra TB into the computer for programs?
It didn’t take much to get him off of the ‘Mac’….all I did was stated the facts…haha. Again…any and all feedback is GREATLY APPRECIATED. Thanks and God Bless.)
Zovic (and all),
As far as the SSD goes, I know there's been alot of debate about the cost/benefit of SSD at their current pricepoints, a possibility to save a chunk a change on the SSD but still get a fair amount of the benefits would appear to be cacheing a 40 or 60gb SSD instead. It's a feature I know is on the z68 chipsets, but I'm not sure what others, but basically the idea is that your computer determines the most commonly accessed programs and files to put on the SSD to get the benefit where it matters most. The article I read goes into more depth and has some benchmarks for adobe programs listed. May be worth considering if you're looking to trim the budget a bit.
86. Re: What PC to build? An update...JEShort01 Feb 21, 2012 5:37 PM (in response to zovic)
Zovic,
Nice build! In fact I would say that you have pushed way past the halfway point from economic to warrior threshold .
I do like SSD drives for OS/programs, but would suggest a smaller 120GB or 128GB size SSD for that purpose. Also, I think that both Crucial SSD drives are a safer choice vs. any SSDs that use the Sandforce controller (OCZ, etc.).
Regards,
Jim)
Zovic,
A 120GB SSD boot drive is plenty for OS, programs, and you can put the "Media Cache DB" on it too. If your system is not running "smoothly" enough then you don't need a bigger or better boot drive, you need more RAID arrays and/or single HDs for projects, media, render, etc.!
Jim
89. Re: What PC to build? An update...Videoguys Feb 24, 2012 11:53 AM (in response to Harm Millaard)
Feb 2012 update with 3 recommended builds! You can mix & match components between the two P9X79 builds or go with a budget system based on the P8Z68 and i7 2600K processor. We tried to get as close to $2K as possible for our system, but we went over.
-.
Unfortunately we still have not had the chance to build our DIY9 machine. Some internal IT issues have taken the bulk of our tech teams time over the past few weeks. We are also finding the i7 3930K processor in very tight supply.
Gary
106. Re: What PC to build? An update...Harm Millaard Apr 13, 2012 7:14 AM (in response to RMO2011)?
107. Re: What PC to build? An update...RMO2011 Apr 13, 2012 7:31 AM (in response to Harm Millaard).
108. Re: What PC to build? An update...ECBowen Apr 13, 2012 8:15 AM (in response to RMO2011)
109. Re: What PC to build? An update...RMO2011 Apr 13, 2012 9:39 AM (in response to ECBowen)!
110. Re: What PC to build? An update...ECBowen Apr 13, 2012 9:41 AM (in response to RMO2011)
111. Re: What PC to build? An update...RMO2011 Apr 13, 2012 3:25 PM (in response to ECBowen).
./.
112. Re: What PC to build? An update...ECBowen Apr 13, 2012 3:39 PM (in response to RMO2011)).
116. Re: What PC to build? An update...Dave Cowl Apr 14, 2012 7:33 PM (in response to Harm Milla.
117. Re: What PC to build? An update...RMO2011 Apr 15, 2012 2:13 PM (in response to RMO2011): -ram-cl11-30nm.html
Hopefully this link can be of some help for people outside USA searching for these sticks.
118. Re: What PC to build? An update...tcharr Apr 17, 2012 9:10 AM (in response to Harm Millaard).
119. Re: What PC to build? An update...Harm Millaard Apr 17, 2012 9:13 AM (in response to tcharr)
In your own thread I gave you the link to my own planned build, | https://forums.adobe.com/message/4335453?tstart=0 | CC-MAIN-2016-40 | refinedweb | 1,329 | 80.72 |
Details
- Type:
Improvement
- Status: Closed
- Priority:
Minor
- Resolution: Fixed
- Affects Version/s: 2.3.1.1
-
- Component/s: Value Stack
- Labels:
- Flags:Patch
Description
I saw using a profiler, that OgnlValueStack.findValue(String) gets called about a thousand times during rendering a page. Most of the calls are coming from ScopesHashModel.
All freemarker templates contain a lot of references to e.g. "parameters". This variable is evaluated in ScopesHashModel over and over again, which takes about 10% time of total page load.
I think we can assume, that the top-level objects on the value stack will not change during rendering a single struts2 tag. So with a little caching, we can eliminate most of the findValue method calls.
In my application I tested this modification and didn't notice any side effects or bugs. The OgnlValueStack.findValue(String) calls on a test page went down from a thousand to a hundred. This improved overall page rendering time from about 400ms to 360ms.
Patch is attached.
Please review it.
Issue Links
Activity
Is it thread-safe ? The patch uses simple HashMap, but maybe I missed something.
Indeed, an instance of ScopesHashModel is not thread-safe. But as I looked through the source I have concluded that it doesn't needs to be thread-safe.
Here is what I did. I opened the call hierarchy for the constructor of ScopesHashModel. This gets called only from FreemarkerManager.buildScopesHashModel(), and that from FreemarkerManager.buildTemplateModel(). From here there are two paths:
1. FreemarkerResult.createModel(), then FreemarkerResult.doExecute(). Here the ScopesHashModel is assigned to a local variable, and after exiting the method, the ScopesHashModel will be garbage collected.
2. FreemarkerTemplateEngine.renderTemplate(). Here the situation is similar, the ScopesHashModel is a local variable and will be garbage collected.
So it seems that an instance of ScopesHashModel is not used by multiple threads. For every struts2 tag rendering, a new instance is created. An other field of this class, unlistedModels is also a simple HashMap, so the class is not totally thread-safe even in it's current form.
But it is true that there may be a plugin or any code using this class in a way that multiple threads operate on the same instance. The base class, freemarker.template.SimpleHash is a bit more thread safe, javadoc says: "This class is thread-safe if you don't call the put or remove methods after you have made the object available for multiple threads.".
So I have created another patch that uses a ConcurrentHashMap. For this the code had to be modified also, because ConcurrentHashMap (unlike HashMap) does not handle null values.
Thread-safe version of patch
The Patch looks good for me. If no one has an recall I will going to include it into next release.
I've applied the Patch. Thank you for providing this Patch.
Integrated in Struts2 #412 (See)
WW-3750: ScopesHashModel calls OgnlValueStack.findValue too many times during rendering freemarker templates
Patch provided by Pelladi Gabor
jogep :
Files :
- /struts/struts2/trunk/core/src/main/java/org/apache/struts2/views/freemarker/ScopesHashModel.java
This patch has a side effect on how <#list> (<#foreach> and so on) are working in Freemarker templates.
Take a look on the exercise below from the config-browser plugin. With patch in place, ${showConfig} expression will be evaluated only once throughout the Stack and the returned value will always be the same.
<#list actionNames as name>
<@s.url
<@s.param${namespace}</@s.param>
<@s.param${name}</@s.param>
</@s.url>
<li><a href="${showConfig}
">${name}
</a></li>
</#list>
With this patch in place the above example is invalid, to be valid instead using <a/> tag, <@s.a href="%{showConfig}
>${name}
</@s.a> must be used. Any thoughts ?
I see.
I wrote in the description: "I think we can assume, that the top-level objects on the value stack will not change during rendering a single struts2 tag."
It seems that this assumption is false. This code:
<@s.url
Modifies the top-level object on the value stack named "showConfig". But with the caching in place, it is evaluated only once. If this is within a loop, this can cause regression.
By using the struts2 "a" tag, the variable will not be evaluated as a freemarker variable, but directly as a value stack variable. It does not use ScopesHashModel. That is why it works.
We have the following options:
- Cache only the parameters object. Every other variable will not be cached. This keeps the majority of the performance improvement without affecting compatibility.
- Keep the current code, and use <@s.a> instead of <a> as you mentioned. Generally, all occurrences of <@s.url> inside a loop should be reviewed.
For the first option, I am attaching a patch.
The parametersCache field in the patch is made thread-safe using the volatile keyword, which is enough for this usage.
Patch that only caches the parameters object.
Done, thanks for the patch!
Integrated in Struts2 #439 (See)
WW-3750 reduces scope of cashing (Revision 1307614)
Result = SUCCESS
lukaszlenart :
Files :
- /struts/struts2/trunk/core/src/main/java/org/apache/struts2/views/freemarker/ScopesHashModel.java
- /struts/struts2/trunk/plugins/config-browser/src/main/resources/config-browser/actionNames.ftl
- /struts/struts2/trunk/plugins/config-browser/src/main/resources/config-browser/page-header.ftl
Patch that improves performance | https://issues.apache.org/jira/browse/WW-3750?page=com.atlassian.jira.plugin.system.issuetabpanels:all-tabpanel | CC-MAIN-2015-48 | refinedweb | 883 | 59.9 |
IQ sample of BLE signal from Lopy4
Hi,
I am now trying to use software defined radio(SDR) to sample the BLE signal from Lopy4. The shape of the received radio seems to be incorrect. Could you help me have a look?
The upper image is the real received signal and the lower one is the BLE signal simulated using MATLAB. I capture the signal in channel 39 only. The sampling rate is 8M samples per second and the bandwidth is 2M.
Since there is preambles in the beginning of each BLE packet, repeated patterns should appear in the beginning of the packet(just as the simulated BLE signal shows). However, there is now no repeated patterns.
Thanks for your time
@yongyuan-wang I would be surprised if you didn't have any other devices sending out BLE advertisements at hand. Nearly any phone would, for instance. Most if not all Macs, many PCs, tablets, TV boxes... In an urban environment it's actually difficult to not see BLE advertisements all over the place, probably even more than Wi-Fi.
- Gijs Global Moderator last edited by
Right, but you still have the issue of signal scattering and receiving out of phase components (except if you're measuring in a anachoic chamber, but then you would probably not be asking the question here :) ). What you could perhaps try is feed of the BLE signal from the Lopy4 from the external antenna connector into the SDR using an attenuator in between (not sure about your SDR capabilities). That should at least remove most environment variables
How can you be sure the start of the signal you plot is correct to the time the signal is sent?
I'd also highly suggest you to take a look at something like this:
Again, I do not have any expertise in the PHY BLE layer, but the ESP32 microcontroller is widely used and I do not believe the hardware is outputting an incorrect signal there.
@jcaron said in IQ sample of BLE signal from Lopy4:
?
I only have Lopy4 on my hand and test 3 devices having the same issue. I set the sdr with center frequency 2.48Ghz and bandwidth 2MHz, which should perfectly fit the channel 39 of BLE
?
@Gijs Thanks for your reply. Please let me talk about what I am trying to do now.
The figure above shows the packet format of the LE uncoded PHYs that is used in lopy4. I use the following codes to send BLE advertisement packets.
from network import Bluetooth from machine import Pin import time BT = Bluetooth() BT.set_advertisement_params(adv_int_min=0x20, adv_int_max=0x20) BT.set_advertisement(name="v1lopy_v1py_v1lopy_v1lopy_v1lopy_v1") BT.advertise(True)
Please just look at the first two parts of the BLE packets(preamble and Access Address). I looked up the specification of BLE and find that the value of preamble and Access Address are the same for each packet. The preamble should be 10101010 or 01010101 and the value of Access Address should be 10001110100010011011111011010110b (See the following figures)
My project is to collect this part of BLE packets that send the same value(or data). I have 10 lopy4 here and I want to use CNN to distinguish each devices(signal waveforms may be not the same due to hardware imperfections, though sending the same data).
My question is since the whole packet is modulated in the same method(GFSK), there is no reason the preamble looks totally different from the Access Address part.
Besides, the simulated signal also shows the preamble part should have some ripples, instead of a descending curve.
The sample rate I set is 8M samples per second and the symbol rate of BLE is 1M symbol per second. 8 samples per symbol and the preamble has 8 symbols (1 symbol equals 1 bit here). Therefore, the first 64 samples should be the preamble and it appears that the first 64 samples are not similar to the following samples. So I am not sure if there are problems with the modulation of the preamble or just my misunderstanding of this topic
Thanks for your time
- Gijs Global Moderator last edited by
Im having a hard time getting up to speed here as you've probably been working on this longer than me.. Could you elaborate on what you are trying to achieve?
Online you can find various sources on how to decode the BLE signal with an SDR that could probably help you better than I can.
We have had no issues (as far as I know) with BLE connections, so Im assuming there is no issue with the actual signal
Hi,
I have not do any corrections yet, but my purpose is not to decode or recover the signal.I did the auto-correlation to the whole received frame to detect the start point of the BLE packet. The originally received frame should be like this:
Besides, one thing to be curious is that the first 64 samples should be the preamble part of BLE packet. I can see there are phase shift in the simulated data but no phase shift in the real received data. I do understand the noise or environment will affect what I received, but I do not understand why there seems to be no phase inverse in the first 64 samples and apparent phase inverse in the rest 256 samples with the same type of modulation (GFSK)
Thanks for your time
Yongyuan Wang
- Gijs Global Moderator last edited by Gijs
Hi,
I have no experience with the low-level signalling of BLE, but I do know some things about RF propagation.
Did you do any processing to the signal you received on the SDR? The transmitted signal will get reshaped by reflections (different path lengths), phase distortion, scattering, diffraction etc. Perhaps try to auto-correlate the received signal and/or apply some noise corrections. Did you do any sample clock or phase corrections? Also, absolute vs real/imag could throw you off there.
It is very hard to accurately sample the BLE signal and there's a lot of signal processing that goes into receiving such a signal on chip.
Let me know!
Gijs | https://forum.pycom.io/topic/6850/iq-sample-of-ble-signal-from-lopy4 | CC-MAIN-2021-10 | refinedweb | 1,030 | 59.64 |
>
Hey, is there a better way to do this? I have a bunch of hidden gameObjects. When I click on the first gameObject, I destroy it then activate the next one. I'm doing it fine, but i'm sure this is not the best way. I'm still a novice. Then I get an error at the end saying that i'm out of bounds.
Here what it looks like:
Here is the code:
public class onMouseClick : MonoBehaviour {
public Transform raceSet;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Transform secondChild = raceSet.GetChild(1);
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition),
Vector2.zero);
if (Input.GetMouseButtonDown(0))
{
if (hit.collider != null)
{
if (hit.collider.gameObject == this.gameObject)
{
Destroy(gameObject);
secondChild.gameObject.SetActive(true);
}
}
}
}
}
Thank you for your time!
Sorry the code is all piled up, how can I format it better? I'm going to recheck the thread tonight after work. Thank you.
Answer by xxmariofer
·
Jan 17 at 06:54 PM
when my answer code doesnt goes in a good format i just put some extra spaces at each code line that works for me.
There are a lot of thinks you can change.
First save vars once if posible, you are declaring a seconChild var when you can just assigned one at the start, but if you want to assign it there for whatever reason dont code extra unnecesary code, you would be able to deckare the var just before the secondChild.gameIbject.SetActive(true)
But dont really use that method, probably with your type of game you can reuse those platforms after that so you can have a pool of hiden objects and just activate and desactivate it by code.
Get use to work with layers and tags for avoiding extra checks, right now you have few objects but with a big project you might have thousands and somthing like raycast would have to do a ot of extra checks
Are all platforms / buttons (not sure what those are) the same? cause you could have just 1 with a bunch of positions and repositionate once per click.
That error is cause the parent object ends up without childs you can fix that just checking if secondChild is null.
If you are using a property frequently you can save it too at the start for saving some extra time like create a Vector2 vectorZero = Vector2.zero.
Also it is better usually a manger that those the work rather than having that script assigned to every object.
Hope it helps other will give you extra Contains(gameObject) to find and destroy a gameObject from a list
2
Answers
Destroying objects
1
Answer
Trouble with destroying an instantiated prefab
2
Answers
Failure to destroy a game object in a for each loop
1
Answer
gameObject doesn't self-destruct after collision c#
2
Answers | https://answers.unity.com/questions/1591242/going-through-empty-gameobject-by-clicking-first-c.html | CC-MAIN-2019-13 | refinedweb | 483 | 70.13 |
Grails is a great little framework - like any framework, you'll need to learn how it works before becoming really productive, and you have to beware of too much hot-shot Groovy code making the application hard to maintain, but I for one am finding it a real boost.
However, personally, I can't live without my Maven dependency management. Yes, I know, Ivy bla bla bla, but Ivy IDE integration sucks. So I was really looking forward to Grails 1.1 because of its promised Maven support.
As people will no doubt be aware, Grails 1.1 came out recently. So I thought I'd take the Maven support for a spin.
Your starting point for any Maven/Grails integration work should be the Grails documentation, or more precisely, the Grails Maven Integration page. Here all will be revealed.
Well, almost all. First of all, you do need to configure your settings.xml file as instructed in the documentation:
<settings>
...
<pluginGroups>
<pluginGroup>org.grails</pluginGroup>
</pluginGroups>
</settings>
From there on, it's slightly simpler than the documentation suggests - you don't need to much about with snapshot repositories or specific versions of the archetype plugin. In fact, all you really need is something like this:
$ mvn archetype:generate -DarchetypeGroupId=org.grails \
-DarchetypeArtifactId=grails-maven-archetype -DarchetypeVersion=1.0 \
-DarchetypeRepository= -DgroupId=com.acme \
-DartifactId=killerapp
Then cd into your new project directory, and initialize the Grails project structure
$ mvn initializeAnd lo-and-behold! A fully armed and operational Grails project!
I can run
mvn grails:create-domain-classor
grails create-domain-classfrom the command line, with the same effect. Maven has no added value when creating Grails classes, so I'd probably prefer the latter.
However, the real reason I was so keen on integrating Grails with Maven was to benefit from the Maven Dependency Management features.
I open up the pom.xml. There are already a lot of dependencies, but Hamcrest isn't one of them. So I add it at the end of the dependencies:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.5<version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.1</version>
</dependency>
No big deal, pretty standard Maven stuff. Now I add some Hamcrest asserts to my Grails unit tests:
void testShouldCheckForMandatoryName() {becomes
mockDomain(Listing)
def listing = new Listing(name:null,...)
assertFalse "validation should have failed", listing.validate()
assertEquals "nullable", listing.errors.name
}
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
...
void testShouldCheckForMandatoryName() {
mockDomain(Listing)
def listing = new Listing(name:null,...)
assertThat listing.validate(), is(false)
assertThat listing.errors.name, is("nullable")
}
Much nicer, aye? By the way, if you are using integration tests to test your field validation in Grails 1.1, don't - use mockDomain instead. This method basically mocks out all of the dynamic domain methods in your domain class (save(), load(), find(), validate(), and so on), so that you can test your validation rules (even "unique"!) to your heart's content. It will perform basic saves, loads, and deletes, using an in-memory list behind the scenes (no database required!). You can learn about the mockDomain() function and other cool new ways of testing in Grails 1.1 at.
At this point, as you would expect, running grails test-app from the command line will no longer cut it. To get your dependencies taken into account, you need to run mvn test. Which is the same thing, except that it throws your dependencies into the mix as well.
So how do the IDEs fare with all this? NetBeans IDE copes poorly. It can see that it's a Grails project, but apparently doesn't know about Maven/Grails integration. And you can't force it to open the project as a Maven project, and then tell it about the Grails structure afterwards. So you can add all the dependencies you like to the pom.xml file, they still won't show up in the auto-completion, and NetBeans IDE will complain about missing classes and packages all over the place. Not cool at all.
IntelliJ copes much better. I imported the project as a Maven project, and it proposed to add the Grails facet automatically. It could find all of the Maven dependencies just fine. Running the tests that use the Hamcrest dependencies works fine - in fact, it's excessively fast from within IntelliJ (much faster that from the command line).
From
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/grails-11-and-maven-taken-test | CC-MAIN-2017-39 | refinedweb | 751 | 59.5 |
I create a Python Script as Show below to print the list of Datasets in arcpy.AddMessage() this script run successfully for (*.gdb, *.sde) but when publish this script as Geoprocessing Service it work successfully for (*.gdb) only and return empty list for (*.sde).
Note: The two workspaces I used as “E:\WSTest.gdb” and “E:\WSTest.sde” where SDE is for SQL Server Express 2008R2
WS_in is string for the path of Workspace
import arcpy WS_in = arcpy.GetParameterAsText(0) arcpy.env.workspace = WS_in arcpy.AddMessage(arcpy.env.workspace) lst = arcpy.ListDatasets() arcpy.AddMessage(lst) for i in lst: arcpy.AddMessage(i)
you might need to register the database connection on the server.
Here's a link in case you are unfamiliar with this setup.
ArcGIS Help (10.2, 10.2.1, and 10.2.2) | https://community.esri.com/thread/116212-listdatasets-problem-with-geoprocessing-service | CC-MAIN-2018-43 | refinedweb | 136 | 71.82 |
In general this is a little trick to loop an operator on a list of arguments in the case you don't want or you can't consider the neutral element of the operator itself.
If you want for example to implement the sum of a list of integers the simpliest way is the following:
l = [1,2,3,4,5,6,7,8,9] r = 0 # the neutral element of sum for i in l: r += i
If you consider for example the "&" or "|" query operators for whom I don't know which is the rispective neutral element you can use the following method based on the associative property of the considered operator to obtain a query in which all conditions has to be verified.
from gluon import dal def querysum(*args): # considering to write this function in my modules I can get db from queries I pass as function arguments db = args[0]._db args1 = args[len(args)%2:] r = map(db._adapter.AND, args1[::2], args1[1::2]) while len(r) > 1: r = querysum(*r) if len(args)%2: # only if I have an odd number of arguments r = map(db._adapter.AND, r, args[:len(args)%2]) return dal.Query(db, *r)
I hope to be of any interest :-)
0
paulo 1 year ago
Thanks for the share!
replies (1) | http://www.web2pyslices.com/slice/show/1496/sum-of-queries | CC-MAIN-2013-20 | refinedweb | 224 | 60.99 |
Mobile web view
Wanted to show your awesome mobile app to other without letting them into the hassle of installing it? Thanks to flutter web (currently in beta) we have covered you.
Installation
Make sure that you are on beta and web is enabled if not then, here
Add in your pubspec.yaml
dependencies: mobile_web_view: ^0.1.2
Then import it in your main
import 'package: mobile_web_view/mobile_web_view.dart';
Warp MobileWebView to your initial route
home: MobileWebView( statusBarIconColor: Colors.white, content: Text("MobileWebView") child: MyHomePage(title: 'Flutter Demo Home Page'), ),
Want to contribute?
A help is always welcomed, check our CONTRIBUTING.md and don't forget to add yourself to CONTRIBUTORS.md | https://pub.dev/documentation/mobile_web_view/latest/ | CC-MAIN-2020-45 | refinedweb | 112 | 51.65 |
mvc offline application
mvc offline application
i have this problem. i've made a sencha touch application using MVC model and it works like a charm in safari and in the emulator but not in my devices.
the simple code is:
Code:
Ext.setup({ tabletStartupScreen: 'tablet_startup.png', phoneStartupScreen: 'phone_startup.png', icon: 'icon.png', glossOnIcon: false, fullscreen: true }); BT = new Ext.Application({ name: "BT", launch: function () { this.viewport = new BT.Viewport(); } });
any idea, please?
my App was rejected by Apple because i'v made my tests only on emulator. the first version of the application wasn't MVC and it had no problems.
thanks in advance
Emiliano
- Join Date
- Mar 2007
- Location
- St. Louis, MO
- 33,582
- Vote Rating
- 433
You shouldn't use Ext.setup when using Ext.application
You shouldn't do BT = new Ext.Application, you should just do Ext.application.
Your views should be placed in the BT.views namespace, not just BT.
In the launch method fired on the,
i've made thi correction but now it doesn't run in emulator too..
Code:
Ext.Application({ name: "BT", launch: function () { alert('ok: '); this.views.viewport = new BT.Viewport(); } });
if I leave this:
Code:
BT = new Ext.Application
if i leave
this.viewport = new BT.Viewport();
instead of
this.views.viewport = new BT.Viewport();
application run in emulator but not in device.
any idea?
sorry for mistake..
i've made some changes but with no results.
now, as before, my app runs via browser and in iPhone emulator but not on my device.
Code:
Ext.regApplication({ name: "BT", launch: function () { this.views.viewport = new BT.views.Viewport(); } });
no infos from debugger and no crash reports.
it simply doesn't open my panel.
what's wrong?????
What version on your device?
What version on your device?
What version of os/safari do you have on your device, is it different to the simulator/desktop browser? I did have some strange errors on safari iOS 5 at first, I think there is a little bug which gave me a white screen. I quit safari completely and tried again and it worked...
Did you try posting parts of the code in senchafiddle.com as well? | http://www.sencha.com/forum/showthread.php?161226-mvc-offline-application&s=b45f23d58d5419f228bec72ffd9f5465&p=691043 | CC-MAIN-2013-20 | refinedweb | 365 | 72.12 |
urn:lsid:ibm.com:blogs:entries-41c56f6a-05ca-4038-907f-6a0ab814c507 Ideally Radical Swapnonil Mukherjee's Blog 0 30 3 2015-02-09T16:09:17-05:00 IBM Connections - Blogs urn:lsid:ibm.com:blogs:entry-f3fb1b4b-f05e-48d2-bf80-05fb682c962d Nevado a JMS Driver for Amazon SQS SwapnonilMukherjee 120000QESN active false Comment Entries application/atom+xml;type=entry Likes true 2012-08-15T12:14:55-04:00 2012-08-15T12:14:55-04:00 receive messages. This places an additional burden on developers.</div><div> </div><div>There are APIs to write pollers in Java. There's the JDK Timer API, Spring Scheduler API and venerable battle hardened Quartz API. If you do not want to use schedulers <a href="">Nevado is a convenient JMS wrapper over Amazon SQS</a>. GIve it a try. <... 0 0 3872-3dda7b0f-e61f-4c01-9dee-3cf27907b3a7 Removing invalid characters from XML. SwapnonilMukherjee 120000QESN active false Comment Entries application/atom+xml;type=entry Likes true 2012-08-15T07:12:20-04:00 2012-08-15T08:19:01-04:00 <p>Unicode is a collection of characters of all the known languages of the world. Unicode characters are represented in code points like U+0048. It is actually <a href="">encoders like UTF-8 or UTF-16 that convert them to a binary form</a> so that they can be stored and transported over the network etc.</p> <p>XML as you would know essentially consists of markup tags and character data. The markup tags are <strong>></strong> (greater than), <strong><</strong> (less than), <strong>'</strong> (single quote), <strong>"</strong> (double quote) and <strong>&</strong> (ampersand). Character data which appears inside text nodes or in attributes could be anything, any character in any language.</p> <p>But not all Unicode characters are fit to be included in XML as character data. There are two specs that one needs to refer to understand this</p> <ol> <li><a href=""></a></li> <li><a href=""></a></li> </ol> <p>The following Java code is an implementation of these rules. It essentially removes all these illegal Unicode characters. The resultant output can be stored as character data inside any XML document. </p> <pre class="prettyprint"> <code class="language-java"> public class Test { /** * Removes all invalid Unicode characters that are not suitable to be used either * in markup or text inside XML Documents. * * Based on these recommendations * * * * @param s The resultant String stripped of the offending characters! * @return */ public static String removeInvalidXMLCharacters(String s) { StringBuilder out = new StringBuilder(); int codePoint; int i = 0; while (i < s.length()) { // This is the unicode code of the character. codePoint = s.codePointAt(i); if ((codePoint == 0x9) || (codePoint == 0xA) || (codePoint == 0xD) || ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF))) { out.append(Character.toChars(codePoint)); } i += Character.charCount(codePoint); } return out.toString(); } /** * Remove all characters that are valid XML markups. * * * @param s * @return */ public static String removeXMLMarkups(String s) { StringBuffer out = new StringBuffer(); char[] allCharacters = s.toCharArray(); for (char c : allCharacters) { if ((c == '\'') || (c == '<') || (c == '>') || (c == '&') || (c == '\"')) { continue; } else { out.append(c); } } return out.toString(); } /** * @param args The arguments to the main function. */ public static void main(String[] args) { String x = Test.removeInvalidXMLCharacters("<Help"); String y = Test.removeXMLMarkups(x); System.out.println(y); } } </code> </pre> <p>I hope you find this useful.</p> Unicode is a collection of characters of all the known languages of the world. Unicode characters are represented in code points like U+0048. It is actually encoders like UTF-8 or UTF-16 that convert them to a binary form so that they can be stored and... 0 0 21207-4eb38c32-bbf3-42a9-8bd1-3492ffc69c34 Unicode is not UTF-8 SwapnonilMukherjee 120000QESN active false Comment Entries application/atom+xml;type=entry Likes true 2012-08-15T07:07:51-04:00 2012-08-15T07:36:20-04:00 chalk, one is apple and the other orange. </div><div> </div><div>Unicode is a abstract representation of all characters of almost all the known languages in the World. For example the English word H e l p is represented in Unicode as U+0048 U+0065 U+006C + U0070 </div><div> </div><div>OK, so now that I know how to represent "Help" in Unicode, how do I store it. You see U+0048 is a bunch of letters and numbers. Computer don't understand letters and numbers. They only understand 0s and 1s. </div><div>That's where encoders come in. They convert Unicode representation of characters in to 0s and 1s so that they can be stored in computer memory. The process carried out by encoders is known as encoding. Here a picture of how things work. </div><a '="" href="" target="_blank"><img alt="image" src="" style=" display:block; margin: 0 auto;text-align: center; position:relative;" /></a><div> </div><div> </div><div>As of today there are two methods of converting that is there are two encoders that can convert Unicode characters to 0s and 1s. One is UTF-8 and the other is UTF-16. UTF-8 is the one that is wildly popular. The reason for it's popularity is that it is backwards compatible with ASCII. UTF-8 uses 8 bits that is 1 byte to store most English characters. For other languages it is free to use up to 6 bytes. </div><div> </div><div>So repeat after me </div><div> "Unicode is an <strong>Abstract Representation</strong> of all characters in all languages" </div><div> "UTF-8 is an <strong>Encoding Scheme to Store</strong> all Unicode characters in computer memory"<... 0 0 2130 urn:lsid:ibm.com:blogs:entries-41c56f6a-05ca-4038-907f-6a0ab814c507 Ideally Radical 2015-02-09T16:09:17-05:00 | https://www.ibm.com/developerworks/mydeveloperworks/blogs/roller-ui/rendering/feed/ideallyradical/entries/atom?lang=en | CC-MAIN-2016-26 | refinedweb | 953 | 57.67 |
tried to read the spec again yesterday, but again it made my head
spin. I don't have a background in tokenizer/parser theory so I
can't say which parts are necessary and which are not. I just noticed
a lot of words like "syntax", "serial", "native", "generic",
"parser", "loader", "dumper", "emitter", "type family", "kind",
"graph", "transfer", "taguri" that are too much to assimilate all
at once. It leaves me with the feeling -- and this is what I told Steve
-- "Does YAML really need a spec that's 73 pages long?" If it does,
maybe it's not a "simple" replacement for XML, and maybe it's not the
tool for small jobs.
Now, Python's grammar and parser module (AST objects) also make my head
spin for the same reason. But fortunately they take up only one small
corner of the documentation and don't prevent me from *using* Python.
They do prevent me from using the parser module to write a program that
lists all a program's dependencies (imports), a project I've tried to do
on and off for years but have always given up on. (Yes, I could do a
text search for "import" but I want to use Python's real parser.) But
that's just one insignificant application, not something that prevents
me from using Python.
XML on the other hand requires you to learn the gory details of DTDs,
namespaces, XSLT, etc, in order to do anything more than the simplest
file. You can't even use most public DTDs with a pretty intricate
knowledge, much less add a couple private tags to them, and the
whole thing gives you a sense of "Why does this have to be so
complicated? Why do I have to specify so many details just because
some huge corporation needs them for their documents?"
YAML has a large gap between the quick reference on the site
(and the other tutorials) and the spec. The tutorials get you started
but then what? For instance, the date format. Four formats, but
no explanation about what it's supposed to be used for, what it's
not supposed to be used for, and why it doesn't handle certain
less-precise formats users would commonly want. I realize YAML
is a new and rapidly-changing project and that this will come.
Still, these are the kinds of problems users face.
The gap can eventually be filled by a big users' guide so that most
people don't have to look at the spec, -or- by simplifying the spec so
it can double as a users' guide. For instance, do we need five
quoting styles for strings (bare, '', "", |, > )? Or 3+ styles for
single- and multi-line mappings? I wasn't here when each style was
adopted, and maybe they are all necessary for significant problem
domains, but it's worth considering whether any can be dropped.
That would shorten the spec and the quickref, and perhaps make YAML
more accessible. At the least, it would make the Perl/Python/Ruby
implementors' job easier, not having to code so many special cases.
Note that I'm not saying we need to do something about strings and
mappings in particular; I'm just using them as examples.
I like Oren's direction in his big message today. Supporting
schema-blind and schema-specific usages equally seems wise, and I
like the idea of banishing type conversions to the smallest portion
of code possible.
> | Nobody's goldfish is gonna die if I provide this *optional* method.
>
> This is where we differ. No body is going to die if _why doesn't
> throw an error when he finds duplicate keys in his loader.
It's possible for the loader to have a default recommended mode that
does whatever, -and- provide options like "extract mappings as pairs",
"all values are strings", or anything we find a significant
constituency for in the future. The options make certain uses of YAML
possible *without* detracting from the core/recommended usage.
(Now, maybe Oren's schema proposal will handle all the situations these
options would, we'll see.)
Perhaps some comparisions between YAML and Cheetah would be helpful.
I'm a developer for Cheetah, a string template system for Python
(). I don't work on the parser code (can you
guess why?), but I do other coding and also wrote the users' guide
and developers' guide.
1) We want Cheetah to be the template system of choice for the widest
variety of tasks. Its primary purpose is for Webware servlets,
and we won't add anything that detracts from that. But we've added
features needed by CGI scripts, Python source generators, Java source
generators, and shell scripts running templates as standalone commands.
We don't add features one person needs. But we add features that
make Cheetah suitable for an entire class of applications it wasn't
before. Anyway, I see YAML as being able to fulfill a similar role
in the data-storage/data-exchange realm. Certain core uses, but
also flexible for other uses on the side.
2) Rather than working from a written grammar and spec, Cheetah's
design was based on a spec inside somebody's head. Then the users'
guide was written, and I'm now writing an EBNF grammar based on the
users' guide. Not a suitable approach for an interoperational
project like YAML, but it's interesting that the two grew in almost
opposite directions.
3) YAML is in rapid change now anticipating a 1.0 spec freeze. Cheetah
was in rapid change last summer and then entered a long beta while we
slowly decided whether we're all comfortable with the current spec.
Since there haven't been any requests for backward-incompatible changes
for several months (except one), we're pretty confident about entering a
final beta as soon as a few small tasks are completed. There are plenty
of requests after that, but they are all behind-the-scenes work or
adding optional features, not things that would change the spec.
It's like popping popcorn, or at least that's been our experience.
Eventually the popping slows down and you can freeze the spec,
confident most people are comfortable with it. And if you end up in
a stalemate argument, the BDFL says this is the way it's gonna be,
and the dissenters either take it or leave it. But usually the best
design emerges on its own.
Thanks to Brian, Clark and Oren for putting all this work into what
might turn out to be a lifesaver for XML refugees.
--
-Mike (Iron) Orr, iron@... (if mail problems: mso@...) English * Esperanto * Russkiy * Deutsch * Espan~ol
View entire thread | https://sourceforge.net/p/yaml/mailman/message/8986792/ | CC-MAIN-2018-17 | refinedweb | 1,123 | 70.73 |
Confessions of an Old Fogey
For whatever reason, most of the toy applications I tend to write seem to end up being dialog based applications. I'm not 100% sure why, it probably has to do with the fact that the dialog box editor makes it really easy to drop controls on a page.
One of the things I often have to do is to specify a filename to the toy application. To do that, I usually add an edit control to display the filename and a "Browse..." button which brings up the common file browser control. Many people find it awkward to use the common file browser to locate files, so they often try typing into the edit control.
One of the really easy "nice touches" that you can specify to help with navigation is to add autocompletion support to the edit control. Fortunately, the Windows shell provides a really handy mechanism to do this in the SHAutoComplete function.
Adding autocomplete support is literally as easy as adding:
SHAutoComplete(hWndEdit, SHACF_FILESYSTEM);\
SHAutoComplete(hWndEdit, SHACF_FILESYSTEM);\
to your code.
It turns out that the shell has a fairly extensive autocomplete mechanism that allows you to customize this facility to a great deal (you can provide your own lists of elements, merge lists from multiple sources, etc).
For me, I almost always end up falling back to the old standby of SHAutoComplete - it's trivial to add it, and it adds a nice touch to your applications.
Whatever happened to Monaco? The other day, my friend was enthusiastically showing me Leopard. After a while, it struck me that Leopard isn't kicking Vista's ass, but iLife is. iPhoto is nice, but I'm happy with Picasa2. iMovie is great, but at least Vista Home comes with something like that. But, GarageBand is very very compelling. It fits in nicely with Apple's iMac, iPod, iTunes music oriented force. The message is clear: if you're a serious musician, music hobbyist , or music enthusiast buy a Mac.
There have been numerous rumors around the web that Microsoft had a GB like app (Monaco?) in the works for Vista dating back to 2004. But, Vista is seriously lacking in this department. What happened?
-g
Is this function also available for .NET Windows Forms?
Thanks Larry!!!
Just curious, under what handler for the edit box do you add the call to SHAutoComplete? The docs say "SHAutoComplete should not be called more than once with the same HWND. Doing so results in a memory leak." So, it seems that this may be kind of tricky to add it to the EN_CHANGE handler, unless I'm reading too much into the docs.
Hugo, I'm not sure...
Coleman: I just add it in the WM_CREATE handler for the dialog which contains the edit control.
Greg: Monaco? What's that?
Thanks again, Larry. I guess I assumed it was something you needed to do repeatedly. Oops, my bad.
I'm sure I can find a TON of uses for this in my applications. I especially like the URL modes. Cool!
Larry, re: Monaco. Here is the web site that put Garage Band, "Monaco" and your name together for me.
If the site is wrong, so be it. If you just can't talk about it, I understand.
thanks,
I love how people take unsubstantiated rumors, and combine them with true stuff (we did revamp the audio system and multimedia visuals in Vista) and come up with new stuff.
In all honesty, I have no idea what this "Monaco" thing is.
Gotcha. Thanks Larry. The internet is a wonderful world of misinformation.
Sorry to thread-jack...
Hugo : In .Net 2.0
System.Windows.Forms.TextBox has the AutoCompleteSource property. It is an enumeration.
Hugo:
In .NET 2.0 TextBox and ComboBox controls have AutoComplete properties that you can set to get this behavior.
In prior versions you can use P/Invoke and the Handle property of the control to call SHAutoComplete directly.
That is a handy trick. I'll have to keep it in mind, though I'll have to check if CE/Mobile supports it, I write plenty of code on that as well.
This is a request to restart the article:
Open Source and Hot Rods
Here is my comment:
Everyone here seems to have missed the key point. The choices are generally Open Source versus a Microsoft development environment. For simplicity, a user interface could be HTML, CSS and Javascript for either choice. But on the Open Source side you primarily have a language choice and many folks choose PHP rather than Python or Perl. On the Microsoft side you have fairly finite programming choices as well. So where is the problem?
Its the glue required on the Microsoft side both internal and external to any program. Internally, some people have even expressed the feeling that Microsoft folks are paying some attention to PHP Object-Oriented Development simply because it raises the complexity, and therefore lowers the understanding, of Open Source development.
Externally, you could write a book, and many have, that tries to explain and simplify the various ASPX gotchas. Inherits, Codebehind, codefile, src, master, page, namespaces, etc., etc. The list goes on and on. Even specification of 1.1 versus 2.0 on the .NET Framework can lead to errors if 2.0 has already been installed but remnants of 1.1 remain for some unexplained reason.
And, that leads to a worse situation. Either you hire someone that knows the ins and outs of the Microsoft software or you have your staff learn the Microsoft software.
Meanwhile my Open Source PHP developers have written more applications for my business. My Microsoft developers have the answers and are technically more knowledgeable. However, they cost me money while my PHP developers introduce new revenue streams far faster.
Unless it is a government agency, a tech-oriented company, or a company that bought into the old "buy blue" and you can't be fired (or is that "green" for Microsoft), the Open Source world seems to be eating the Microsoft lunch. I think that will only accelerate.
Jeff appears to almost have a clue. It's the gap that scares me.
Sorry to be a bit rude, but I am completely lost. How can a post about auto complete turn into comparison of Windows Vista with Leopard?
This is a great tip!
As some one who uses a Tablet PC at various times I'm a big fan of AutoComplete.
Thinking if its that easy it should have been an option in the OpenFileName struct used by GetOpenFileName().
Bill
Is Jeff related to aManFromMars?
(And many others.)
By the way, SHAutoComplete only works fine if the AutoComplete option for web addresses in the Internet Properties dialog is checked. If this option is unchecked, SHAutoComplete still returns S_OK, but no list is displayed.
Please read the description about dwFlags, especially the first four.
However, this MSDN topic does not negate Sven's argument that autocomplete from IE's dialog must be enabled for it to work in shell.
After I posted my article on the SHAutoComplete , I mentioned it to one of my co-workers. His response
Great thing is that (probably due to custom subclassing) it doesn't work in MFC based apps.
Igor: Are you sure? I know I've used that in MFC app's I've written in the past.
If it's true, it stinks.
Igor, it works fine for me. Were you trying with an Edit, or a ComboBoxEx? (If it was the combobox, you probably made the same mistake I did, missing the note about having to first get the combobox's Edit control, and then passing that handle to SHAutoComplete().)
Larry, Great post! This one somehow snuck by me; I've been working with the other method all this time. Thanks for the great time and space saving tip.
I agree with Jeff. More often than not, I encounter stuff Microsoft has done that seems to be there only for the sake of complexity. And about those cheepasses with NT4 drivers for their application - either they stay on NT4 or pay some programmers to develop them a new program - now the whole world suffers instead! (See, I optimized my comments and put two posts into one). :)
I tried on an edit box, Visual Studio 2005 (that'll be MFC 8.0 right?). I did it in OnInitDialog().
As Larry said in a reply to my post, it doesn't work for him either. Now if someone in Microsoft could tell us why and how to fix it... That would be cool.
If you think about it -- it is totally unintuitive. You get to use such a great thing if you write pure Win32 code (which many believe it is hard to do) and you don't get it if you use MFC which was made to make your life easier.
Oops, sorry. I misinterpreted what Larry said. He said _if_ it is true. | http://blogs.msdn.com/larryosterman/archive/2007/11/01/adding-autocomplete-to-your-edit-controls.aspx | crawl-002 | refinedweb | 1,505 | 74.9 |
REST API¶
Treeherder provides a REST API which can be used to query for all the resultset, job, and performance data it stores internally. To allow inspection of this API, we use Swagger, which provides a friendly browsable interface to Treeherder’s API endpoints. After setting up a local instance of Treeherder, you can access Swagger at. You can also view it on our production instance at.
Python Client¶
We provide a library, called treeherder-client, to simplify interacting with the REST API. It is maintained inside the Treeherder repository, but you can install your own copy from PyPI using pip:
pip install treeherder-client
It will install a module called thclient that you can access, for example:
from thclient import TreeherderClient
By default the production Treeherder API will be used, however this can be overridden by passing a server_url argument to the TreeherderClient constructor:
# Treeherder production client = TreeherderClient() # Treeherder stage client = TreeherderClient(server_url='') # Local vagrant instance client = TreeherderClient(server_url='')
When using the Python client, don’t forget to set up logging in the caller so that any API error messages are output, like so:
import logging logging.basicConfig()
For verbose output, pass
level=logging.DEBUG to
basicConfig().
User Agents¶
When interacting with Treeherder’s API, you must set an appropriate
User Agent header (rather than relying on the defaults of your
language/library) so that we can more easily track API feature usage,
as well as accidental abuse. Default scripting User Agents will receive
an HTTP 403 response (see bug 1230222 for more details).
If you are using the Python Client, an appropriate User Agent is set for you. When using the Python requests library, the User Agent can be set like so:
r = requests.get(url, headers={'User-Agent': ...})
Authentication¶
A Treeherder client instance should identify itself to the server via the Hawk authentication mechanism. To apply for credentials or create some for local testing, see Managing API credentials below.
Once your credentials are set up, if you are using the Python client pass them via the client_id and secret parameters to TreeherderClient’s constructor:
client = TreeherderClient(client_id='hawk_id', secret='hawk_secret') client.post_collection('mozilla-central', tac)
Remember to point the Python client at the Treeherder instance to which the credentials belong - see here for more details.
To diagnose problems when authenticating, ensure Python logging has been set up (see Python Client).
Note: The system clock on the machines making requests must be correct (or more specifically, within 60 seconds of the Treeherder server time), otherwise authentication will fail. In this case, the response body will be:
{"detail":"Hawk authentication failed: The token has expired. Is your system clock correct?"}
Managing API credentials¶
To submit data to Treeherder’s API you need Hawk credentials, even if you’re submitting to your local server. The recommended process is slightly different for a development server versus submitting to Treeherder staging or production, see below for details.
Generating and using credentials on a local testing instance¶
To generate credentials in the Vagrant instance run the following:
vagrant ~/treeherder$ ./manage.py create_credentials my-client-id
The generated Hawk
secret will be output to the console, which should then
be passed along with the chosen
client_id, and Vagrant instance
server_url
to the TreeherderClient constructor.
For more details see the Submitting Data section.
Generating and using credentials on treeherder stage or production¶
Users can generate credentials for the deployed Mozilla Treeherder instances
(and view/delete existing ones) using the forms here:
stage /
production.
It is recommended that the same
client_id string be used for both stage
and production. Once you’ve created your set of credentials, you can get
access to the Hawk
secret by clicking on the link that should appear on the
credentials list page.
The credentials must be marked as approved by a Treeherder admin before they can be used for submitting to the API. Request this for stage first, by filing a bug in Treeherder: API. Once any submission issues are resolved on stage, file a new bug requesting approval for production.
Once the credentials are approved, they may be used exactly in exactly the same way as with a local testing instance (see above).
Treeherder administrators can manage credentials here: stage / production. Note: Bugs must be filed to document all approvals & changes, to ease debugging and coordinating with credential owners in case of any later issues. | http://treeherder.readthedocs.io/rest_api.html | CC-MAIN-2017-26 | refinedweb | 726 | 50.67 |
I have written a widget using JS API 4.16/TypeScript and I'm deploying it in another application (also using TypeScript) and I'm getting the error in the post title on compile. In index.html I have:
and in my main.ts I have (this is the line generating the error):
the error is the same as the title: Cannot find module or its corresponding type declarations.ts(2307)
my tsconfig is:
the file structure is:
/
..my-app/
.. ..app/
.. .. ..main.ts
.. ..index.html
.. ..tsconfig.json
..Widgets/
.. ..MyWidget/
.. .. ..app/
.. .. .. ..MyWidget.ts .js etc
How can I resolve this error? There's a lot of info on developing custom widgets, but not much on deploying/moving to production, so I'm looking for any tips on the best way to do that, too.
It looks like the order is incorrect in this line:
import MyWidget = require("my-widget/MyWidget");
Should be something like this:
import MyWidget = require("MyWidget/my-widget");
Here are some examples about this workflow from our samples page:
Create a custom widget | ArcGIS API for JavaScript 4.16
Custom Recenter Widget | ArcGIS API for JavaScript 4.16
Thanks for the reply. I've tried using the order you suggested and it results in the browser trying to load my widget from the js api, and generating a not found error.
From DevTools console:
GET 404
Using the original order, the code still compiles and loads properly in the browser. That made me think it was a problem with my TypeScript configuration. | https://community.esri.com/t5/arcgis-api-for-javascript-questions/custom-widget-cannot-find-module-or-its/td-p/163814 | CC-MAIN-2022-27 | refinedweb | 254 | 53.61 |
09 October 2012 05:29 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
The rise in current account surplus was partly because there was an increase in
The current account measures a country’s trade in goods, services, tourism and investment with the rest of the world.
This resulted in a trade deficit of Y644.5bn in August, widening from the Y373.6bn deficit a month earlier.
“There is little evidence that the [Japan’s] export outlook will improve soon in the fourth quarter, if taking into account the weakness in global demand, the strength in the yen, and the repercussions of China-Japan political tensions,” said Singapore-based DBS Group Research.
($1 = Y78 | http://www.icis.com/Articles/2012/10/09/9602151/japans-current-account-surplus-in-august-up-4.2-year-on-year.html | CC-MAIN-2013-48 | refinedweb | 113 | 62.38 |
A tag consists of two items, a key and a value. Tags describe specific features of map elements (nodes, ways, or relations) or changesets. Both items are free format text fields, but often represent numeric or other structured items. Conventions are agreed on the meaning and use of tags, which are captured on this wiki.
Keys and values
Tags are presented for humans as
key=value: key and value separated by an equals sign. Sometimes, the key or value is surrounded by quotes to avoid confusion:
key="value" or
"key"="value"; the quotes (and, indeed, equals sign) are not part of the tag content.
Tags are applied to elements or changesets (i.e., tagging them) resulting in a collection of tags of any size. However, each collection may only contain a key once. Where a tag is not present, there are often considered to be default values or values inherited from parent elements.
The key, therefore, is used to describe a topic, category, or type of feature (e.g., highway or name). Keys can be qualified with prefixes, infixes, or suffixes (usually, separated with a colon, :), forming super- or sub-categories, or namespace. Common namespaces are language specification and a date namespace specification for name keys.
The value details the specific form of the key-specified feature. Commonly, values are free form text (e.g., name="Jeff Memorial Highway"), one of a set of distinct values (an enumeration; e.g., highway=motorway), multiple values from an enumeration (separated by a semicolon), or a number (integer or decimal), such as a distance.
Here are a few examples used in practice:
- highway=residential a tag with a key of
highwayand a value of
residentialwhich should be used on a way to indicate a road along which people live.
- name=Park Avenue a tag for which the value field is used to convey the name of the particular street
- maxspeed=50 a tag whose value is a numeric speed and speed unit. The unit,
km/h, is implied, but can be explicitly specified; miles per hour can be alternatively specified by appending
mph. Across OSM, metric units are the default.
- maxspeed:forward=* a key that includes a namespace for
maxspeedto further distinguish its meaning.
- name:de:1953-1990=Ernst-Thälmann-Straße a tag with the
namekey suffixed namespaces to specify the German name which was valid in some years.
Finding your tag
The following resources are often used to find an appropriate tag or explore tag usage:
- Map Features – a list of accepted tags grouped by key meaning.
- How to map a – an alphabetic list of real-world objects.
- Taginfo – an site to explore current tag usage in the OSM database, including tag values that are not necessarily documented (but it includes links to this wiki if there is a documentation for a tag)
- Search this wiki or browse its category tags
- TagFinder – Website providing full text search engine for OSM tags. (Also webservices available).
- Look how a similar object at another place is mapped (if you know where it might also exist)
- Read any tags you like
- Search the tagging mailing list archive or questions about “tagging” at the help site or forum.openstreetmap.org. Of course you also could ask at all three sites (but please only one at a time).
- OSM Semantic Network – a machine-readable structure containing the OSM tags
- …
Use in an editor
Some OSM editors (for example iD, Potlatch 2) hide the tags of objects by default, making them not directly editable; instead users fill-in a form. However, in most editors all tags can be displayed and edited by entering some kind of advanced mode of your editor.
For the example editors:
iD
- (only needed if you created a new object) Select the generic feature type preset (it is the bottom one). For example select “point” if you created a new “point” object.
- select “All tags” (bottom left)
Potlatch 2
- select “Advanced”
Metadata
Some tags were used in data elements only for attaching metadata displayed in map editors or in quality assurance tools (such as completion status, things to do, approximations, data or imagery source, tool or editor version, etc.). Since version 0.6 of the API, map editors and import tools are encouraged to attach a few metadata tags to the changesets they create (changesets are not data elements) instead of tagging every added or modified data element: these tags are now documented on this wiki as "discardable", meaning that they may be silently deleted from data elements by editors when they update them (they are still usable in changesets, and these tags are still visible in older versions of elements where these discardable tags have been removed and you can still inspect these old tags from old changesets that did not use this now preferred tagging method because these changeset still point to the older versions of elements that had these tags). | http://wiki.openstreetmap.org/wiki/Keys | CC-MAIN-2017-26 | refinedweb | 818 | 58.21 |
sandbox/bugs/adaptwaveletbug.c
This case includes the axisymmetric solver combining with Navier-Stokes, two-phase flow and surface tension as well
#include "axi.h" #include "navier-stokes/centered.h" #include "two-phase.h" #include "tension.h"
Introduce some constants of the case,
int LEVELmax = 9, LEVELmin = 5;
The program starts here,
int main() { size(10.0); init_grid(16); rho1 = 1000.0; rho2 = 1.0; mu1 = 5.0e-4; mu2 = 2.0e-5; f.σ = 1.6e-2; run(); return 1; }
As it can be seen, the initial condition is showing a drop with 10% gap for the refinement. The drop velocity is also set here.
event init(i = 0) { double x0 = 7.50; refine(sq(x - x0) + sq(y) + sq(z) < sq(1.1) && sq(x - x0) + sq(y) + sq(z) > sq(0.9) && level < LEVELmax); foreach() { if (sq(x - x0) + sq(y) + sq(z) < sq(1.0)) { f[] = 1.0; u.x[] = -10.0; } else f[] = 0.0; } }
The adapt_wavelet is used to construct a refined mesh close to the interface by choosing the “f” as the variable and “0.001” as the tolerance.
event adapt(i++) { adapt_wavelet({f}, (double[]) {0.001}, maxlevel = LEVELmax, minlevel = LEVELmin); }
And, finally, for the iteration showing and GFSView output we will use the following “events”.
event showiteration(i += 50) { printf("i[%06d], dt[%e], t[%.2f]\r\n", i, dt, t); } event gfsview(t += 0.1) { static FILE * fp; char name[500]; sprintf(name, "GFS[%05d]-t[%.2f].gfs", i, t); fp = fopen(name, "w"); output_gfs(fp, translate = true); printf("write data file!\r\n"); fclose(fp); }
The final time can be set here as well.
event end(t = 0.50) { printf("i[%06d], dt[%e], t[%.2f]\r\nEND OF RUN!\r\n", i, dt, t); }
The results has to show a drop moving with constant velocity; therefore, the adapt_wavelet has to move with the interface accordingly. Nevertheless, the refinement is not following the interface in some cells. | http://basilisk.fr/sandbox/bugs/adaptwaveletbug.c | CC-MAIN-2018-34 | refinedweb | 327 | 71.92 |
Red Hat Bugzilla – Bug 150665
local variable used before set
Last modified: 2007-11-30 17:11:01 EST
Description of problem:
I just tried to compile device-mapper-multipath-0.4.2-1.0 from Redhat
Fedora Core development tree with the Intel C compiler.
The compiler said
main.c(650): remark #592: variable "mode" is used before its value is set
The source code is
if (mkdir(CALLOUT_DIR, mode) < 0) {
Suggest init local variable mode before first use.
Version-Release number of selected component (if applicable):
How reproducible:
Steps to Reproduce:
1.
2.
3.
Actual results:
Expected results:
Additional info:
is the following enough to calm ICC ?
@@ -682,7 +511,7 @@
static int
prepare_namespace(void)
{
- mode_t mode;
+ mode_t mode = S_IRWXU;
struct stat *buf;
char ramfs_args[64];
int i;
>is the following enough to calm ICC ?
I haven't tested it, but a visual inspection suggests it will.
This is fixed in 0.4.3 and up. Can this bug be resolved now? | https://bugzilla.redhat.com/show_bug.cgi?id=150665 | CC-MAIN-2017-09 | refinedweb | 164 | 66.84 |
, what it means to deliver DPCs and interrupts, how IRQLs limit driver execution, why threads are scheduled the way they are, how synchronization mechanisms work, how memory is allocated and memory addresses are translated, and many other extremely important details on how Windows works—Windows Internals is the course for you. (And so is “the book”—Windows Internals, 5th Edition.)
First and foremost, you need to set up an environment in which you will build, deploy, and load your driver. We will be using a host machine on which we’ll build and debug, and a target virtual machine to which the driver will be deployed. My own setup is a Windows 7 64-bit physical host and a Windows XP 32-bit target VM, running VMWare Workstation.
In the next part, we will compile our first driver and load it onto the system using OSR Driver Loader.
During.
Dima has brought to my attention a nasty bug probably attributed to a memory corruption. The bug’s manifestation is usually an access violation in a completely unrelated piece of code, oftentimes causing an ExecutionEngineException.
This is an example of an access violation of the above variety (some of the output was snipped for brevity):
0:004> .loadby sos clr 0:004> g (510.c88): Access violation - code c0000005 (first chance) First chance exceptions are reported before any exception handling. This exception may be expected and handled. 00742a11 8b4028 mov eax,dword ptr [eax+28h] ds:002b:0000002c=???????? 0:000> !CLRStack OS Thread Id: 0xc88 (0) Child SP IP Call Site 004bedb8 00742a11 OverlappingObjects.Program.Main(System.String[]) [\OverlappingObjects\Program.cs @ 51] 004beff0 724221bb [GCFrame: 004beff0] 0:000> k ChildEBP RetAddr WARNING: Frame IP not in any known module. Following frames may be wrong. 004bedc4 724221bb 0x742a11 004bedd4 72444be2 clr!CallDescrWorker+0x33 004bee50 72444d84 clr!CallDescrWorkerWithHandler+0x8e … 0:000> !u 0x742a11 Normal JIT generated code OverlappingObjects.Program.Main(System.String[]) Begin 00742980, size d7 … \OverlappingObjects\Program.cs @ 51: 00742a0c mov ecx,dword ptr [esi+4] 00742a0f mov eax,dword ptr [ecx] >>> 00742a11 mov eax,dword ptr [eax+28h] 00742a14 call dword ptr [eax+8] Hmm. The exception seems to be happening when calling a virtual function on an object stored in the ECX register. From inspecting the source code, this is a virtual function call to GetHashCode.
If this generates an access violation, ECX must be some invalid pointer. (Although if this were a simple null reference exception, we would fail at the previous instruction when trying to dereference ECX.)
0:000> r ecx ecx=026ae494 0:000> !do 026ae494 <Note: this object has an invalid CLASS field> Invalid object 0:000> !gcwhere 026ae494 Address Gen Heap segment 026ae494 2 0 026a0000 Well, this is no null pointer. ECX is a reference into the GC heap, but for some reason calling a method through it fails. What does the method table look like?
0:000> dd 026ae494 L2 026ae494 00000004 00000000
Ow! This is not a method table. So far we have a reference into the GC heap that is not actually a reference to a valid object, so an attempt to call a virtual function on it fails. Let’s look around for some instances:
0:000> !dumpheap -type Overlapping Address MT Size 026ae480 00373534 16 total 0 objects Statistics: MT Count TotalSize Class Name 00373534 1 16 OverlappingObjects.ReferenceHolder Total 1 objects 0:000> !do 026ae480 Name: OverlappingObjects.ReferenceHolder MethodTable: 00373534 EEClass: 0062126c Size: 16(0x10) bytes Fields: MT Field Offset Type VT Attr Value Name 0060c12c 4000003 8 System.UInt32 1 instance 3405695742 Marker 003734b0 4000004 4 ...bjects.SomeObject 0 instance 026ae494 TheReference 0:000> !do 026ae494 <Note: this object has an invalid CLASS field> Invalid object 0:000> !dumpheap 026ae494-100 026ae494+100 Address MT Size 026ae480 00373534 16 026ae490 001cdb38 16 Free 026ae4a0 005dc838 4012 total 0 objects Statistics: MT Count TotalSize Class Name 00373534 1 16 OverlappingObjects.ReferenceHolder 001cdb38 1 16 Free 005dc838 1 4012 System.Int32[] Total 3 objects
What have we here? Our object lies in the range [026ae490…026ae4a0) which is attributed to a free object; i.e. the GC has reclaimed this memory for other uses (and we’re lucky not to see some other object already in this space!).
Moreover, the reference we have is at a four-byte offset from the object’s former resting place—and we obtain this reference from a valid instance of the ReferenceHolder class. Now here is a likely scenario that explains this turn of events:
I would like to reiterate that this access violation is a fairly optimistic outcome. Things could have been much, much worse if another valid object was allocated in the free space, and the GetHashCode method call would magically be invoked on that object. Another alternative is that a large object would occupy the space both before and after the reclaimed memory, and then the invalid reference would actually point in the middle of a valid object, producing the effect of objects overlapping in memory!
Below is the code required to reproduce this scenario. Because it uses memory offsets that may change between CLR versions and OS flavors, to repro you would need a Windows 7 64-bit OS and compile the code as .NET 4.0 Release 32-bit.
namespace OverlappingObjects
{ [StructLayout(LayoutKind.Sequential)] class SomeObject { public uint X; public uint Y; ~SomeObject() { Console.WriteLine("Finalizer"); } } [StructLayout(LayoutKind.Sequential)] class ReferenceHolder { public uint Marker; public SomeObject TheReference; } class Program { static void Dismantle(int[] arr) { GCHandle gch = GCHandle.Alloc( arr, GCHandleType.Pinned); IntPtr ptr = gch.AddrOfPinnedObject(); const int OFFSET = 8 + 4000; Marshal.WriteInt32(ptr, OFFSET, Marshal.ReadInt32(ptr, OFFSET) + 4); gch.Free(); } static void Main(string[] args) { Console.ReadLine(); int[] arr = new int[1000]; ReferenceHolder holder = new ReferenceHolder(); holder.Marker = 0xCAFECAFE; holder.TheReference = new SomeObject {X = 0xDEADBEEF, Y = 0xBADF00D}; int[] arr2 = new int[1000]; Dismantle(arr); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); holder.TheReference.GetHashCode(); Console.WriteLine("MAIN DONE"); Console.ReadLine(); GC.KeepAlive(holder); GC.KeepAlive(arr); GC.KeepAlive(arr2); } }
}
A.)
This. | http://blogs.microsoft.co.il/blogs/sasha/archive/2011/05.aspx | crawl-003 | refinedweb | 1,003 | 57.57 |
This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.
If linking against Glibc with a compiler for which the __GNUC__ macro is not defined, problems arise when including header files that use the __restrict or __inline keyword and when including uchar.h. Glibc strips __restrict from the prototypes of C library functions in this case. This is undesirable if the compiler is a C99-compliant compiler, because C99 includes the restrict keyword and uses it in the declaration of a number of functions in the C library. While this is broadly correct, lack of this information can have undesirable effects on analysis tools. The same thing occurs with the __inline keyword, which is also defined in C99 but stripped if the compiler is not GNU C. Here we except the case where the compiler declares itself to be C99-compliant from these checks in order to allow better C99 compliance for non-GNU-C compilers which link against Glibc. Glibc defines char16_t and char32_t in uchar.h as __CHAR16_TYPE__ and __CHAR32_TYPE__ when the __GNUC__ macro is defined, but when linking against Glibc with a different compiler, these types are not defined at all, which is a violation of C11 sec. 7.28 paragraph 2, as well as a syntax error because these types are used in the prototypes of functions declared later in the file. According to this section of the standard, these types must be defined in this header file and must be the same type as uint_least16_t and uint_least32_t, which are defined in stdint.h as "unsigned short int" and "unsigned int" respectively. Here we modify the header so that if __GNUC__ is not defined, we still provide these typedefs, but we obtain them from bits/stdint.h, where they are defined to be equal to uint_least16_t and uint_least32_t, if __CHAR16_TYPE__ and __CHAR32_TYPE__ are not defined by the compiler. --- I had trouble testing this patch because I ran into unrelated errors in the test suite. No tests seem to fail on my machine after the patch that were passing before, however. It seems to happen because it can't dynamically link against libgcc_s, but I'm not 100% sure what the correct way to pass that to make check is. Can someone point me to where this documentation is? --- Changed from previous version: * Updated patch description based on comments on mailing list. * Added a bits/stdint.h which defines __uint_least16_t and __uint_least32_t and which is included from stdint.h and uchar.h. I didn't move stdint.h out of sysdeps because I wasn't sure how controversial that would be, but I can do that in a third version of the patch if need be. I was under impression that the issue was that uchar.h was outside sysdeps and could not directly assume a particular version of stdint.h, but that assuming that whatever particular version of bits/stdint.h you had would define a certain type, and including that header from outside sysdeps should be fine. If this is not the case, apologies, just let me know. --- 2016-01-28 Dwight Guth <dwight.guth@runtimeverification.com> [BZ #17979] * wcsmbs/uchar.h (char16_t, char32_t): Define types if __GNUC__, __CHAR16_TYPE__, or __CHAR32_TYPE__ are not defined. * sysdeps/generic/bits/stdint.h: Created. * sysdeps/generic/stdint.h (uint_least16_t, uint_least32_t): Defined based on types from bits/stdint.h. [BZ #17721] * misc/sys/cdefs.h (__restrict, __inline): Define as keywords if __GNUC__ is not defined but __STDC_VERSION__ is at least C99. --- diff --git a/misc/sys/cdefs.h b/misc/sys/cdefs.h index 7fd4154..af23ff7 100644 --- a/misc/sys/cdefs.h +++ b/misc/sys/cdefs.h @@ -69,8 +69,11 @@ #else /* Not GCC. */ -# define __inline /* No inline functions. */ - +# if defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L +# define __inline inline +# else +# define __inline /* No inline functions. */ +# endif # define __THROW # define __THROWNL # define __NTH(fct) fct @@ -360,7 +363,11 @@ /* __restrict is known in EGCS 1.2 and above. */ #if !__GNUC_PREREQ (2,92) -# define __restrict /* Ignore */ +# if !defined __GNUC__ && defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901L +# define __restrict restrict +# else +# define __restrict /* Ignore */ +# endif #endif /* ISO C99 also allows to declare arrays as non-overlapping. The syntax is diff --git a/sysdeps/generic/bits/stdint.h b/sysdeps/generic/bits/stdint.h new file mode 100644 index 0000000..ee63a2a --- /dev/null +++ b/sysdeps/generic/bits/stdint.h @@ -0,0 +1,29 @@ +/* uint_least16_t and uint_least32_t definitions + Copyright (C) 2016 _BITS_STDINT_H +#define _BITS_STDINT_H 1 + +/* uint_least16_t and char16_t must be the same type, as must + uint_least32_t and char32_t. We define here a reserved identifier + for these types so that they will always remain the same type. */ + +typedef unsigned short int __uint_least16_t; +typedef unsigned int __uint_least32_t; + +#endif /* bits/stdint.h */ diff --git a/sysdeps/generic/stdint.h b/sysdeps/generic/stdint.h index 4427627..2f4ebd2 100644 --- a/sysdeps/generic/stdint.h +++ b/sysdeps/generic/stdint.h @@ -25,6 +25,7 @@ #include <features.h> #include <bits/wchar.h> #include <bits/wordsize.h> +#include <bits/stdint.h> /* Exact integral types. */ @@ -74,8 +75,8 @@ typedef long long int int_least64_t; /* Unsigned. */ typedef unsigned char uint_least8_t; -typedef unsigned short int uint_least16_t; -typedef unsigned int uint_least32_t; +typedef __uint_least16_t uint_least16_t; +typedef __uint_least32_t uint_least32_t; #if __WORDSIZE == 64 typedef unsigned long int uint_least64_t; #else diff --git a/wcsmbs/uchar.h b/wcsmbs/uchar.h index ce92b25..875919a 100644 --- a/wcsmbs/uchar.h +++ b/wcsmbs/uchar.h @@ -30,6 +30,8 @@ #define __need_mbstate_t #include <wchar.h> +#include <bits/stdint.h> + #ifndef __mbstate_t_defined __BEGIN_NAMESPACE_C99 /* Public type. */ @@ -39,14 +41,16 @@ __END_NAMESPACE_C99 #endif -#if defined __GNUC__ && !defined __USE_ISOCXX11 +#if !defined __USE_ISOCXX11 /* Define the 16-bit and 32-bit character types. Use the information provided by the compiler. */ # if !defined __CHAR16_TYPE__ || !defined __CHAR32_TYPE__ # if defined __STDC_VERSION__ && __STDC_VERSION__ < 201000L # error "<uchar.h> requires ISO C11 mode" # else -# error "definitions of __CHAR16_TYPE__ and/or __CHAR32_TYPE__ missing" +/* Same as uint_least16_t and uint_least32_t in stdint.h. */ +typedef __uint_least16_t __CHAR16_TYPE__; +typedef __uint_least32_t __CHAR32_TYPE__; # endif # endif typedef __CHAR16_TYPE__ char16_t; | https://sourceware.org/ml/libc-alpha/2016-02/msg00001.html | CC-MAIN-2018-30 | refinedweb | 987 | 59.9 |
Please refer to the errata for this document, which may include some normative corrections.
See also translations.
Copyright © 2011-namespace” in the subject, preferably like this: “[css3-namespace] CSS Namespace Test Suite has been developed during the Candidate Recommendation phase of this CSS Namespaces specification. An implementation report is also available.
This document is the same as the previous, Proposed Recommendation version, except for editorial changes to the front matter, and updating of references.
not a valid
style sheet..
If a namespace prefix or default namespace is declared more than once only the last declaration shall be used. Declaring a namespace prefix or default namespace more than once is nonconforming.] Note this means that. | http://www.w3.org/TR/2011/REC-css3-namespace-20110929/Overview.html | CC-MAIN-2015-27 | refinedweb | 114 | 50.43 |
Man Page
Manual Section... (3) - page: asinf
NAMEasin, asinf, asinl - arc sine function
SYNOPSIS
#include <math.h> double asin(double x);
float asinf(float x);
long double asinl(long double x);
Link with -lm.
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
asinf(), asinl(): _BSD_SOURCE || _SVID_SOURCE || _XOPEN_SOURCE >= 600 || _ISOC99_SOURCE; or cc -std=c99
DESCRIPTIONThe asin() function calculates the principal value of the arc sine of x; that is the value whose sine is x.
RETURN VALUEOn success, these functions return the principal value of the arc sine of x in radians; the return value is in the range [-pi/2, pi/2].
If x is a NaN, a NaN is returned.
If x is +0 (-0), +0 (-0) is returned.
If x is outside the range [-1, 1], a domain error occurs, and a NaN is returned.
ERRORSSeeC99, POSIX.1-2001. The variant returning double also conforms to SVr4, 4.3BSD, C89.
SEE ALSOacos(3), atan(3), atan2(3), cas | http://linux.co.uk/documentation/man-pages/subroutines-3/man-page/?section=3&page=asinf | CC-MAIN-2014-10 | refinedweb | 161 | 65.01 |
This article is a demo on developing MVVM Application Without any Frameworks.
The new framework to hit WPF world is the MVVM framework. MVVM stands for Model - View - ViewModel. I will not explain the theory stuff here, for that you can refer this article. We will build this MVVM application WITHOUT using any frameworks. Just our own good'ol C# code.
In short,
List<>
ObservableCollection<>
So lets get started. Fire-up Visual Studio 2011. Click on new Project. Select Metro and Blank Application. Hit Ok.
The first screen that you'll get is the default metro UI. Its nothing much than a blank black background. No buttons. Nothing. The code-behind contains few default lines of codes and a lot of comments. We will be using the code-behind only once, to write a single line of code in the constructor.
Now create 2 folders in the solution. Model and ViewModel. The Model folder will contain our "class" and ViewModel will contain, well, class but these classes will represent a collection of the Model's classes and will also contain code to wire the View with our ViewModel.
Next, we write our Model. For this application, I'll choose a simple Contact class having a Name and an Email and a GUID to identify it uniquely. So right click on Model folder, Add -> Class. Name the class as Contact.cs. Import the namespace System.ComponentModel, since we will be using the INotifyPropertyChanged interface. This will allow the ViewModel to communicate to the Model if something has changed. I'll keep the discussion simple.
System.ComponentModel
INotifyPropertyChanged
After the Model, lets now focus on ViewModel. Right-click on the ViewModel folder, add -> class. Since this ViewModel will work with our Contact.cs Model, we'll name it as "ContactViewModel.cs". Click Ok.
Now pay close attention, this is where the MVVM magic happens. Our ContactViewModel implements the INotifyPropertyChanged interface, this time to notify the changes in properties to the View and vice-versa. Import System.ComponentModel and implicitly implement INotifyPropertyChanged.I'll make it simple here on how-to construct a basic ViewModel.
ContactViewModel
ObservableCollection<Contact>
Contacts
System.Collections.ObjectModel
Mvvm2_Basic.Model
MyCommand
ICommand
Action<T>
Our View is a very simple UI. As mentioned earlier, we only have 5 buttons on our View. So lets go ahead and create our View. For our View, we will use the BlankPage.xaml. Open BlankPage.xaml.cs (the code-behind). We need to tell our View that whatever events will be raised on the view, they will be handled by our ViewModel.
The DataContext links the current UI with our ContactViewModel.
Now lets create our 5 buttons. They will be "Refresh", "Add New", "Save", "Update", "Delete"
Note the "Command" property on every button. The command property tells the View where to look for, when that button is clicked. In our Command property, we specify the ViewModel property that we want to invoke. That ViewModel property will then invoke the appropriate method.
Command
You should've understood by now that its the head-ache of the ViewModel property to invoke the appropriate method. This separates the concern of the UI about reacting to events. This entire setup allows us to test each "part" separately.
So when "Save" button is clicked, SaveCommand property is invoked. The SaveCommand property from ViewModel has the signature of OnSave() method passed in it. Hence ViewModel's SaveCommand will finally call the OnSave() method.
SaveCommand
OnSave()
You can see in the output window when each method is called, it outputs some text that we've written in Debug.WriteLine in every method.
Debug.WriteLine
Very well. This completes the basic skeleton for our MVVM XML Metro application. In the next series, we will see how to perform CRUD operations using XML file. Till then stay tuned.
If Images in this article isnt proper then please Download the. | http://www.codeproject.com/Articles/391783/An-Address-Book-Application-Made-in-MVVM-For-Metro?fid=1720626&df=90&mpp=10&sort=Position&tid=4262903 | CC-MAIN-2014-35 | refinedweb | 647 | 60.92 |
Search Feature
More FAQs about Plumbing Marine Systems 3
Related Articles: Plumbing Marine Systems, Plumbing
Return Manifolds,
Refugiums,
Related FAQs: Marine Plumbing 1, Marine Plumbing
2,,
Don't you wish you had one of these at home? Not Bob, the floor drain! Here
at Pacific Aqua Farm's new facility in Los Angeles
Re: Live Rock & Large Predators
Thank you Steven for your quick response, especially about the two-pump/two-sump idea. Man, I guess I would have messed things up. Two follow-up
questions, and please forgive my lack of plumbing expertise: The two sumps are of necessity moderately sized as they are both squeezed underneath my tank in its cabinet. One is a Rubbermaid-type 18 gallon container, while the other is a former Amiracle 300SB wet-dry. If I follow your lead and run a line between the two sumps (feeding one sump's water into the other), does the water have to "fall" downward into the second sump even if it is being pulled through by a pump that is stationed after the 2nd sump?
<It depends on what you want to do, but no they do not have to fill one to drain to the other. They can both be drilled a few inches up from the bottom of each and have bulkhead fittings connected by PVC pipe. This will create, in effect, one large sump where the water levels will fluctuate in both "sumps" as per evaporation. If you wanted to create a static level for a refugium in one sump, it would be best to elevate one have it fill and drain into the second.>
I assume not, but I am a plumbing dunce, after all, so I ask... Or can the line simply be (for example) a level one that is 1" off the bottom on both sumps?
<Yes, that will work.>
Next, will my new Iwaki MD40RLXT (1200GPH at zero head) do a very good job pulling all this water through these two sumps from underneath my cabinet and back over the top of my 180?
<Use at least 1" bulkheads or larger if you can get them, but they should be fine.>
FYI, I will add some other pump or powerheads) for more circulation later on down the road.
<Ok>
Thank you again, & have a great week. Steve (I'm not Pro, just Amateur)
<Very funny. -Steven Pro>
Durso Standpipe
Hi Guys
I -- >>
Sump for Eclipse System 12
Bob,
<Steven Pro here with the follow-up.>
Thank you for your help. The project went well! The Eclipse 12 tank is
drilled, plumbed, and my new CPR SR2 is already producing some high quality "gunk".
<Great!>
I do have another question though. My drain line seems to develop
some
most>
Water flow for SPS tank
First let me add my name to the list of those who you've helped countless times with your wisdom. The number mistakes I have avoided by reading this
over the past year is shocking ;-)
<our purpose indeed! thank you for sharing>
I am setting up a new 60x18x24 acrylic tank which will eventually be home to mostly SPS with some LPS corals.
<do try to avoid the mix as much as possible... better to feature one group for better success in the long run>
The tank is from Advance Aqua Tanks (who generously label it a 125R ;-). I have read many comments in the daily Q&A
about water flow and most recently in Anthony's book, and I am attempting to heed the advice. I suspect that even though I "upgraded" the tank to
include a second corner overflow, that it remains inadequate.
<indeed a common flaw with many tank designs for reef purposes>
Before I reduce my options by filling the tank I would like your advice on how to
improve. My current setup consists of two Iwaki MD30RLT, pumping from the sump, with
each dedicated to one of the two returns (one will also pass through a chiller).
<do confirm with chiller specs that this flow will not be too high... else tee a bleeder for the chiller on a sump loop and send the rest topside>
The returns are through a 3/4" bulkhead in the bottom of the tank in the overflow chamber and then piped finally to a 1/2" bulkhead with a
loc-line Y and fan nozzles.
<wow... that is a somewhat significant reduction on the return (down to 1/2")... you will gain some velocity but lose some volume I suspect>
The overflows include Durso standpipes
<excellent>
connected to a 1" bulkhead and then to the sump. The manufacturer says the overflows will each do "300-750 gph flow rate" which seems to match up with
the pumps.
<hahahhahhaa..... er, I mean. I think the manufacturer meant to simply say 300pgh. A 1" bulkhead on a silent (relatively) gravity overflow runs about 300gph when the lines are new, clean and have very few elbows
to impediments (valves, fitting, etc). Operating at dangerously high capacity (creating a siphon and making a sucking sound louder than cash coming out of Enron execs portfolio)... a 1" bulkhead MIGHT run near 600pgh. Quite frankly... it would be ironic to see you apply two Iwaki pumps and reduce their flow in half to keep up with these two 1"
bulkheads when one Iwaki would suffice (unless you drill more holes for overflows)>
This gives me about 1000 gph combined. I had planned to use 4xMaxijet 1200 powerheads with a wavemaker in the tank, but would rather
consider supplementing or replacing these with a closed-loop.
<heck ya! powerheads suck for many reasons... a necessary evil at best. When ever possible, use one or two large external water pumps with a topside manifold to do most of the work>
I have done much research on how to create more natural flows for the SPS, but admit I have come up with no solution with which I am comfortable. It
seems to me that devices like Sea-Swirls will do very little to create random, non-laminar flows anywhere but the top of the tank.
<agreed... quite frankly... most of the wave-maker/timing devices are just toys and IMO do not serve the tank well. Strategic FULL time flow (producing random turbulent patterns) is much better than the on-again, off-again motion of so many clever and
overpriced devices. Just another toy, expense and burden on the electric bill (not to mention a contribution with the powerheads to making the
power strip in back look like a Rasta's dreadlocks)>
Finally ;-)) the questions:
1. I am thinking about drilling four new holes in the tank, to keep the holes in the existing overflows (and protect from fully draining the tank in
case of a bulkhead leak),
<excellent and agreed!>
I would be limited to 4 x 3/4" bulkheads, two in and two out for a closed loop driven by another pump (similar or same
Iwaki). Will this be sufficient in terms of volume, or should I ignore the risk of a future leak and drill the bottom outside of the overflows with larger diameter?
<not sure I follow here... are you talking about a third pump? Please reply with total number of overflow holes, total number of return holes, and total number of pumps>
2. Do you have any specific advice on what to do with the output of the closed loop, in terms of orienting the flows, or use of hardware such as
Ocean Currents to make the flows more random. I intend to return the output of closed loop somewhere near the middle of the tank depth.
<yes...simple and very effective. Have four to six outlets at the surface of the water with a small length of adjustable lock-tite tubing. The adjustable tubing will allow you to change directions as corals grow, get removed, etc. Direct all as necessary (opposing) to converge and simply create dynamic random turbulent water flow... your goal is of course to reduce or eliminate the
possibility of dead spots or decidedly laminar flow (unless keeping special animals that need it...sea fans, black sun coral, etc)>
Many many thanks, Michael
<best regards, Anthony>>
Marine Set-Up
WWM Crew,
<Howdy>
I think I have decided what to do with my Aquarium, and I am just looking for a touch more feedback.
<Okay>
I am going to keep the display tank the way it is, but include a sump(30 gal) and refugium(20gal) in the stand under the tank. I am hoping to use
a self-leveling siphon to overflow from my display tank into the sump, and then pump it back up from underneath, do you know if these systems
work alright?
<Can... always dangers... of inadvertent plugs... overflows... best to build in redundancy (pans under tank stand... cheap carpets, renters insurance... not have the siphon extend all the way to bottom...>
Image from
And then run a refugium off of the sump for lower flow rate, I was also planning on remoting all my equip to the sump (heater, chem. filtration,
skimmer) if this would work out.
<Should... though I like other constant level "box" designs. Please see the graphics on CPR's site here:>
In the refugium I was planning on having a deepish sand bed, live rock, and all the fun algae and critters etc, and keep the sump for all the
mechanicals (is there a better way to do this?)
<A bigger sump, sub-divided... or more than one sump... added lighting... Please read through the numerous FAQs, links on the topic posted on WetWebMedia.com>
in my display tank I am planning on keeping the current setup with the crushed coral, but adding live rock and some powerheads for circulation,
since it will be a FOWLR system, how much circulation do fish enjoy?
<Different species... quite different amounts... almost all systems are less-circulated than wild environments...>
Anyhow, I would love to get any input you may have Thanks, Chris
<Read through WWM and enjoy, share my friend. Bob Fenner>
Water level
My tank has a corner overflow. The water level in the tank is too high, brushing up against the glass cover. This is a minor annoyance more than a big problem, but I want to get around to finally fixing it. The simple solution seems to be cutting deeper (lower) water access grooves into the acrylic overflow,
<agreed>
perhaps doing so carefully with a metal file. Is this my best bet or is there a better way that my simple little mind is not seeing?
<alas, no... agreed. The high dam of the overflow is an obstacle>
I obviously don't want to goof up and crack the overflow. Thanks for your advice. Steve The Dimwitted Aquarium Repairman.
<best regards, the vertically challenged aquarist, Anthony>
Plumbing
Hello there. <<Hello.>> Had a couple of questions regarding my sump size and return pump size. I have a 125 gal. fish-only tank with a 35 gal. sump (using only about 16 gals.), and a RIO 3500 gal. (using about 30 gals.), Also, getting two Lifereef models that feature the "U" tube, (Instead of just one). And having two Rio 3500's as return pumps.
Will this much overflowing be too much? <<No... more is better when it comes to circulation.>>
Should I stick with only one overflow? <<If you want more circulation, you'll need this additional overflow.>>
Will this much return pump be too little/or too much? <<The tank will only overflow as much as you pump into it, so it will match up just fine. As for too much/little - there's really no practical way to
duplicate the currents of the ocean so... as long as you're not blowing things out of the tank, all is fine.>>
And would you recommend getting a single pump, but bigger, like a Little
Giant or something that can produce over 1000 GPH? <<Is your choice, having two separate pumps pretty much guarantees that you will have some flow should one of the two pumps fail.>>
Keep in mind that its only a fish tank, but in a couple of years I am
thinking of going to a full reef system, (if this makes a difference).
Your help would be greatly appreciated, thanks. <<Even in fish only, the fish really appreciate high circulation.>>
mulletboy, Riverside, California
<<Cheers, J -- >>
Plumbing
Hello there. I had a couple of questions regarding my sump size and return pump size. I have a 125 gallon fish-only tank with a 35 gallon sump (using only about 16 gallons), and a RIO 3100 gallon (using about 30 gallons). Also, getting two Amiracle overflow box models that feature the "U" tube. And having two Rio 3100's as return pumps. My questions are as follows;
1. Will this much overflowing be too much?
<Should be approximately 1500 gph, just about right.>
Should I stick with only one overflow?
<This depends exclusively on what the Amiracle overflows are rated at. I am not familiar with they as I exclusively used drilled tanks.>
2. Will this much return pump be too little/or too much?
<Just about right.>
3. And would you recommend getting a single pump, but bigger, like a Little Giant or something that can produce over 1000 GPH?
<I prefer to use two external pumps, in case one ever breaks the other is still working.>
Keep in mind that its only a fish tank, but in a couple of years I am
thinking of going to a full reef system, (if this makes a difference).
<Depending on corals kept, you may still need additional current.>
Your help would be greatly appreciated, thanks. Riverside, California
<You are welcome. -Steven>
Need help with plumbing
Hay Bob : We have just got a Mandarin 1 Biological filter from a friend and it came in a lot of pieces. Would you have any plumbing diagrams for the
mandarin 1?
<Sorry, I have never even heard of it. I would search for the company using Google or Yahoo.>
Is there any way to run 2 reef tanks? We have a 55gallon reef tank setup and are starting another 45 gallon. Can it run both tanks?
<It is possible to run two tanks, or more, off of one sump. We may have some diagrams of this in the business section. Otherwise, I know Martin Moe has written and drawn about systems such as this in his "Marine Aquarium Reference" and "Breeding the Orchid Dottyback.">
Thanks, Steve Barry
<You are welcome. -Steven Pro>
Plumbing reef aquarium diagram
Hi all,
<cheers, mate... Anthony Calfo in your service>
I found the diagram at and have a question. If I do not use the surge device, then where should the return go (yes I know, IN THE TANK, approximately WHERE <G>)
<heehee... yes, my friend. It is simply unnecessary if you choose not to employ a surge device. Bypass it entirely>
thanks don
<best regards, Anthony>!!!
Den
<<You too. Cheers, J -- >>
John Guest Speed fit fitting
<<Greetings... >>
Hello friends, I'm curious if any of you are familiar with this John Guest Speed fit
fitting? <<I am. It is a brand name and unique type of fitting for small tubing that does not require a
collect>
Return Pump on 72g
Hello,
<Howdy>
In an attempt to reduce some powerheads (and heat) in my 72g tank, I'm considering upgrading my Mag 7 pump to a Mag 9.5. My tank has one
corner overflow and there is 5 feet of head pressure from the sump. My current pump is pushing only around 375 gph with this amount of head
pressure. Would a 9.5 be too much for my overflow to handle? I believe it would actually push about 700 gph. If it is too much, would a ball
valve work to reduce it slightly?
<Mmm, there's a few questions to ask back... what's the diameter of the present plumbing? You may well not be able to force much more through this line due to induced drag. Do you intend to add another discharge line? Will there be problems with linear flow through these lines... i.e. can you direct the flow such that it won't dangerously blast the livestock about? The overflow, will it supply the desired intake water? You may need to rig a transit-volume sump of a sort to
accommodate the excess water in play (this can be a surprising volume once spread out on a floor with the power off, pump failure.). I would not rig up a plumbing/pump configuration with the intent to have to throttle it down much (like with a ball valve) if I could avoid it... due to waste heat, electrical consumption considerations. Bob Fenner>
Thank you, Karen
Hi Anthony, Thanks for the quick reply -
<my pleasure>
I certainly wish Pittsburgh was somewhat closer to Albany!.
<yes... we should all buy an island so that reefkeepers can live in peace and near fellowship... how about Australia. Lets start a fundraiser to buy it>
I am planning on designing the circulation setup to work without powerheads, using two strong pumps (Mag18's or above), and tee'd lock lines to do the job. There certainly is some controversy up here in regards to attempting complete circulation for an SPS/Clam tank running through the sump.
<agreed as with most anything among SPS keepers>
Getting that kind of volume (2500 - 3000) gph down twin drains, and running all this through a sump scare some.
<yes...true, in fact. My top shelf recommendation is not to d this at all. However... not everyone can afford top-mounted Tunze
Turbelles water pumps on
solenoids for the main display at $200-300 each <G>>
The thought is that the sump is used primarily for filtration (skimmer) and some circulation, the rest coming from water circulated through powerheads.
<I have many criticisms with powerheads" heat generating, interior noise (for fishes), stray voltage, poor longevity, few with grounded plugs, etc>
But I want to try your "nirvana" plan, as I do not like powerheads for many reasons.
<yes... a directional manifold overhead (swivel nozzles) can be quite inexpensive, fun and effective>
Given that, in a twin overflow 150gal tank, what size drains would you recommend?
<At least 2-2" drains perhaps more. Lets consult Rainbow Lifeguard or like bulkhead mfg for specs to compare against your pumps and head pressure>
I will try your open topped tee's also to muffle noise - thanks.
<good... not perfect, but inexpensive and simple if you are not a perfectionist>
My concern regarding the 2500-3000 gph hitting the sump was not so much noise, as I will release the output under water, but turbulence causing bubbles. Not sure if this is even a problem...( I keep thinking of those
jet boats that use water thrust instead of propellers on our lakes up here!).
<not a problem at all as long as they are not aspirated through the return pumps for lack of dissipation/baffles. Even then not always a problem>
Without getting too technical and taking up more of your time, why is discharging a calcium reactor's low PH output into a highly aerated skimmer box not a good method for
off-gassing Co2? I figured this would be similar in theory as when one aerates fresh RO/DI water.
<no sir... RO water is demineralized (no Calcium, etc) and aeration essentially just
off-gasses the carbonic acid. A reactors effluent however is rich with calcium, and aerating such water will produce insoluble calcium
carbonate (!) much like the "skin" on the surface of a vessel of Kalkwasser exposed to air. No aerating limewater or Calcium reactor effluent <smile>!>
Thanks again Anthony. Steve
<best regards, my friend. Anthony>
Plumbing Question
Hi Anthony,
<Cheers, Steve>
I would like to direct this to you again, as you answered a related question recently of mine regarding mechanical filtration. I am in the early stages of putting a 150gal reef tank together (already have a 75gal reef tank up and running fine for the last two years, but bigger is better !). My concern is with the dual overflows processing water at 15-20 times tank volume, all "crashing" into the planned 55gal sump below the 150.
<sound is very easy to dampen... a open topped tee on end (extended if necessary) at the top of the tank for each/any drain... output in sump released under water and filter batting/pad in top of tee above to muffle noise. Crude but very inexpensive and effective>
The 75gal uses a 25 micron bag to catch bubbles, and probably slow things down somewhat. Based on your earlier thoughts, I know you do not like the 25 micron bag setup.
<wow... I really never liked this idea for general purpose (but I love it for the maniacs <engineers...same thing> that will rinse this bag almost daily)>
From a plumbing perspective, would you have the water coming from the overflows piped directly into the sump, or would you set up some type of baffling system, like a stand pipe, to catch it and then overflow into the sump? Otherwise, it seems that a lot of water will be entering the sump, and at pretty good speed.
<Others would argue that this is a great opportunity for aeration/O2 saturation. Is your concern noise or something else?>
Right now the two overflow drains are planned for 1.5 inches each. Do you think this is enough to handle the volume of water necessary to keep SPS and clams happy (was planning on 15-20 times utilizing twin Mag18 pumps) ?
<not even close to being able to handle that kind of flow if your goal is to reduce/avoid powerheads
I the main display (which I love/agree with... powerheads are awful for so many reasons!!!)>
Another quick question if I may. I am considering the new Aqua C EV240, or the Euro Reef CS 8.2 as my skimmers. Putting you on the spot - how would you choose?
<For a substantial savings in cost and only slightly more maintenance/supervision if any at all... the Aqua C is a better deal. However, I am reticent to adding even the tiniest extra maintenance chores to my already busy schedule. So... I would spend the extra and Buy the Euroreef. Which is your situation? Too busy to care or more sensible than I am? Ha!>
The EV240 has a fitting for calcium reactor discharge directly into the skimmer. Do you see this as effective in raising the PH of the reactors output, possibly giving an advantage to the Aqua C product?
<actually a disadvantage to off gas it this way. Advantage: Aqua C. A better route for the calcium reactor is a second inline chamber to raise the pH. I think most every Ca reactor should run two chambers inline>
Finally, the marine club you guys are in in Pittsburgh sounds like a place I would love to be.
<its a great gang!>
Do you have members living some distance from Pittsburgh who still find it "works" being a member? I live in upstate NY, near Albany. Would it make sense to look into joining, even with my distance from you guys?
<we've recently lost our journal editor and don't have anyone filling in just yet! So... truthfully, until we get a quality newsletter back on par... perhaps not <G>! Heehee... still, looking forward to chatting more with you>
Thanks Anthony. Steve (who has your book - # 364)
<outstanding... thank you, my friend!>
A tough Plumbing Problem
Dear Bob and Friends,
My 90 gallon reef is now 18 months old and I have had very few problems thanks to Bob's coaching, books, the web site, and an almost daily reading of other peoples problems and solutions. One thing I have never solved is the cloud of tiny bubbles from my incoming filtered water.
A 40 gallon (net) two chamber filter sump with Turboflotor, carbon, auto top off, valved optional Ocean Clear, and U/V and an in-series 30 gallon refugium full of rock and
Caulerpa are in the basement. Also an R/O/D/I unit feeds a 30 gallon salt mix tank and a 10 gal.
Kalk mix tank feed the system.
A High pressure Iwaki pump with 1 in. intake from a chamber in the filter sump moves 700 gph upstairs through a one way valve and into the show tank by way of a manifold with three 3/4 in. outlets moving water from right to left on the surface.
The sump chamber is absolutely free of any bubbles as the Turboflotor, etc. all discharge into a separate chamber. The bubbles must either originate in the Iwaki or in the 1 in. PVC line. All pipe joints are well glued with an outer coating of silicon for good air tightness.
I give up on stopping the source of the bubbles and am hoping you might suggest something that can be done at the outlet into the show tank?
This is a living room acrylic tank and I can't put any thing above or beside it. I can build most anything from acrylic and PVC.
<Perhaps an internal "hang on box" of dark material (black Plexi?) with an open cell foam, filter matting... to 'catch' the bubbles, coalesce them... With slots cut into the upper lip of the box to let the water out...>
Except for this ongoing bubble problem, I feel that I have a perfect system -- never had a chemical problem or any disease process whatsoever. I keep a variety of fish, soft and hard corals. No anemones, I lost one probably due to the air bubbles.
Howard
<Do check out "Oz Reef" on the marine links of WetWebMedia.com for more DIY possibilities, ideas. Bob Fenner>>
Schematic
Bob,
What is the best/most convenient way for me to get a plumbing schematic to you for a once-over? I am concerned with delivery rates and the sump
setup the schematic has all pump and pipe specs). Would a Word or PowerPoint attachment be acceptable?
<Sure... or a fax, 858-578-7372, or mail: 8586 Menkar Rd., San Diego, CA 92126... if you're as handy as I am with such programs... or? Bob Fenner>
Thanks,
Mike Stewart
****Faxed it out today, peruse it at your leisure and let me know what you think; no real hurry. Thank you. MLS ****
<Got it... good to see you have sufficient space all the way around... good volumes, placement, construction on both the sump and
refugium... I would place a "pad" of batting material (Dacron filter "wool") in the
Bioball splashdown area and leave out the plastic media. Do opt for the larger (model 1250) Eheim pump. Not shown, but want to mention to add some internal pumps
(powerheads are fine) for inside the tank for additional circulation, aeration. Nice to see some images once you've got all of this together. Be chatting, Bob Fenner>
Re: Faxed Schematic
Thank you!!! I will send some pics when completed.
<Real good. Looking forward to them. Bob F>
Michael L. Stewart | http://www.wetwebmedia.com/pbfaqmar3.htm | crawl-001 | refinedweb | 4,546 | 72.26 |
NVMECTL(8) NetBSD System Manager's Manual NVMECTL(8)Powered by man-cgi (2021-06-01). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias.
NAME
nvmectl -- NVM Express control utility
SYNOPSIS
nvmectl devlist nvmectl identify [-x [-v]] device_id nvmectl logpage [-x] [-p page_id] [-v vendor-string] [-b] device_id|namespace_id nvmectl power [-l] [-p power_state] [-w workload_hint] device_id nvmectl wdc cap-diag [-o -path_template] device_id
DESCRIPTION
NVM Express (NVMe) is a storage protocol standard, for SSDs and other high-speed storage devices over PCI Express. logpage The logpage command knows how to print log pages of various types. It also knows about vendor specific log pages from hgst/wdc and intel. Page 0xc1 for hgst/wdc contains the advanced smart information about the drive. Page 0xc1 is read latency stats for intel. Page 0xc2 is write latency stats for intel. Page 0xc5 is temperature stats for intel. Page 0xca is advanced smart information for intel. Specifying -p help will list all valid vendors and pages. -x will print the page as hex. -b will print the binary data for the page. wdc The various wdc commands.
EXAMPLES
nvmectl devlist Display a list of NVMe controllers and namespaces along with their device nodes. nvmectl identify nvme0 Display a human-readable summary of the nvme0 IDENTIFY_CONTROLLER data. nvmectl identify -x -v nvme0ns1 Display an hexadecimal dump of the nvme0 IDENTIFY_NAMESPACE data for namespace 1. nvmectl logpage -p 1 nvme0 Display a human-readable summary of the nvme0 controller's Error Informa- tion Log. Log pages defined by the NVMe specification include Error Information Log (ID=1), SMART/Health Information Log (ID=2), and Firmware Slot Log (ID=3). nvmectl logpage -p 0xc1 -v wdc nvme0 Display a human-readable summary of the nvme0's wdc-specific advanced SMART data. nvmectl logpage -p 1 -x nvme0 Display a hexadecimal dump of the nvme0 controller's Error Information Log. nvmectl logpage -p 0xcb -b nvme0 > /tmp/page-cb.bin Print the contents of vendor specific page 0xcb as binary data on stan- dard out. Redirect it to a temporary file. nvmectl power -l nvme0 List all the current power modes. nvmectl power -p 3 nvme0 Set the current power mode. nvmectl power nvme0 Get the current power mode.>. NetBSD 9.3 May 19, 2016 NetBSD 9.3 | https://man.netbsd.org/NetBSD-9.3/i386/nvmectl.8 | CC-MAIN-2022-40 | refinedweb | 387 | 58.99 |
27 February 2012 10:07 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
The 150,000 tonne/year PP facility, which is currently running at full capacity, obtains 70% of its gas feed from KNPC’s refining complex in Shuaiba, the source said.
“The KNPC refinery is shut because of maintenance works at one of the pipelines, so our FCC [fluid catalytic cracking] unit is unable to produce sufficient propylene to feed the PP unit,” the source said.
“Because of the reduced operating rates, we can only supply to our regular customers. We will reduce our quantities to spot markets such as southeast Asia and
PIC obtains the remaining 30% of its gas supplies from Equate, the source said.
PIC, which is a wholly-owned subsidiary of Kuwait Petroleum Corp (KPC), produces PP grades of raffia, fibre and biaxially-oriented PP (BOPP) film.
KNPC is a subsidiary of Kuwait Petroleum | http://www.icis.com/Articles/2012/02/27/9535949/kuwaits-pic-to-run-shuaiba-pp-unit-at-70-80-in-h1.html | CC-MAIN-2014-41 | refinedweb | 149 | 51.07 |
iText is a wonderful library if you want to generate PDFs in Java. It comes with a huge set of API to create/manage a PDF file. We already saw in our previous tutorial how to generate a pdf file in itext and also how to merge two pdf files using itext.
In this tutorial we will see how to generate Pie charts and Bar charts in Java using iText and jFreeChart library. First a brief note about jFreeChart.
JFreeChart is a free 100% Java chart library that makes it easy for developers to display professional quality charts in their applications. It gives a wide range of API to generate charts and graphs in Java.
Step 1: Download required Jar files
For this example we will need following jar files.
Download the jFreeChart jars from:
Step 2: Generating Pie Charts/Bar Graph using jFreeChart
Next we will use jFreeChart library and generate the pie and bar charts.
package net.viralpatel.itext.pdf; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.DefaultCategoryDataset; import org.jfree.data.general.DefaultPieDataset; public class PieChartDemo { public static void main(String[] args) { //TODO: Add code to generate PDFs with charts } public static JFreeChart generatePieChart() { DefaultPieDataset dataSet = new DefaultPieDataset(); dataSet.setValue("China", 19.64); dataSet.setValue("India", 17.3); dataSet.setValue("United States", 4.54); dataSet.setValue("Indonesia", 3.4); dataSet.setValue("Brazil", 2.83); dataSet.setValue("Pakistan", 2.48); dataSet.setValue("Bangladesh", 2.38); JFreeChart chart = ChartFactory.createPieChart( "World Population by countries", dataSet, true, true, false); return chart; } public static JFreeChart generateBarChart() { DefaultCategoryDataset dataSet = new DefaultCategoryDataset(); dataSet.setValue(791, "Population", "1750 AD"); dataSet.setValue(978, "Population", "1800 AD"); dataSet.setValue(1262, "Population", "1850 AD"); dataSet.setValue(1650, "Population", "1900 AD"); dataSet.setValue(2519, "Population", "1950 AD"); dataSet.setValue(6070, "Population", "2000 AD"); JFreeChart chart = ChartFactory.createBarChart( "World Population growth", "Year", "Population in millions", dataSet, PlotOrientation.VERTICAL, false, true, false); return chart; } }
In above code, we have created two methods that returns JFreeChart object. These methods creates charts using jFreeChart API. Note that we have used dummy data. In real example these values must be dynamically fetched from database or other data source.
Also note that the main method is still empty. We haven’t added yet the code to generate actual PDF file using iText API.
Step 3: Generate PDF with Charts/Graphs in Java using iText
Now its time to generate the actual PDF files. For this we will use iText library and pass it the graphs generated by jFreeChart library. Add following code in your java class.
public static void main(String[] args) { writeChartToPDF(generateBarChart(), 500, 400, "C://barchart.pdf"); writeChartToPDF(generatePieChart(), 500, 400, "C://piechart.pdf"); } public static void writeChartToPDF(JFreeChart chart, int width, int height, String fileName) { PdfWriter writer = null; Document document = new Document(); try { writer = PdfWriter.getInstance(document, new FileOutputStream( fileName)); document.open(); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(width, height); Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width, height); chart.draw(graphics2d, rectangle2d); graphics2d.dispose(); contentByte.addTemplate(template, 0, 0); } catch (Exception e) { e.printStackTrace(); } document.close(); }
In above code we have created a method writeChartToPDF() which take few arguments like jFreeChart object, width, height and filename and write a PDF files in that file.
This is ofcourse very preliminary example of adding pie charts in PDF using Java iText/jFreeChart. But atleast it gives basic idea of how to achieve this. Feel free to modify the above code and play around to generate different charts/graphs in PDF.
Excellent Tutorial. It’s Matches with my requirement. Very Very Thanks for Providing This tutorial
can u provide me a code to handle multiple edit button for each row of table .
i am using dispatch action of struts 1 , but not been able to set the hidden varibale dynamically to send it to next action.
Hi Viral,
A very useful article! Thanks a bunch. :-)
I am facing a technical problem and I wonder if you will be able to help me out. I am using iText 2.1.5 (I know a newer version exists) to generate pdf files. I am picking up text from database and putting it in the pdf file. The database text however has tags like “Bold” instead of good old “
<b>Bold</b>“.
Despite using HTMLWorker.parseToList, the text Bold” is printed as it is in the generated pdf. I see that tags are not in the tagsSupported list of HTMLWorker.
I have googled and checked many sites but nothing seems to be working so far. If I don’t find any solution, I will have to resort to parsing the strings by myself and replacing tags with appropriate html tags like
<b>, etc. I am hoping I don’t have to do that as it somehow feels inelegant.
Am I doing something wrong? Can you please help me out here?
Thanks a lot once again!
Swapna
I am sorry Viral. I didn’t realize the site will format my text as per the html tags I mentioned. I will post the relevant part once again.
The database text has tags like “span” with “style” set to “font-weight:bold;” or “font-style:italic” instead of using b, u or i like tags.
Hi Viral,
I am using iText and JFreeChart.
I have generated a chart and am using iText to save the chart as PDF.
When I save the PDF to filesystem, the file saves correctly, then when opened, shows chart without any problems.
But when I try to serve the pdf as response to request, it gives me error file does not start with %pdf-.
My code is below.
Can you help me out in resolving this problem, where I might have made any mistake?
Thanks.
Regards,
Venkata.
Appreciate your help.
response.setContentType("application/pdf");
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
try {
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
document.addTitle("Test PDF");
document.addAuthor("research");
document.addSubject("Demo");
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, mapper);
Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
chart.draw(g2, r2D);
g2.dispose();
cb.addTemplate(tp, 0, 0);
} catch (DocumentException de) {
System.err.println(de.getMessage());
}
document.close();
Thanks a lot for the tutorial. A small addition, you could replace the document line by the following to set the pdf size :
Document document = new Document(new Rectangle(width,height));
Hey can u tell me where i save this jar file??????
plz repli fast.
@pradeep, it doesn’t matter where you put the jar files, just make sure you add them to the classpath/buildpath.
@donc_oe
Thank u :)
can anyone help me for creating dynamic graph(live trading)
x axis shoul be current time and y axis value is to get from database……..
I have done x axis part in that i used thread and timeseries now i want to connect with database on y axis…………
plzzzzzzzz help
Thank u :)
good work.
Its really suited my requirement…..with partial changes like, instead using pdf html display and getting data from db to replace the hardcoded dataset values
Super Cool code man.Working perfect .Thanks.Keep it up.
Hello,
I want to Generate Pie Chart/Bar Graph in JSF;plz anybody help me!!!
Document document = new Document(PageSize.A4_LANDSCAPE, 10, 10, 10,
10);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
writer = PdfWriter.getInstance(document, baos);
document.open();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse(); document.add(new Paragraph(“Report:”, FontFactory.getFont(FontFactory.COURIER, 10, Font.BOLD,new CMYKColor(255, 255, 255, 255))));
Paragraph paragraph1 = new Paragraph();
paragraph1.setSpacingBefore(4);
document.add(paragraph1);
/*like wise content will be added to pdf document*/
document.close();
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat(“dd_MM_yyyy_HH.mm.ss”);
response.setContentType(“application/pdf”);
response.setHeader(“Content-disposition”,”attachment; filename=Batch_Report” + format.format(date)+ “.pdf”);
ServletOutputStream out;
try {
out = response.getOutputStream();
baos.writeTo(out);
out.flush();
out.close();
facesContext.responseComplete();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
By using the above iam able to create pdf file in jsf
Hi all, Can any one send me simple source code for generating a chart using database. and generating pdf using Database.
plz help me out bcz the itext is very new for me
thanks..
mail me @ [email protected]
May I also have a copy?
Great working code for JFreeChart + iText. Thanks a lot!
cannot compile it , teach me please !
i am downloading this program and jar files but it shows error.. at
chart.draw(graphics2d, rectangle2d);
wt we do…? pls help?
Hi Viral… Your article really helped me a lot.. ‘BIG’ thanks… :)
Thanks a lot for this great tutoria!!!
can you give me a software that build in c language with their source code. its important to me
plzzz i am waiting for ur reply…
hi , thanks for the tutes.. but can u plz elaborate that what is the use of of comparable rowkeys
comparable column keys in creating bar chart
Thansk alot .. for a wonderful contribution :)
Thanks a lot for it :D
hi…
i used this code but for me its getting just blank page can anyone help in this
thanx bro…!!!
Hey, helped a lot, thx!
But i still got one question: the legend on my pieChart is to big in the PDF, so that the names of the pie parts are above each other and dont scale down, although this doesnt happen when i paint them with jPanel. Maybe any1 got a tip?
**Excuse my english ;
hi ! viral your blog help me alot … thank u very much..:)
we are doing feedback project…. please give me the code how to summarize the results. which we are getting from the students..
please give me an idea
hi…
we are in the process of making the online student feedback system application
we had prepared the front end web pages now we are facing problems in generating code for obtaining the correct selected radio button directed to the database and to make an average of all the forms of one class… please help us regarding this…
please contact: [email protected]
Can i get the souce code please…getting error when placing in eclipse ..thanks
Hi Viral,
This tutorial helped me a lot..thankyou very much.
Hi Viral,
when i download the jar files form the website, i get all zip files like this, jcommon-1.0.16.zip , should i be changing that to .jar or shoud i find .jar from the .zip file and place in my WEB-INF/lib dir.
Please advice.
thanks
Hi Viral,
I am using your tutorial, but PdfTemplate.createGraphics(int, int, DefaultFontMapper) is deprecated. can you pls tell how to replace that part of the code?
I tried replacing with PdfPrinterGraphics2D but not getting any success.
thanks
hey viral ….
actually i included all the jar in project as you said above but when i copy ur code in my project its showing some errors at these following lines…
Document document = new Document();
writer = PdfWriter.getInstance(document, new FileOutputStream(fileName));
document.open();
Graphics2D graphics2d = template.createGraphics(width, height,new DefaultFontMapper());
document.close();
can u just ell me what to do now….plz reply
surjeet
Thanks for sharing such a wonderful tutorial.
However, I am facing an issue that whenever I generate pdf congaing bar chart, I get half page white space & after that it shows bar chart graph. Can you please tell me how can I fix this issue?
the code is not running it has error stated :” could not find or load main class”.. pls suggest me what should i do ?
It helped me a lot. thank you for nice post
Can anybody give me a simple source code. The Tutorial isn’t working all errors occur after the try{} part.
Chart is getting plotted at the end of the page. How to position the chart at the start of the page?
x and y coordinates in the following two lines are already set to zero, still the chart comes at the end of the page.
Rectangle2D rectangle2d = new Rectangle2D.Double(0, 0, width,height);
contentByte.addTemplate(template, 0, 0);
Any help? | https://viralpatel.net/blogs/generate-pie-chart-bar-graph-in-pdf-using-itext-jfreechart/ | CC-MAIN-2019-09 | refinedweb | 2,052 | 60.31 |
97
Very little to go on here, but I'll respond in kind (vaguely):
You may need to have some version of the server software installed on
your desktop - for instance if you are running a web app that is served
through an Apache Tomcat server, and you want everything on your local
system, you'll need to install Tomcat locally.
Wrapping the necessary server startup and application startup commands
in batch files can be helpful too.
If you're running from DOS, without a Windows GUI to act as the "head",
that is probably a dead-end for graphical applications. I expect that
most of the jython/java gui libs expect a windowing environment underneath.
irashad ahmad wrote:
> hi,
> how can i run jython for java web application by dos prompt....
>
> ------------------------------------------------------------------------
> Do you Yahoo!?
> Take Yahoo! Mail with you!
> <*>
> Get it on your mobile phone.
On Apr 8, 2005 12:10 AM, irashad ahmad <write2irashad@...> wrote:
> hi, greg
> i have 2 question:-
>
> 1).how can i run jython.
> What i did- i install jython and run from comand prompt like this
> C:\jython\jython but i did
> not get ">>>" but this "C:\jython" only.
> 2).how can i write jython script for non UI applicaton and how can i run it
> by Grinder.
>
> thanks and regards,
> Irashad Ahamad
Irashad,
You will do better to keep messages on the mailing list, since I'm not
familiar with Grinder I don't really know the answer, but someone else
might.
I think you should focus on getting Jython to run on the command line
first and within Grinder much later.
Did you follow the steps at ?
If so and you are still having problems, perhaps you can follow them
again just to be sure and then let us know what happens.
Thanks,
Greg
I already partially know the answer - Jython was once known as JPython -
but still... the language variant doesn't show up on the SF Software
Map. The real question is, how to fix it.
Navigating to Python, a search for jython shows no results. Similary,
nothing showed up under Java. A global search returns 0 projects with
the term "jython" - even when the associated Yahoo web search returns a
link to the sourceforge project page for Jython.
A search for JPython discovers 10 projects, the first of which is Jython
itself, and two others which mention the name Jython in their brief
descriptions.
I mention this to make the community aware. Jython is currently
invisible on SF (or at least, very translucent). It seems to me that
this kind of broken window can give the wrong impression to people
trying to get a feel for the viability of the language.
- Mitch
On Apr 7, 2005 4:01 AM, irashad ahmad <write2irashad@...> wrote:
> hi,
> how can i run jython for java web application by dos prompt....
>
We are definitely going to need more information to try to answer this question.
Greg
On Mar 8, 2005 1:48 PM, Aaron Freeman <afreeman@...> wrote:
> I know you can effectively rename java classes by using 'import as', but
> is there also a way to rename all the stuff in the class? We're working
> with a proprietary library, so I don't have access to the java source.
>
Wouldn't it be possible to extend the class and redo all public
methods as references to the super methods?
Greg
Try creating it on a command line and creating files in that folder.
Maybe the directory is not empty and there are old read-only files there
that cannot be overwritten. Maybe another Jython script is running and
locked those files. In that case please check that the directory is not
accessed from other computers and your computer time is set correctly.
- Alexey.
mike simmons wrote:
>I am using Grinder in windows XP for the first time and im getting
>this error that i can't seem to solve.
>
>*sys-package-mgr*: can't create package cache dir, ' c:\devTools\jython\cachedir
>\packages'
>
>i have all the appropriate permissions to be able to acces, read, and
>write to the directory.
>
>Any help understanding/solving this would be AWESOME!.
>
>Thanks in advance.
>
>
>
--
------------------------------------------------------------------------
/ Alexey N. Solofnenko
/
On Apr 3, 2005 12:07 PM, Don Schwarz <don.schwarz@...> wrote:
>.
>
Well, if you screenshot the _whole_ screen you could come up with some
graphics analysis that looks for things like corners to find the top
most application's location. What would you do with that? I don't
know. The only things I can think of aren't good: phishing, spyware,
popups.
Greg
hi,
how can i run jython for java web application by dos prompt....
---------------------------------
Do you Yahoo!?
Take Yahoo! Mail with you! Get it on your mobile phone.
I was reading the posts this morning about embedding Jython into Java applications and was stirred to inquire if Jython can be embedded into a Java application, such that at any point, an interactive command interpreter can be displayed and can be queried to give us any/all information about any java object in the system. [Note, by trade, I am not a developer, I am a technical writer with a strong python background. I have written several small Jython/Swing applications.]
In the book Jython for Java Programmers, page 237 states:
. Java code surrounding the interpreter is unaware
. of what is within the bubble, and objects within the
. bubble are unaware of the outside world.
The
. following sections detail
how to pass Jython and
. Java object[s] in and out of the embedded interpreter.
So, can the embedded interpreter be used to promiscuously look at any/all java objects or only the objects that are passed to it?
Roger M
Hi all,
I am trying to access the functionality offered by this simple jython
command
>> sys.settrace(MyTraceBackFunction())
from a java program that runs a Jython interpreter .
I tried the following :
PySystemState s = Py.getSystemState();
s.settrace(new MyTraceBackFunction());
Where MyTraceBackFunction is defined as follow:
public class MyTraceBackFunction extends PyObject {
public PyObject __call__(PyFrame frame, PyString name, PyObject
arg) {
// do something here.
return this;
}
}
However it doesn't work ...
I couldn't find any example about it .. could you point me to the rigth
direction ?
Thanks in advance
Nicola
Am Mittwoch, 6. April 2005 14:46 schrieb Mikel Ega=F1a Aranguren:
>...
Looks so. But I'm no expert on this either - check the docs for mysql. This=
is=20
a mysql question, after all. When you can connect to the mysql using tcp an=
d=20
username/password, then you won't have any trouble connecting using=20
java/jython.
Diez...
Mikel
On Wed, 2005-04-06 at 14:22 +0200, Diez B. Roggisch wrote:
> > Any clues of what can be going on? Many thanks.
>
> Could it be that the mysql daemon is not listening on a tcp port? What does
>
> mysql -h localhost -u me -ppassword
>
> give you?
>
> Diez
> Any clues of what can be going on? Many thanks.
Could it be that the mysql daemon is not listening on a tcp port? What does
mysql -h localhost -u me -ppassword
give you?
Diez
Hello;
I have a little project based on jython scripts that query a MySQL
database. I installed jython in my home using the class file from
sourceforge, because the Debian package doesn't include the
com.ziclix.python.sql module.=20
I have put the driver .jar in the classpath
(mysql-connector-java-3.1.6-bin.jar). This configuration works in my
other computer with Windows. This is part of the code of the script:
from com.ziclix.python.sql import zxJDBC
mysqlConn =3D
zxJDBC.connect("jdbc:mysql://localhost/GO","me","mypassword","org.gjt.mm.my=
sql.Driver")
When I execute it, I obtain an error (pasted in the end of this
message). I can access the database from the same shell by doing=20
mysql -u me -p, but the script doesn't seem to be able to connect to the
database.=20
Any clues of what can be going on? Many thanks.
The error:
** BEGIN NESTED EXCEPTION **
java.net.SocketException
MESSAGE: java.net.ConnectException: Connection refused
STACKTRACE:
java.net.SocketException: java.net.ConnectException: Connection refused
at
com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.ja
va:151)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:280)
at com.mysql.jdbc.Connection.createNewIO(Connection.java:1699)
at com.mysql.jdbc.Connection.<init>(Connection.java:405)
at
com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java :268)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.ziclix.python.sql.connect.Connect.__call__(Connect.java)
at org.python.core.PyObject.__call__(PyObject.java)
at org.python.core.PyObject.invoke(PyObject.java)
at org.python.pycode._pyx0.f$0(parent_retriever.py:6)
at org.python.pycode._pyx0.call_function(parent_retriever)
** END NESTED EXCEPTION **
--=20
---------------------------------------------------------------------
Mikel Ega=F1a Aranguren
---------------------------------------------------------------------
--> Mail: pik@... / mikel.eganaaranguren@...
--> Web:
--> Bit=E1cora:
--> Metabolik BioHacklab:
--> Debian GNU/linux:
--> Gene Ontology Next Generation:
---------------------------------------------------------------------
"Toda religi=F3n es un insulto a la dignidad mental del hombre, pero
principalmente la religi=F3n cat=F3lica, que ha elaborado dogmas contrarios
a la raz=F3n humana. (...) La iglesia cat=F3lica es lo m=E1s hostil que hay
contra la libertad del hombre y la estimulaci=F3n del bien: el mejor
organizado sistema de la aberraci=F3n y el perjuicio, la estupidez y la
falacia. Yo creo que la religi=F3n cat=F3lica es el enemigo n=FAmero uno de=
la
humanidad pensante..." H. G. Wells
---------------------------------------------------------------------
Hi,
As part of my research I've been developing on a Java-based app
called Ceryle:
I recently embedded jython into the framework and have been playing
around with it (I'm still new to python so this also gives me a
chance to learn within an environment I know). Ceryle has an
embedded Jetty server with a JSPWiki dropped in. JSPWiki is fine,
but I'm not wedded to it.
I was wondering if anyone knows of anyone developing a wiki engine
in jython, especially one that could plug in almost as a replacement
for JSPWiki. Or even if it were standalone, a jython-based wiki
would obviously integrate well with a Java application. Since there
are a number of python-based wiki engines around and obviously some
skilled python programmers, it doesn't seem like too much of a leap
to think that a jython-based wiki wouldn't be too difficult simply
as a conversion from an existing python-based wiki.
I'm pretty tied up with my own project, but would certainly be
willing to test and provide feedback, and as my jython skills come
up to speed, perhaps to code (but I can't make any coding commitment
right now, as I'm already pretty overbooked with one big project,
a Ph.D. thesis, etc.). But insofar as it might become part of my
own project it's easier to justify...
Thanks very much for any help,
Murray
......................................................................
Murray Altheim
Knowledge Media Institute
The Open University,.
How to fix jython to print unicode correctly in apple's Terminal.app
and iTerm, the two predominant terminal applications on the mac-- Maybe
something like this should be the default on OS X?
import sys
from string import atoi
from java.lang import System
from java.io import PrintStream
if System.getProperty("os.name")=="Mac OS X":
System.setOut(PrintStream(System.out, 1, "UTF-8"));
class encoder:
def write(self, text):
System.out.write(text.encode("utf-8", "replace"))
sys.stdout = encoder()
Note that using System.out in the python encoder is required, as
sys.out messes up the output.
Hi,
many others asked this question already:
HTH
Alex.
On Apr 5, 2005 1:11 PM, Charles Griswold <charles.griswold@...> wrote:
>?
>
> -------------------------------------------------------
> SF email is sponsored by - The IT Product Guide
> Read honest & candid reviews on hundreds of IT Products from real users.
> Discover which products truly live up to the hype. Start reading now.
>
> _______________________________________________
> Jython-users mailing list
> Jython-users@...
>
>.
-Don
> Actually, assuming that the window you want to capture was created by
> the same Java (or Jython) process, this is actually pretty easy to do
> in Java:
But obviously the OP wanted to create some sort of screen snapshot
application:
> > > I am new to python/jython. I am trying to get the location (upper left
> > > hand corner x and y pixel) and size(length and width) of the current
> > > active window (i.e. the window with focus). After I get this info, I
> > > want to pass it to Java so that I can create a screen capture of only
> > > this window. I would like to be able to do this regardless of which OS
> > > I am using.
Regards,
Diez
(sorry if this is a repost, my first message never got through...)
Hello,
I have a file, helloworld.py, with the single line
print "hello world"
in it. I'm experimenting with Jythonc and would like to compile that
file to Java class files.
Running
$ python helloworld.py
works all right, but when I run
$ jythonc helloworld.py
I get the following error messages:
Traceback (innermost last):
File "/usr/share/jython/Tools/jythonc/jythonc.py", line 5, in ?
File "/usr/share/jython/Tools/jythonc/main.py", line 299, in main
File "/usr/share/jython/Tools/jythonc/main.py", line 162, in
getOptions
AttributeError: class 'org.python.modules.os' has no attribute 'path'
I don't know it this helps, but these are some diagnostic outputs I ran:
$ python
>>>']
>>> sys.prefix
'/usr'
>>>_CREAT', 'O_DIRECT', 'O_DIRECTORY', 'O_DSYNC', 'O_EXCL',
'O_LARGEFILE', 'O_NDELAY', 'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK',
'O_RDONLY', 'O_RDWR', 'O_RSYNC', 'O_SYNC', 'O_TRUNC', 'O_WRONLY',
'P_NOWAIT', 'P_NOWAITO', 'P_WAIT', 'R_OK', 'TMP_MAX', 'UserDict',
'WCOREDUMP', 'WEXITSTATUS', 'WIFEXITED', 'WIFSIGNALED', 'WIFSTOPPED',
'WNOHANG', 'WSTOPSIG', 'WTERMSIG', 'WUNTRACED', 'W_OK', 'X_OK',
'_Environ', '__all__', '__builtins__', '__doc__', '__file__',
'__name__', '_copy_reg', '_execvpe', '_exists', '_exit',
'_get_exports_list', '_make_stat_result', '_make_statvfs_result',
'_pickle_stat_result', '_pickle_statvfs_result', '_spawnvef', 'abort',
'access', 'altsep', 'chdir', 'chmod', 'chown', 'chroot', 'close',
'confstr', 'confstr_names', 'ctermid', 'curdir', 'defpath', 'dup',
'dup2', 'environ', 'error', 'execl', 'execle', 'execlp', 'execlpe',
'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fchdir', 'fdatasync',
'fdopen', 'fork', 'forkpty', 'fpathconf', 'fstat', 'fstatvfs', 'fsync',
'ftruncate', 'getcwd', 'getcwdu', 'getegid', 'getenv', 'geteuid',
'getgid', 'getgroups', 'getloadavg', 'getlogin', 'getpgid', 'getpgrp',
'getpid', 'getppid', 'getuid', 'isatty', 'kill', 'killpg', 'lchown',
'linesep', 'link', 'listdir', 'lseek', 'lstat', 'major', 'makedev',
'makedirs', 'minor', 'mkdir', 'mkfifo', 'mknod', 'name', 'nice', 'open',
'openpty', 'pardir', 'path', 'pathconf', 'pathconf_names', 'pathsep',
'pipe', 'popen', 'popen2', 'popen3', 'popen4', 'putenv', 'read',
'readlink', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', 'sep',
'setegid', 'seteuid', 'setgid', 'setgroups', 'setpgid', 'setpgrp',
'setregid', 'setreuid', 'setsid', 'setuid', 'spawnl', 'spawnle',
'spawnlp', 'spawnlpe', 'spawnv', 'spawnve', 'spawnvp', 'spawnvpe',
'stat', 'stat_float_times', 'stat_result', 'statvfs', 'statvfs_result',
'strerror', 'symlink', 'sys', 'sysconf', 'sysconf_names', 'system',
'tcgetpgrp', 'tcsetpgrp', 'tempnam', 'times', 'tmpfile', 'tmpnam',
'ttyname', 'umask', 'uname', 'unlink', 'unsetenv', 'utime', 'wait',
'waitpid', 'walk', 'write']
And the same, from Jython:
$ jython
Jython 2.2a0 on java1.4.2_05 (JIT: null)
>>> import sys
>>> sys.path
['', '.', '/usr/share/jython/Lib']
>>> sys.prefix
'/usr/share/jython'
>>> import os
>>> dir(os)
['__depends__', 'classDictInit']
Could some kind soul please tell me what I am doing wrong?
Many, many, many thanks in advance,
David
On Mar 30, 2005 3:34 PM, Diez B. Roggisch <deets@...> wrote:
> Am Mittwoch, 30. M=E4rz 2005 18:51 schrieb Bryant, Jason L:
> > Hello all,
> >
> > I am new to python/jython. I am trying to get the location (upper left
> > hand corner x and y pixel) and size(length and width) of the current ac=
tive
> > window (i.e. the window with focus). After I get this info, I want to =
pass
> > it to Java so that I can create a screen capture of only this window. =
I
> > would like to be able to do this regardless of which OS I am using.=20
>=20
> I doubt that is doable in jython or java at all - unless there exists a
> 3rd-party library that makes heavily use of C/C++ and the JNI. It's just =
too
> low-level.
>=20
Actually, assuming that the window you want to capture was created by
the same Java (or Jython) process, this is actually pretty easy to do
in Java:
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import javax.imageio.*;
=20
public class Grab
{
/**
* Get the Window that has focus and write a screenshot of it to
* the specified file in the specified format ("png", "gif", etc.)
**/
public static void grabScreenshot (File writeToFile, String format)
throws InterruptedException, AWTException, IOException
{
Window w =3D
KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
=20
Point p =3D w.getLocationOnScreen();
=20
int x =3D (int)p.getX();
int y =3D (int)p.getY();
=20
int width =3D w.getWidth();
int height =3D w.getHeight();
=20
Robot robot =3D new
Robot(w.getGraphicsConfiguration().getDevice());
Rectangle area =3D new Rectangle(x, y, width, height);
BufferedImage img =3D robot.createScreenCapture(area);
=20
ImageIO.write(img, format, writeToFile);
}
}
No JNI necessary.
-Don
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/jython/mailman/jython-users/?viewmonth=200504&page=3&style=flat | CC-MAIN-2016-30 | refinedweb | 2,819 | 65.83 |
Add an open PPS object to the specified poll list.
#include <hnm/pps.h>
int pps_Object_addToPollList(pps_Object *pps_object, struct pollfd poll_list[], unsigned poll_list_size)
A pointer to the structure that represents the PPS object's file descriptor to be added to the specified poll list.
An array that represents the list of file descriptors to poll. The specified PPS object will be added to this list if possible.
The size of the provided poll list. This represents the maximum number of file descriptors that can be added to the list.
The pps_Object_addToPollList() function adds an open PPS object to the specified poll list and then updates the PPS object's poll_fd member to point to the poll entry that corresponds to the object. This allows the revents mask associated with the PPS object to be accessed directly via the object's structure.
The index of the current structure in the poll list. | http://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.hnm/topic/pps_Object_addToPollList.html | CC-MAIN-2018-13 | refinedweb | 151 | 63.59 |
liquid - Way to store data in shopify
I have a requirement, where in I have 4 different drop down on shopify home page. The First drop-down, let's name it city-drop-down, will show list of city. Based on the city selected in city-drop-down, the second drop down, lets name it category-drop-down, will show list of categories available for particular city. Similarly the third drop down should show the value based on the 2nd drop down and 4th drop down should show the value based on 3rd drop down.
Basically, I need to store list of categories available for each city. Similarly I have to store values available for each categories. How can I store this value, so that the moment a value is selected on webpage, I can use a AJAX call to get the available data for next drop down.
Edited *****
Do let me know, if I am doing it totally wrong. Included the scripts. Please note, initially I uploaded the files under "Files". However I moved it to Assets folder as it was easier to edit the file in Assets folder.
function readcityfile(){ var xmlhttp = new XMLHttpRequest(); var url = "/assets/city_type.txt"; alert("hi"); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { try{ var myArr = JSON.parse(xmlhttp.responseText); alert(myArr); //myFunction(myArr); } catch(err) { alert(err.message); } } }; xmlhttp.open("GET", url, true); xmlhttp.send(); } function myFunction(arr) { var i; for(i = 0; i < arr.length; i++) { alert(arr[i].city); } }
And the JSON file is -
[{"city": "Jamshedpur","types": "Sweets@Savories@Cake"},{"city": "Ranchi","types": "Sweets@Savories@Cake"}]
Answer
Solution:
One simple way if the data size isn't too large would be to generate your data as a JSON file and simply store it as a file and then edit your theme to include the file's url. A file that is too large might be 100k. Smaller is better but if you don't have a back end to handle the AJAX calls the static file certainly provides a low cost proof of concept.
There are two ways to do this.Either as an asset or a file. Assets are part of your theme so even though you'll be altering your templates to manage this I'd tend to go with a file. (Assets are just files located under the theme but the are dealt with slightly differently)
- go to your Shopify Admin control panel
- Click Settings
- Click Files
- Click "Upload Files"
After upload you'll have a file. The next step uses the file's name not its URL.
Go to your theme editor:
- Shopify Admin control panel
- Online Store
- Themes
- click Customize Theme
- drop-down Theme Options and select HTML/CSS
I'm guessing you are going to select the template product.liquid to edit. do that and decide where you want to introduce your javascript file. If your script file was named cities_etc.js you'd import it as below:
{{ 'cities_etc.js' | file_url | script_tag}}
Answer
Solution:
This method seems a bit slow if all that you are trying to do is create a tiered menu. Using Ajax requests will mean there are several round trips and it will be visually slow for the user waiting for the ajax request to complete.
You can create a linklist ()
I know you have already found your method but I would strongly urge you to give this a go. Here is an example of some liquid markup that will created a tiered menu. The parent linklists handle is
main-menu then you need to create a linklist for each of the children where the handle matches the title in the main-menu. For example if you have an 'About Us' link in the main menu create a linklist also with the handle 'about-us'. Then just use some simple css or javascript to hide and show the menus on hover.
{% for link in linklists.main-menu.links %} {% assign child_list_handle = link.title | handleize %} {% if linklists[child_list_handle].links != blank %} <li class="dropdown" aria- <a href="{{ link.url }}" class="nav-link {% if link.active %} active{% endif %}"> {{ link.title }} </a> <ul class="dropdown_menu hidden" id="{{ child_list_handle }}"> {% for childlink in linklists[child_list_handle].links %} <li> <a href="{{ childlink.url }}" class="nav-link{% if childlink.active %} active{% endif %}">{{ childlink.title | escape }}</a> </li> {% endfor %} </ul> </li> {% else %} <li> <a href="{{ link.url }}" class="nav-link{% if link.active %} active{% endif %}">{{ link.title }}</a> </li> {% endif %} {%. | https://e1commerce.com/items/way-to-store-data-in-shopify | CC-MAIN-2022-40 | refinedweb | 741 | 76.01 |
Keras Sentiment Analysis in plain english
Karan
・9 min read
Hi devzzz!
I'm trying to learn ML and recently bought the book Deep Learning with Python by François Chollet.
Here's an implementation of the IMDB sentiment model from the book with some changes, I'll try and explain what I know and what I did, apologies for my code 😓.
Premise
- Machine learning essentially uses math equations which can be tweaked to do shallow things that humans can do very easily.
- Deep learning is machine learning with neural networks, like layers of meshes lying one on top of another. Each network is again, a math equation, multiple layers of neural networks are well multiple math equations on top of another.
- Each networks has weights associated with it, like a coefficient in an equation. Like when you say y = ax + b, then a is the weight associated with x. Don't worry about it too much as Andrew Ng says.😊
- When you put these network adjacent to each other and train them using data they form what everyone in the ML field call as an internal representation.
- These internal representations is what the networks see based on the world of data which they have been trained on. Think of yourself as a caterpillar who's crawling along the floor and all your life, all you know is that there is something beneath you on which you crawl, even though you've never seen it, even though you don't know that it is and you obviously don't care about the humans who built it but you know mentally that If I crawl on this I'll be able to move.
- In the same way this model is trying to learn if sentiments are positive or negative. Remember it cannot actually feel or understand the sentiments but with the help of labelled data this is possible.
- Labelling is the cornerstone of supervised learning (part of machine learning where models learn by showing examples of something). It's like showing a kid what a car is then they're able to identify cars like experts, machine learning models though are obviously way behind in that general sense.
Code
What's Keras btw? : As far as I understand from the book and online articles, it's an API specification which calls lower level functions of other ML libraries such as Tensorflow, CNTK or Theano. To say simply, it makes it a lot easier for anyone to use lower level libraries without getting bogged down by the details. At a given point of time it can use any one of those and you won't have to change anything in your code on the top! A super naive view would be Keras is your front end and Tensorflow/CNTK/Theano are your backends :)
import stuff
import numpy as np # for numerical arrays from keras import models #book told me to do it ! :) from keras import layers from keras.datasets import imdb from keras import optimizers import matplotlib.pyplot as plt # for plotting
get the data
Keras allows you to directly import data into your program without hassle.
(train_data, train_labels),(test_data, test_labels) = imdb.load_data(num_words = 10000)
And it's so sweet that it splits the data into training and testing.
training and testing data?
Well you might have heard people throwing words around like overfitting, underfitting to sound cool? Well this is what they're talking about. When you get a bunch of rows, thousand of rows (yes think of it as excel rows and columns) of data, the best idea is to divide it into training and testing. The training data trains the models (neural network layers) and the testing data is used to see if the model actually is any good. You'll see more on this later.
labels?
Let's see a simple table below:
So here the labels are the last column, Can Code?, more importantly when you ask the model to look at these, you need to make them binary, i.e. No for 0 and 1 for Yes.
Let's split this data:
Training Data: train_data would be columns User & Age, train_labels would be Can Code?
Testing Data: test_data would be columns User & Age, test_labels would be Can Code?
In our case of IMDB comment sentiment analysis, the data is like this:
Word indices is an array which holds the frequency number of a word which appears in a comment.
Say for example: "Shawshank Redemption is probably the best movie ever", this would be translated to the following based on the frequency of the words in the english corpus as follows:
The last value of 1 is actually saying this is a positive comment, by a human who has labelled it, in this case it's your truly :). You can try this yourself if you have keras installed as follows:
from keras.datasets import imdb s = "Shawshank Redemption is probably the best movie ever" for word in s.split(' '): print(word_index.get(word, '?'))
not all comments are of the same length dude! & vectorize
Yes, you're right and so we use something called one hot encoding to convert this mess of words into a standard length of an array of 10,000 elements, remember this?:
num_words = 10000
This limits the comments to have only those words which have a frequency of more than 10,000, i.e. they are used most often.
x_train = np.zeros([len(train_data),10000]) for number, sequence in enumerate(train_data): x_train[number, sequence] = 1
And you do this with the test data as well, since you'd need to maintain consistency when you test the model which works on arrays of 10,000 elements right?
so...
#in the book it is done as a function...but like right now.....ignore it x_test = np.zeros([len(test_data),10000]) for number, sequence in enumerate(test_data): x_test[number, sequence] = 1
Vectorize (or make them into numpy arrays) the labels as well:
#vectorize labels y_train = np.asarray(train_labels).astype('float32') y_test = np.asarray(test_labels).astype('float32')
what is validation?
Now comes a part where we split the training data as well! Yeah, but why do that?
What's over or underfit?
If a model is overfit, it means it's sticking so close to the data it trained on, that it cannot identify/classify/work on anything outside of what it encountered during training, just like saying "I now know what a Honda Civic is" but then when you see any different car you just say "that's Honda Civic! And that's Honda Civic and that's Honda Civic!"
On the other hand, when in an underfit scenario, it's going to be "I now know what a Honda Civic is" but then whenever you see a new car you say "well what is that? It's not a Honda Civic! Is it even a car? What is it?".
And so let's do some simple math here:
Keras IMDB data gives us 50,000 rows or samples.
25,000 went to training --> 15,000 would go into actually training those neural networks and the rest 10,000 would go into validation. Validation essentially refers to using training derived data to tune the model, to make it WORK, whenever we make some changes and train the model again on those 15,000 samples we check the result on the validation set of 10,000 samples.
Remember we never touched the rest of the 25,000 which are into the test set, not touching it at all! And that's the whole point of machine learning: how to use data generously to train a model to generalize while at the same time preventing overfitting and underfitting, therefore the test data will never have any contribution towards training the model.
where is the machine learning in all this?
- Here we are, we will define the model and inputs that go into it.
- I have added some for loops into the model creation area of the program to test different types of activation functions, loss functions, hidden layers and hidden units.
Let me show you:
#model iterations activations = ['relu', 'tanh'] loss_func = ['mse', 'binary_crossentropy'] hidden_layer_units = [16, 32, 64] hidden_layers = [1,2,3] for activation in activations: for function in loss_func: for units in hidden_layer_units: for lyrs in hidden_layers:
What's an activation function?
Relu or tanh/sigmoid which are rectified linear units and hyperbolic functions which put some non linear(non linear is fancy way of saying not on a straight line) vibe into the math equations we're using. These are nothing but operations on the neural network mesh to make those internal representations and primarily in the end learn a good representation of the input data. Again don't worry about it too much, I just went ahead and used them!
What's a loss function?
Imagine your guitar tutor telling you that the riff you just played was not even close to how Slash plays it! You're furious, it sounds pretty good to you, but not to the tutor! So how do you tell if you're improving? Well one way is to record yourself playing and listening to it and then using that feedback to improve so you could reduce the difference between you and Slash. That's what a loss function is calculating. It's trying to minimize the difference between what it predicts and what the actual label is.
In this case, it would be:
Human
Comment : "Shawshank redemption is the bomb yo!" Label : 1
Model
Comment : "Shawshank redemption is the bomb yo!" Prediction : 0.85
As you see this model has probably been trained well and it's prediction is about 0.85 or 85%, that is leaning to 1.
hidden layers and hidden units?
These items are to be covered in the book in more depth! 😂 But they form the deep part of deep learning. Say you have 3 layers:
Layer 1 : Input layer which accepts that 10,000 element array
Layer 2 : A middle (hidden)layer with an activation function, takes input from layer 1 of 10,000 elements and spits out 16 element output.
Layer 3 : An output layer with an activation function, takes input from layer 2 of 16 elements and spits out a 1 element output.
In the above case we have 1 hidden layer with 16 units.
The only reason I added those for loop was to try all the activations, loss functions etc. Loop over all of them to find the best fit as you see below.
GO GO GO GO!
We define the model, if you see the three layers above, the following lines are doing just that. The for loop in between just adds layers on different iterations which may return a better prediction.
#print(activation, function, units, lyrs); #write model model = models.Sequential() model.add(layers.Dense(16, activation = 'relu', input_shape = (10000,))) for i in range(0,lyrs): model.add(layers.Dense(units, activation = activation)) model.add(layers.Dense(1, activation = 'sigmoid')) #optimzers, loss etc. model.compile(optimizer = optimizers.RMSprop(lr = 0.001), loss = function, metrics = ['accuracy'])
The last line is adding another beast, the optimizer, which if you take the guitar example is like saying how will you reduce the difference between yourself and Slash, by:
- Practicing 24 hours a day?
- Or, selling your soul to the devil?
- Or, asking Slash to play in your place?
To put in plain english the optimizer works on the loss function to reduce the error rate of the model and hence increase the accuracy.
history = model.fit(x_train_partial, y_train_partial, epochs = 10, batch_size = 512, validation_data=(validation_x_train, validation_y_train))
This line above is where you see the magic happen on the terminal! THE ACTUAL TRAINING, try it out, it's oddly satisfying! 😌
Where do we go from here?
Well the model training part is half the stuff done, the part is looking at the results, the accuracy, whether the model overfits or underfits etc and then changing your parameters. Any of the following:
- Learning rate
- Activation function
- Epochs - how many passes you make over the training data
- Hidden layers
- Hidden units
- Loss function
And that's where this article ends, I still haven't found the right combination, although I think it's a simpler problem, considering it's the first in the book!
Here is one of the outputs from the model, one of the 36 combinations:
Here is the code:
You might have to change the paths to save the images and the models. | https://dev.to/hydroweaver/keras-sentiment-analysis-in-from-the-book-in-plain-english-36hd | CC-MAIN-2019-22 | refinedweb | 2,088 | 61.67 |
..., Java
variables, constants, and literal, Java identifier example, what is public 1) write a program to print prime numbers?
2) write a program to print factorial of given number?
3)Please provide complete material..., visit the following link:
Collection of Large Number of Java Sample Programs and Tutorials
example of java program is
provided that shows you how you can...;
HelloWorld
Java Program
Simple...Collection of Large Number
of Java Sample Programs and Tutorials
Java
programs - Java Beginners
.
(by using methods of minimum and maximum of numbers)
3. Write a Java program to demonstrate inheritance.
4. Write a Java program to demonstrate dynamic polymorphism.
5. Write a Java program to implement the following hierarchy
Java Programs
In this section of RoseIndia we are providing several Java programs on
various topics like get example, java exceptions, wrappers class, java pass
value, java break example, Java Biginteger, Java string examples etc. All
java programs
java programs write java applet program to display an image using drawimage method of an java graphic class
programs - Java Beginners
three dimensional array programs Example of three dimensional array program in Java. Hi friend public class ThreeDArray { public static void main(String[] args) { int[][][] threeD = new int[5][4][3]; for (int i
programs - Java Magazine
:
Thanks
Amardeep...programs a program to print circle and fill a colour in it. ...
This program based on Java2D
import java.awt.BasicStroke;
import java.awt.Color class program - Java Beginners
Simple Java class program Hello,
Please help me, Write a simple class that iterates through all the arguments passed in on the command line....
Generics Example Program in Java
Generics Example Program in Java explaining how you use it effectively... the Java Program? The introduction to the Generics is the major step in
the Java... in Java code.
Generic List Example
In this example I will show you how you can
Simple FTP upload in Java
Simple FTP upload in Java How to write a program for Simple FTP upload in Java? Any code example of Simple FTP upload in Java will be very helpful for me.
Thanks
Hibernate Simple Program Using Java Application with Eclipse
Hibernate Simple Program Using Java Application with Eclipse How to write Hibernate Simple Program Using Java Application with Eclipse?
I wish... is: First Hibernate Example Step by Step in Eclipse
Check Hibernate tutorial home
Programs in java - Java Interview Questions
Program in Java decimal to binary i need a java example to String Reverse. Can you also explain the Java decimal to binary with the help.../java/example/java/util/CapturedText.shtml
Java programs - Java Beginners
Java programs Hello
Please write the following programs for me using GUI.Thanks You.
1. Write a java program that reads the first name, last name... a program that reads the name of a student, his age in years and three grades
Simple Java Calculator - Java Beginners
Simple Java Calculator Write a Java program to create simple Calculator for 4 basic Math operations,
Addition, Subtraction, Multiplication...,
Please visit the following link:
Java Programs
Java Programs Hi,
What is Java Programs?
How to develop application for business in Java technology? Is there any tool to help Java programmer in development of Java Programs?
Thanks
double array in java Please give me an example of double array in java. Hi friend public class TwoDArray { public static void main(String[] args){ int[][] twoD = new int[8][4]; for (int i=0; i<twoD.length; i
Very simple `Hello world' java program that prints HelloWorld
Hello World Java
Simple Java Program for beginners... to develop robust applications. Writing a simple Hello World program is stepwise step. This short
example shows how to write first java application and compile
First Java Program Example
;. To demonstrate about a Java
program I am giving a simple example.
Example
Here... your first program in Java. In this example I have created a simple class
named...First Java Program Example
In this section we will discuss about the first
Installing programs over a network
Installing programs over a network Hi, i want to write a java program that will allow me to install programs from a server to a client machine. Any help will be appreciated. Thanks
Simple Java class program - Java Beginners
Simple Java class program Hi sir,
Please help me Write a simple class that iterates through all the arguments passed in on the command line...();
}
}
--------------------------------------------
Read for more information.
java programs
java programs A union B, transpose of matric, denomination of a given number i need java programs for this category?
Hi Friend,
Transpose of matrix:
import java.util.*;
public class Transpose {
public
simple pgm
simple pgm a java program which uses super class...;
in this example) where your program is saved.
Java uses the "javac"
java program example - Java Beginners
java program example can we create java program without static and main?can u plzz explain with an example
Installing programs over a network using java
Installing programs over a network using java Hi, i want to write a java program that will allow me to install programs from a server to a client machine. Any help will be appreciated. Thanks
throws example program java
throws example program java how to use throws exception in java?
The throws keyword is used to indicate that the method raises..." java.lang.ArithmeticException: / by zero
Description:- Here is an example of throws clause. We
Switch Statement example in Java
;
This is very simple Java program... in your java
program for developing java application. This section provides you... also provides you an example with complete
java source code for understanding
Please help me to solve these programs in Python - Java Beginners
Please help me to solve these programs in Python 1. Write a program.... For example the string ?argh? would appear ?aarrgghh? Hi friend...();
}
}
}
--------------------------------
read for more information,
Struts 1 Tutorial and example programs
Struts 1 Tutorials and many example code to learn Struts 1 in detail.
Struts 1... the Java Servlet API to encourage developers to
adopt an MVC...?
The basic purpose of the Java Servlets in struts is to handle requests
Simple Java Desktop Upload application
Simple Java Desktop Upload application I try do simple example for upload applicationtake file from c:\ put to d:\ :)
PLEASE HELP program - Java Beginners
java program Pl. let me know about the keyword 'this' with at least 2 or 3 example programs.
pl. let me know the program to multiply 2 matrix.... It helps us to avoid name conflicts. As you can see in the following program simple question - Java Beginners
Java simple question I have to design a program for a trucking company that has 7 trucks in its fleet. Each truck is identified by a number, 1-7.... Truck 7 Max = 30K weight = 20K. (8 possible dialog boxes: program instructions
Programs - JMS
JMS Example Program Hi, can any one explain the JMS program with the help of an example.
JAVA7 : "Hello World" Example
JAVA7 : "Hello World" Example
This tutorial elaborate a simple example of JAVA 7.
Creating Java Program :
Before writing java program we... program easily.
The following image shows how java program execute -
Example
Simple Date example
Simple Date example
In this section we have presented a simple Date example... is the example code of SimpleDate.java as
follows:
SimpleDate.java
Simple Form in Java
Simple Form in Java
This is a simple program of java awt package which
constructs a look like a form by using various java component. In this
section, you will learn how
Writing Simple Java Script Program
Writing Simple Java Script Program
... of JavaScript and
create your first JavaScript program.
Creating your first JavaScript Program
In the last lesson you learned how to create simple
java script
program
program i want a progra in java to print a sentence in alphabetic order, taking the input from the user.the program should writen without using the array
for example : if input= this is a cat
then output sould = a cat
simple team leader
simple team leader Could you please help me to write a program for a simple team leader?
Please clarify your problem. Which type of program you want to create in java? Please specify
Simple date formatter example
Simple date formatter example
In this section of simple date formatter example we... is the full example code of SimpleFormatDate.java as
follows:
SimpleFormatDate.java
Core Java Hello World Example
.
In this section we will discuss about a simple Java program. A HelloWorld
application... are used in this program. This is a basic example of core Java that
explains how...Create Java Hello World Program
This tutorial explains you how to create
Java simple reference source - Java Beginners
Java simple reference source Hi,
please could you recommend me a Java simple reference source (on line or e-book) where I could quickly find the stuff? For example list of operetors
, list of loops + usage, list if ArrayList
program for HashSet - Java Beginners
://
Thanks.
Amardeep...program for HashSet I need a program that illustratest the concept..., LinkedHashSet, and TreeSet classes implement these interfaces.
Here is the simple
Advertisements
If you enjoyed this post then why not add us on Google+? Add us to your Circles | http://roseindia.net/tutorialhelp/comment/93911 | CC-MAIN-2015-35 | refinedweb | 1,532 | 55.64 |
When compared to the native look and feel of Windows apps, the
JToolBar's interior padding(ie the distance from its border to
the buttons contained in it) is incorrect. You can see this by
comparing a native Windows app that doesn't have the rollover
toolbar effect(like WordPad) to one created using Swing. The
code below creates a simple toolbar with three buttons. On a
native Windows app the interior padding is roughly 3 pixels above
and below the contained buttons and 4 pixels on the far left
and right(these are eye-balled). The JToolBar, using the Windows
LF doesn't provide any padding, which makes it different from the
the native appearance it's suppose to be emulating.
When invoking the test app if you don't supply any command-line
args the LF is Metal. If any args are supplied the LF is Windows.
Here's the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class bug extends JFrame {
public static void main(String args[]) {
if (args.length > 0) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {}
}
new bug();
}
public bug() {
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
});
JToolBar toolbar = new JToolBar();
toolbar.add(new JButton("Button1"));
toolbar.add(new JButton("Button2"));
toolbar.add(new JButton("Button3"));
getContentPane().add(toolbar, BorderLayout.NORTH);
pack();
setSize(300,100);
setVisible(true);
}
}
(Review ID: 94800)
======================================================================
In my program i use abstract actions to create my buttons which
are added to a toolbar. When using the metal look and feel, the
buttons in the toolbar are squares (the used icons are all
16 * 16 pixels in size). But when using the windows
look and feel they are much wider than high. Even when setting
the margin with the setMargin method of button, the problem is
not resolved because this method seems not to work properly
(at least for the vertical margin).
This is how i create my buttons and the toolbar
...
JToolBar toolBar = new JToolBar();
Action act;
JButton button;
button = toolBar.add(act);
...
(Review ID: 95766)
======================================================================
You can manually set the toolbar border to use a compound
border, where the inner border is empty and is set to use the
appropriate top,left,bottom,right padding.
======================================================================
This has been fixed as part of the revision to the Windows Look and Feel. The ToolBarBorder class was added to WindowsBorders.
xxxxx@xxxxx 2000-08-02 | http://bugs.sun.com/bugdatabase/view_bug.do%3Fbug_id=4268306 | crawl-002 | refinedweb | 406 | 56.45 |
Talk:PHP Programming
From Wikibooks, the open-content textbooks collection
[edit] Front Page Cleanup
I think the front page needs to be cleaned up a little. The top sections are good along with the contents of 'The Basics' section but further down it gets a little disorganised. It needs to be cleaned up and filled in to make the front page more presentable. Also, do we really need a 'Contributors' section? I thought the point of Wikis was that everyone contributed, it seems against the ethos to attribute certain pages to certain people. Fyorl (talk) 11:37, 13 February 2008 (UTC)
[edit] Working with Files
I plan on adding a section related to working with files. I will discuss mainly the use of the f(open|write|close) in conjunction with file() and file_get_contents() as well as devoting a small section to file_put_contents and how to emulate it with PHP 4.
I'm just checking that nobody is already working on a similar section. If I hear no response in a couple of days I will start work on the article on my Talk page and then tranfer it over upon completion.
The article will also make a reference to serialization. Since this could appear in both the Database section and the Session section, I was wondering if it was best to create a separate page and link to it from within all the other pages? Fyorl (talk) 16:52, 9 February 2008 (UTC)
[edit] Naming policy?
I am not new to Wikipedia, but this is the first time I have looked at a Wikibook. I have some confusion about the template that says the book's title does not adhere to the "naming policy." What is wrong with the title, and how does it not adhere? Here I have seen discussions about the book's content, cover, PHP version, and so forth, but nothing regarding the name or that template. To anyone that may advise--thanks. 67.42.14.57 18:19, 4 December 2007 (UTC)
- If you click on the link in the naming policy notice, you'll see the preferred naming convention. This wikibook used to use a colon (:) separator for sub pages, which resulted in the need to manually link to the index (example: hello world). Currently, the barely-existing PEAR page seems to be the only page still using the depricated naming convention. --banzaimonkey (talk) 20:28, 10 December 2007 (UTC)
- As it seems that all of the pages are in order (excepting PEAR), I removed the template. --banzaimonkey (talk) 20:33, 10 December 2007 (UTC)
- But now it is back; anyone care to explain? — Sam Wilson (Australia) 21:36, 4 June 2008 (UTC)
[edit] Version
Are we talking PHP version 4 or 5 here?
PHP5 was recently released, and features the ZEND II engine, which includes enhanced OOP(Object Oriented Programming) features, better XML support, and built in SQLite support.
PHP4, on the other hand, is still the prevalant web technology, and I suspect that most servers will not be offering PHP5 support for some time.
Either way, I suggest that OOP be included in the 'advanced php' section. I just don't know how to write it because of the discrepancies between php4 and php5. --Noah 20:19, 28 Jul 2004 (UTC)
Ok, since I recieved no response, I will assume that this page is geared towards PHP5. I am going to start writing the OOP features accordingly. I will also edit the intro to make this obvious. --Noah 18:46, 14 Aug 2004 (UTC)
I think for anything specific to one version, we should show the equivalent in the older / newer version if possible. --Spoom 01:47, 7 Sep 2004 (UTC)
- I'd like to second this notion, and extend it. Whenever possible I think functions that are aviable in both versions should be used. For most of the introductory material it doesn't matter. OOP can be part of a later discussion, along with other major version 5 improvements. Since these books are perminant static things we can always drop discussion of version 5 when it becomes the standard (in other words we can stop singling out the difference at that point). I would expect most people learn PHP at the moment are still working in 4. --Ahc 06:28, 2 Dec 2004 (UTC)
[edit] External links?
There are many "dead" links here to pages that don't exist on wikibooks, and will most likely never exist. For example: GUI or Rasmus Lardorf will most likely not get their own books. It's much more likely that they'll get a Wikipedia page(GUI already has one), and I think that's where those links should take you...
I'd say change them to link to Wikipedia if you find them then, just use common sense. --Spoom 06:15, 6 Oct 2004 (UTC)
[edit] Smarty Templates
There is no reason to discuss Smarty Templates as part of the language. You can either hit them in a round about PEAR and Templating or put the package in a list of "useful" PHP projects.
- While Smarty is not part of the core language, it is mentioned in many other PHP books, and it is a very useful to have knowledge of its features. However, I think merging Templates and Smarty would be useful.
[edit] Include/Require functions
There seem to be at least 3 sections which talk about require(_once) and include(_once) (Headers and footers, Template and Including Files. Since these deal with basically the same subject, couldn't they be merged into a single page about the use of require and include, and a list/example of the uses of these functions? -- DorianGray
If I don't see any reasons why in the next few days I'll delete Templates and Headers and Footers and move all relevant content to Including Files. --DorianGray 06:58, 15 Nov 2004 (UTC)
[edit] Internal Functions?
I know that the PHP website has a lot of information about PHP's internal functions, but do we want to start highlighting the ones most used? I'm particularly interested in the mail() function myself.
<niallj 20:59, 3 September 2005 (UTC)> I would say that's unnecessary, unless it comes up in the course of a lesson. I feel that a structured, lesson based approached would be better. Example: a lesson on "Sending E-Mail with PHP" rather than "mail()", and "Working with Arrays" as opposed to "Array functions" or "array_sort()" </niallj>
[edit] MySQL in PHP5
Should it be mentioned that PHP5 on Windows no longer has MySQL support built in, but has it shipped as a separate DLL that needs to be referenced in php.ini?
Hi, i think that this should be mentioned in the php:mysql page, not the main page. I wrote that it should be downloaded separately -- User:Wykis
[edit] Sub-pages
<Jun-Dai 00:20, 3 Jun 2005 (UTC)> Shouldn't the pages for setting up your environment be on subpages? It makes this main page seem awfully noisy to have them right there. </Jun-Dai>
- <davidd 23:05, 11 Dec 2005> I agree, I think there seems to be alot of emphasis on lesser PHP topics such as setup, templating etc. and there should be more PHP code and the setup stuff should be in a sub-topic</davidd>
[edit] Accessing files
I'd like to see a section on reading and writing from/to files. Anyone? Thanks!
- I'm writing it now if no-one has any objections. I plan to put it in the basic section as a starter's guide to file manipulation.--Davidd 23:09, 11 December 2005 (UTC)
[edit] echo/print functions/constructs
<niallj 20:53, 3 September 2005 (UTC)>On the Hello World page, and maybe in other places that I haven't noticed yet, echo and print are referred to as functions. Since they are actually language constructs in their own right, should they be more accurately referred to simply as statements?</niallj>
[edit] The newline "operator"
<niallj 21:06, 3 September 2005 (UTC)> In PHP Basics Example #1: Basic Arithmetic Operators, a reference is made to a newline "operator". The example in question is actually referring to the process of adding a newline by using the \n escape sequence in a double quoted string. I recommend that firstly this reference is clarified, explaining escape characters, and that secondly, since PHP is most often used with HTML, that this example be rewritten to use the <br /> tag- it being the case that in a browser, the \n character does not cause a newline. </niallj>
I've got to agree on this too. This is so annoying when user changes the page to rendered html page. for example, text to text and
to new line... We are not evaluating html here. HTML is just an example. Please don't edit any pages just to do that. Thank You Wykis 07:03, 26 March 2006 (UTC)
[edit] where are the Snafus?
The part that always seem to be left out from programming tutorials, or, if present, truncated to incomprehensibility (part of the ph.D curriculum I guess.. ;) is a bunch of common errors in writing the code.
Anyone who has done any programming have made mistakes that take forever to track down. Please add a section with the most obvious ones, and put it in the 'beginner' section. (a personal favourite is 'if ($X == $y;) {...}' which took a few re-readings to catch..)
[edit] How about some exercises per lesson?
Not just simple questions. I mean something along the lines of "Make a script that prints 'foo' if 'x' is true" or something like that. Doing this helps keep the concepts stuck in your head, and would be tragic if this textbook didn't have it.
[edit] First person writing?
Should addendums be added in first person, such as "I recommend ..."? How should this be handled? 209.149.56.162 00:35, 29 December 2005 (UTC)
Hey, i just noticed this too, I will correct the mistakes as the book is written by a lot of people,not one person ;p Wykis, 14:42 14 January 2006
[edit] New presentation
I propose to change the look of the PHP book : we can use this look fr:Programmation PHP (sorry in french). Do you like this ? Merrheim 10:07, 5 March 2006 (UTC)
wow, wish i knew about this b4. i think this page is going to change my life --Nerd42 16:58, 16 March 2006 (UTC)
I don't agree on this. I like the idea though. The design of that French page looks good but I prefer this book to be just like a normal book. Just a book :) Wykis 18:20, 29 March 2006 (UTC)
- Wikibooks are viewed on a computer. Since there isn't a tangible book with pages to turn, an outline view would be really nice. Getting between lessons in the current layout is rather tedious, and a TOC / Index / Outline view would probably work better than putting "Next Page" links on each lesson because the ordering of the lesson can change, and the navigation would break. Changing the formatting would be a lot of work, but we should look into it (it doesn't have to be a carbon copy of the French layout). It doesn't do anyone much good if the information herein is inaccessible. --banzaimonkey
- I'm working on some indexes at the moment, so don't go running off and do something I've already done. ;) --Banzaimonkey 19:01, 11 July 2006 (UTC)
[edit] for MediaWiki
it would be cool if there was a section on advice for would-be developers about writing bug fixes for MediaWiki. 128.250.37.103 07:41, 22 March 2006 (UTC)
[edit] Alredy exists?
Did you try googlling about this? helps quiet a lot. This is a Programming book for PHP, NOT for MediaWiki. Instead, try looking in IRC and [1]. Wykis 18:18, 29 March 2006 (UTC)
[edit] Flag Frog = Ripped from Smarty?
Flag Frog templating system looks like a rip from Smarty template engine. Should this be removed from the page? Wykis 18:16, 29 March 2006 (UTC)
- It looks like a fork of Smarty-Light. It's under the GPL, so I see no issue with it in and of itself, but I don't think it's something that needs to be posted on the PHP wikibook considering that as of now, there are 164 downloads in total of all version of the FlatFrog package. Has anyone here heard of it before? Spoom 17:57, 5 April 2006 (UTC)
[edit] Major Changes to this Wikibook
I'm planning a significant overhaul for this wikibook. It currently has a decent amount of information but suffers from irregular organization, lack of verbocity, and has room for substantial additions of content. I've been writing a small todo list for myself, which you can view on my userpage. If you're an active reader / contributor and would like to take part in a discussion about changes to this wikibook, please reply in this page or contact me on my talk page. Otherwise I'll just assume that I'm the only person here who is active and will carry on with the changes as time permits. --Banzaimonkey 09:04, 12 July 2006 (UTC)
- Update: I have been working on thing for a few weeks and am ready to proceed with a few things on my list. Code examples will be wrapped in a color-coded box designating the type of code example (see Code Template for details). I've also created a cover for the book which you can view here. I've tagged the book as having a deprecated naming convention, and I will begin the process of migrating them to the new namespace once I decide what that namespace will be (probably PHP_Programming. This will enable root auto-links on each page (returning the user to the main page), as well as conforming to the new naming convention (as of March 1rst, 2006). Next on my list is an overhaul of the table of contents, but I'm still unsure how this will be reorganized. If I have free time after all that, I'll go through this talk page and clean it up a bit. --banzaimonkey 02:17, 6 August 2006 (UTC)
- Update: The overhaul on the table of contents will probably take place before the migration. This will allow me to figure out how things need to be organized when they're moved. --banzaimonkey 06:39, 6 August 2006 (UTC)
[edit] Color Code Boxes
I have wrapped the first two Basic programming lessons. All code is contained in a colored template. You can view them here and here. Please leave your feedback in response to this post. My own thoughts are positive, but I'm not entirely satisfied with the functionality. I may rewrite the template with a more modular, extensible approach. --banzaimonkey 06:36, 6 August 2006 (UTC)
I think that it is a good idea. Makes for easier reading and quicker reference.Bounton 08:26, 12 September 2006 (UTC)
What do you think about adding syntax highlighting? In my opinion, it makes the code much easier to read. --King elessar 00:35, 20 September 2006 (UTC)
- I like this idea if it's at all possible to do automatic syntax highlighting of PHP code within MediaWiki somehow. Also, have you taken a look at Template:Code:PHPHTML? I don't know if you're already using it but it's a perfect fit. Keep up the good work. --Spoom 18:03, 22 September 2006 (UTC)
Very interesting. I like it. Helps to highlight what we are trying to do with the code.
Its a good idea!
Love it. Reading is much easier on the eyes
good idea
Excellent idea. Much easier to read. Go on u's.
[edit] Book Cover
I've added the book cover to the main page to garner attention and feedback. Please leave your feedback here. When the book is reorganized and migrated, the book cover will appear on the main page and will link to the table of contents. --banzaimonkey 06:40, 6 August 2006 (UTC)
I personally like the design. It seems friendly, colourful and has PHP code and the elephant in it. It also seems like a cover you might see on a book. Good work.213.168.233.251
The licensing sounds incompatible (combination of GNU GPL and GFDL) - maybe elroubio would agree to license the elephant under the GFDL?
- This licensing crap and legal encumbrance is the primary reason I haven't done any work on wikibooks lately. It's too tedious trying to figure out how to get everything done legally, much less organized, formatted, proofread, etc. I don't do legal work unless I'm paid for it. If someone else wants to contact him (he speaks French, btw), go ahead, otherwise... *shrugs* --banzaimonkey 03:41, 25 October 2006 (UTC)
- The GFDL is for documentation. Why do you want to use it for a image? —Andrew Hampe Talk 01:38, 24 July 2007 (UTC)
- I had been under the impression that contributions to wikibooks were limited to GFDL (since the text is licensed as GFDL). It seems that is not the case, so I have changed the license to GPL to avoid any particular incompatibilities with the source images. --banzaimonkey (talk) 19:55, 10 December 2007 (UTC)
Ehh. I like it, brings good attention to the page
I like it. It makes more sense than Programming Python, the O'Reilly book. It has a mouse on it. SNAKES EAT MICE. (I'm curious, what does that code do?) --74.101.118.195 04:28, 23 July 2007 (UTC)
[edit] Reorg
I am going to reorganize the information contained in the "Hello World!", Nuts and Bolts, and commenting and Style modules to a more K&R approach:
- "Hello World!"
- Variables
- Operators
- Expressions
I think giving each topic its own module will make a better layout for reference use and break up complex topics so that they will be easier to learn. It will also be easier for us to maintain since it is clear where topics will go (trying to avoid duplicate data), so added bonus. Any issues? --Karl McClendon (talk) 12:23, 20 February 2008 (UTC)
- Yes, a good idea I think. The front page needs a bit of work. — Sam Wilson ( Talk • Contribs ) … 23:33, 27 July 2008 (UTC)
[edit] Experienced PHP developer
The Wikimedia Foundation office in San Francisco does have an opportunity for an experienced PHP developer. Dedalus (talk) 20:17, 11 April 2009 (UTC) | http://en.wikibooks.org/wiki/Talk:PHP_Programming | crawl-002 | refinedweb | 3,127 | 71.24 |
Some Jupyter Notebook / nbconvert Housekeeping Hints
A few snippets and bits of pieces regarding housekeeping around Jupyter notebooks.
Clearing Output Cells
Via Matthias Bussonnier, this handy command for rendering a version of a notebook with a the output cells cleared:
jupyter nbconvert --to notebook --ClearOutputPreprocessor.enabled=True NOTEBOOK.ipynb
Adding --inplace will rewrite the notebook with cleared output cells.
Custom Templates
If you have a custom template or a custom config file in the current directory, you can invoke them using:
jupyter nbconvert --config=my_config.py NOTEBOOK.ipynb
jupyter nbconvert --template=my_template.tpl NOTEBOOK.ipynb
I found running the --log-level=DEBUG flag was also handy…
Via MinRk, additional paths can be set using c.TemplateExporter.template_path.append('/path/to/templates') though I’m not really sure where that setting needs to be applied. (Whilst I love the Jupyter project, I really struggle to keep track of where things are supposed to be located and which bits are working/don’t work anymore:-(
He also notes that [a]bsolute template paths will also work if you specify: c.TemplateExporter.template_path.append('/'), adding the comment that [a]bsolute paths for templates should probably work without modifying template_path, but they don’t right now.
It would be really handy if the ability to specify an absolute path in the command line setting did work out of the can…
Split a Long Notebook into Multiple Sub-Notebooks
The Jupyter notebooks allow you to split long cells into two cells using the cursor as a split point, but how about splitting a long notebook into multiple notebooks?
The following test script will split a notebook into sub-notebooks at an explicit split point – a markdown cell containing just the string SPLIT NOTEBOOK.
import IPython.nbformat as nb import IPython.nbformat.v4.nbbase as nb4 mynb=nb.read('TEST_LONG_NOTEBOOK.ipynb',nb.NO_CONVERT) #Partition a long notebook into subnotebooks at specificed split points #Enter SPLIT NOTEBOOK on its own in a markdown cell to specify a split point c=1 test=nb4.new_notebook() for i in mynb['cells']: if (i['cell_type']=='markdown'): if ('SPLIT NOTEBOOK' in i['source']): nb.write(test,'subNotebook{}.ipynb'.format(c)) c=c+1 test=nb4.new_notebook() else: test.cells.append(nb4.new_markdown_cell(i['source'])) elif (i['cell_type']=='code'): cc=nb4.new_code_cell(i['source']) for o in i['outputs']: cc['outputs'].append(o) test.cells.append(cc) nb.write(test,'subNotebook{}.ipynb'.format(c))
I should probably tidy this up so that it reuses the original notebook name rather than the subNotebook stub. It might also be handy to turn this into a notebook extension that lets splits the current notebook into two relative to the current cursor location (e.g. all cells above the selected cell go in one sub-notebook, everything from the selected cell to the end of the notebook going into a second sub-notebook.
Another refinement might allow for the declaration of a comment set of cells to prefix each sub-notebook. By default, this could be the set of cells prior to the first split point. (Which is to say for N split points, there would be N, rather than N+1, sub-notebooks, the cells above the first split point appearing in each sub-notebook. The first sub-notebook would thus contain cells starting with the first cell after the first split point, prefixed by the cells appearing before the first split point; and the last sub-notebook would contain the cells starting with the first cell after the last split point, prefixed once again by the cells appearing before the first split point.
A second utility to merge, or concatenate, two or more notebooks when provided with their filenames might also be handy…
Anything Else?
So what other handy Jupyter notebook / nbconvert housekeeping hints and tricks am I missing? | https://blog.ouseful.info/2015/12/03/some-jupyter-notebook-nbconvert-housekeeping-hints/ | CC-MAIN-2018-26 | refinedweb | 635 | 51.68 |
Join devRant
Search - "pycharm"
- I really like this. Maybe you like this too and enjoy it or you dislike it and move on with your life29
- Today pycharm recommended me to simplify "if x > min and x > max"
Result: "if min < x < max"
Thank you for enlightening me, JetBrains6
-
-
-
-
-
- My PyCharm student license is expiring and I am no longer a student.
I think I need to enroll for another program to activate my PyCharm license.17
-
-
- never had problems with punctuation marks during coding, especially the notorious semicolons because I've always used an IDE, ain't gotta time to waste on compiler errors.
But today I meet my nemesis, a fucking comma wasted an hour of my precious time, causing my unit tests to fail in Python, my unit tests where expecting a list and the actual value is a tuple, it turned out that there was this trailing comma - which I don't know where the hell it came from - at the end of a function call that returns a list.
I only noticed this freaking comma after Pycharm indicated a conflict between the returned type and the expected type and underlined the culprit, that small invisible fucker 😬.
Thank you Pycharm and type hints in Python 3.
this is why, my fellow devs, you have to use an IDE.
PS: For those of you who aren't familiar with python, a trailing comma at end of a variable turns it into a one element tuple.
1, = (1,)2
-
- Opens pycharm
import time;
print(time.
*hits Ctrl+space*
>Auto complete not working
>Searches SO no answer
>Realized file saved as time.py
> Proceeds to contemplate career choice3
-
- >dad nagging to learn python
>i hate python
>cuz i hate snakes
>whatever
>so started learning it
>with some awesome video tutorials
>even though i like the instructor
>i find the language
>boring
>uhh
>why do u use this?
>oh and you say it is easy 4 begineers
>oh good
>then why does only
>del keyword gets highlighted in pycharm
>just to look cool i guess
>lua is way better
>hope lua is more used than python
>and more supported
>but i still like C#
Moral: C# rocks10
-
- VS Code is cool and everything, but man, PyCharm is some next-level shit. And the best part: free for students.16
-
- Intellij, Android Studio, PyCharm, ...
Because it looks the best for a full IDE (editors are another topic 😉). Especially with Kotlin:10
-
-
-
- Dear PyCharm,
When you decide to change the default templating language from Django to Jinja2, please tell me.
You owe me for psychiatrist bills2
-
-
-
-
- Are there any big advantages of using pycharm instead of sublime?
I'm learning Python and I already have sublime installed, should I use pycharm instead?10
-
-
-
- Fuck windows!
Now that I have your attention. My problem is with "IAR embedded workbench", not so much with windows but I'll get to that.
I've used that IDE for a few years.. 2 years ago. Since then I apparently forgot how to even create a project from scratch with adding all the necessary libraries and all that.
My initial deal with a client was to give them a solution using whatever tools I deem necessary. As I recently moved to linux and IAR is not available for that os.. and I also enjoyed working with CLion and PyCharm which Are available I decide to use CLion to write my C project.
A problem was that to compile code for microcontrollers I need tools unsupported by CLion.. oh well. I can do all the compilation and uploading of the code through terminal .. so I make a bash script that does it all. Super convenient. Development is going well and all.. until they ask me for the project.
I sent them the project so that they can see my progress. They can't do shit with what I gave them because they don't even have make on their machines let alone the compiler. All they have is IAR. But the guy that wants to see the code is not really a programmer.. he is a hardware specialist so I can't expect him to do anything more than use what he knows. He doesn't need or want to learn more right now.
So I go to windows and start porting my code to an IAR project and 2 days later I am still stuck with it. FUCK. Not only was the installation process horrible but the tools I wanted to install additionally did not work as promised either.
I know it took me about 2 days to setup all I needed on linux but I was enjoying it every step of the way. While this garbage is frustrating me so much. The fact that I used to do it before adds to the pain.
I am this close to telling them to just look at my code in notepad and I can setup a vm for them in which they can compile it if they really really need to.
If they just told me from the very start that they want me to work with IAR that would have been fine. I would have never seen the easier way and would have gladly figure it out then. Not now.1
-
-
- But seriously though, It's starting to break PyCharm. I have to uninstall them and just install one as my go to...2
-
- Just tried the new PYCHARM update
Honestly speaking I was a bit disappointed with the update as a whole.
Firstly, I it didn't recognize conda as the default development environment and moreover it didn't let me switch from virtualenvs also it took away my in built terminal option and to further aggravate my miseries the performance of the IDE as a whole had fallen quite a bit for instance at one point the ide alone was using around 1.5GiB of RAM and a huge
chunk of my CPU usage
-
- I've switched from pycharm to sublime to vsocde in a month, now vim is catching my eye, my mentor will kill me if i started using vim now but it's freaking interesting, will be learning a little bit of vim, will stick to vscode for long term i guess.13
-'m an android developer. It's Friday evening. Just received a call from my honcho. He asked me to "hack" one website and get all the data from it.
Now I'm downloading PyCharm...
It's not a regular "fucking hell". It's a shit. Period.2
- PyCharm's Warning: "Function name should be lowercase for PEP8 naming conventions."
Do Python developers not like camel case function names?3
- How to create an application using kivy.
- Install Kivy
- Open PyCharm and create your first application
- Follow the documentation
- Try to start the application
- The application crash for a arg that the run() method doesn't require
- Go to google to find the solution
- Don't find any solution
This is what I have done in the last 3 hours
Thanks Kivy3
-
- Pycharm why you no allow me to continue to use the professional edition...
Damnn and they way pycharm has served me well.11
-
-
-
- I declared it a Heisenbug!
So, basically I was starting multiple threads...
I was getting a list index out of range on line 268 which was a dict. Strange.
36 hours later, a lot of changes, I was still having the same error whatever I put on line 268, log, try, but when I got it on a comment... I lost it.
Restarted Pycharm.
Reset the branch to remote.
Everything worked fine.
Fuuuuuuuuuuu
- There's a humble bumble special Python with a 6-month Pycharm pro + 50$ in digital ocean + Fluent Python + talk.python classes + more at 25$.
A portion of the sales go to the Python foundation, it's a super good deal!!!1
-
- Why is it such a pain when I have to install all my external modules of Python for PyCharm? JetBrains products are cool, but this,... literally had to remember all the modules from scratch.1
-
- Until today
Get the pycharm annual subscription for 30% off!
Head to this link...
Disclaimer: I am not endorsed with Jetbrains s.r.o. or DSF in any way.
-
-
- was using separate console for running my django project.
But then, I discovered run and debug functionality of pycharm.
Awestruck. Feeling blessed.
- I been using PyCharm for a long time now to do my python work, what are everyone else's feelings on it?4
-
- PyCharm - worth buying?
Currently 30% off.
I'm learning to code Python at the moment and just using Sublime - so wondering whether it's worth it?
-
-
Top Tags | https://devrant.com/search?term=pycharm | CC-MAIN-2019-35 | refinedweb | 1,457 | 71.95 |
GETLINE(3) Linux Programmer's Manual GETLINE(3)
getline, getdelim - delimited string input
#include <stdio.h> ssize_t getline(char **lineptr, size_t *n, FILE *stream); ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): getline(), getdelim(): Since glibc 2.10: _POSIX_C_SOURCE >= 200809L Before glibc 2.10: _GNU_SOURCE. Alternatively, before calling getline(), *lineptr can contain a pointer to a malloc(3)-allocated buffer *n bytes in size. If the buffer is not large enough to hold the line, getline() resizes it with realloc(3), updating *lineptr and *n as necessary. In either case, on a successful call, *lineptr and *n will be updated to reflect the buffer address and allocated size respectively. getdelim() works like getline(), except that a line delimiter other than newline can be specified as the delimiter argument. As with getline(), a delimiter character is not added if one was not present in the input before end of file was reached..
EINVAL Bad arguments (n or lineptr is NULL, or stream is not valid). ENOMEM Allocation or reallocation of the line buffer failed.getline(), getdelim() │ Thread safety │ MT-Safe │ └──────────────────────┴───────────────┴─────────┘
Both getline() and getdelim() were originally GNU extensions. They were standardized in POSIX.1-2008.
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { FILE *stream; char *line = NULL; size_t len = 0; ssize_t nread; if (argc != 2) { fprintf(stderr, "Usage: %s <file>\n", argv[1]);); }
read(2), fgets(3), fopen(3), fread(3), scanf(3)
This page is part of release 4.11 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at. GNU 2017-03-13 GETLINE(3)
Pages that refer to this page: fgetc(3), gets(3), rpmatch(3) | http://man7.org/linux/man-pages/man3/getdelim.3.html | CC-MAIN-2017-22 | refinedweb | 302 | 57.16 |
The BeerSmith Icon Enhancement & Revision (BIER) Add-On
The BeerSmith Icon Enhancement & Revision (BIER) Add-On is a complete set of 140+ new, completely unofficial icons for BeerSmith homebrewing software. The BIER icon set has a simple, flat, material design inspired theme that is intended to enhance the overall experience of using BeerSmith. Of course, it’s based entirely on my own personal preferences. Should you so choose, you can also use the approach detailed below to further customize the icons to suit your own aesthetic.
Installation: To add BIER to your copy of BeerSmith, simply download the set of icons from the link above and extract the zip file. Follow the directions below according to your platform:
- For Windows, extract the “icons” folder in the zip file to your BeerSmith directory (which is usually located at “C:\Program Files (x86)\BeerSmith3\icons\”). You’ll need to replace the existing “icons” subdirectory in the process, so you may wish to back them up first to give you the option of easily returning to the stock UI.
- For Mac, click the BeerSmith app icon and click “Show Package Contents”. Go into “Contents”, then “Resources”. Backup the current “icons” folder there, then copy the icons folder you downloaded to this location. (Thanks /u/SlayterDevAgain from reddit for Mac install instructions!)
That’s it!
Compatability: BIER was designed for the Windows version of BeerSmith 3 and has been tested on Windows 7 and Windows 10. Please let me know if you try it out on additional platforms with success or failure!
Note: Many of the icons in the BIER Add-On are either from or inspired by The Noun Project, a creative commons resource for royalty free icons. See the list at the bottom of this page for more information on which artists helped make BIER possible.
Since the demise of BrewToad last December, I’ve been in the market for a new brewing software. As a casual brewer, I was averse to anything subscription-based, but I was also hesitant to spend time porting recipes into a free service that could go the way of BrewToad and … well, croak.
Enter BeerSmith. I had always heard good things about its capability, I liked its one-time licensing option, and its local installation / local recipe storage guaranteed that I could keep everything around for as long as I wanted to use it (Note: BeerSmith does have cloud storage options for convenience, as well). So, I decided to give it a go.
My first impression was one that I’ve seen echoed elsewhere:
If you’ve heard one thing about BeerSmith, it’s probably that it’s powerful. If you’ve heard two things about BeerSmith, the second is probably a criticism of its outdated UI. While a flashy interface is secondary to what’s under the hood, there’s still something to be said for user experience and how icon design can help or hinder a software’s workflow. For many of BeerSmith’s icons, it’s obvious that time and care went into designing them, but some compounding issues with the overall implementation can unfortunately detract from a very capable tool.
Stock BeerSmith 3 BeerSmith 3 with BIER Add-on
But, I was happy with BeerSmith otherwise. So, what else is there to do but spend hours customizing its look? Modding is Life!
Before I get into the details, I do want to be clear that I’m not out to disparage BeerSmith’s stock icons. It’s a real possibility that my taste is horrible and I’m making everything objectively worse. That’s the joy of customization! More to the point, in most cases within BeerSmith, it’s not a question of the icons’ quality, but with how they’re displayed or how they scale to smaller sizes. Let’s investigate…
Designing for Scale
As an example, consider the grains:
At 48 pixels square (BeerSmith’s maximum icon size) we have some perfectly fine stalks of grain. There’s some shading and a black outline that helps it stand out on both light and dark backgrounds, but we start running into issues when we reduce the resolution. At 16 pixels square (BeerSmith’s minimum icon size) most of the detail is lost, the colors blend into a dark brown mess, and it looks more like a chicken foot than anything you’d want in your beer. In the third version on the right, you can see a further loss in quality when the image is limited to full transparency only, which we’ll discuss in a minute.
Now, let’s look at the grain icon in BIER to see what we can do differently. For the grains, we start with a wheat icon by Alice Design from the Noun Project. It’s a simple design, and it renders clearly both large and small. There’s only one color, and the lines stay fairly sharp even at 16 pixels across. Consequently, we have an icon that is quickly identifiable and maintains its structure when scaled.
Transparency and Anti-Aliasing
Next, let’s get back to that transparency issue. Just to complicate things further, the BeerSmith UI for Windows has a glaring rendering issue with icons in the tree and list widgets. The icons look as you would expect if you open up the file externally, but they render poorly within BeerSmith itself.
After some experimentation, I realized this was an issue with transparency support. For some as-yet-unknown reason, the list and tree widgets only support full transparency (i.e., a pixel is either solid or invisible). Meanwhile, the source icon files are designed with an alpha channel that supports a full spectrum of partial transparency (translucency) from 0% to 100%. This translucency is critical in anti-aliasing the icon enough to look decent at 16 pixels wide, but due to this issue, any partial transparency is ignored and those pixels instead appear invisible. This is the reason the icons end up looking jagged and lumpy in lists and recipes.
As far as I can tell, this issue is limited to the 16×16 icons in the list and tree widgets, but that’s a fairly large percentage of the icons you’ll see in BeerSmith (recipes, ingredient lists, etc.). Correcting this would go a long way to improving BeerSmith’s UI, but that’s beyond what we can do by just replacing the icons. However, what we can do is design the 16×16 versions of our icons with this issue in mind to minimize the impact it has on the UI.
To combat BeerSmith’s Flawed Architecture for Rendering Transparency (hereafter referred to as FART), I modified the 16×16 versions of the replacement icons to remove translucency. This primarily consisted of putting the icon onto a white background and manually selecting which of the translucent pixels should be made fully transparent and which should be turned opaque by merging with the white background.
Depending on the icon and the colors involved, this can produce a white matte around the icon. Fortunately, it’s not usually noticeable in BeerSmith since the list and tree backgrounds are white even with the darker themes enabled. It can sometimes be seen when an item is highlighted, or in limited cases where an icon is used on a dark background, such as in the calendar. C’est la vie, that’s the best we can do by modding PNGs.
The Goals of BIER
(% of icons using color)
The two issues above were the core problems I tried to solve with the BIER add-on. In doing so, I also tried to adhere to the following principles:
- Minimalist icon designs that are clearly recognizable at 16 pixels or 1600 pixels, matching and mirroring each other wherever possible.
- A limited color palette. Altogether, BIER uses about 18 colors to keep the icons as simple, stark, and cohesive as possible.
- A tailored set of 16×16 icons specifically adjusted to mitigate the aforementioned transparency issue as much as possible.
Customizing Your Own Icons
“But wait!” you say, “I hate what you’ve done, and I’d rather make my own icons for BeerSmith!”
Well, I have some good news for you. With enough blood, sweat, and pixels, you sure can! If you take a peek into BeerSmith’s icons folder, you’ll see that its icons are saved as PNGs in four different sizes: 16, 24, 32, and 48 pixels square, plus an additional set at double those resolutions. The double resolution set is labeled 16@2x, 24@2x, 32@2x, and 48@2x (corresponding to 32, 48, 64, and 96 pixels). I wasn’t able to determine where, how, or if the 2x icons are actually used, but I replaced them all anyway for completeness (the same is true for a handful of icon designs that seem to be vestigial or for unimplemented features).
Of course, you may balk at the idea of resizing and saving over a hundred different icons eight times each, especially if you keep tweaking the designs and need to regenerate all 8 files every time. Well, balk no more, for automation shall prevail!
If your image editing software has batch processing, that’s one solution. Personally, I opted to write a Python script that finds all PNG files in a directory and uses Pillow, a fork of the Python Imaging Library, to generate the eight sizes we need with their appropriate filenames. Every time I made changes to the icons, I ran the script to generate the complete set and port it into BeerSmith.
import os from PIL import Image dir1 = "D:\\BeerSmith Custom Icons\\Full Size" # Source Directory dir2 = "D:\\BeerSmith Custom Icons\\Resized" # Output Directory # List of Sizes to Generate for Each Image outSizes = [(16,16),(24,24),(32,32),(48,48),(32,32),(48,48),(64,64),(96,96)] # List of Strings (Added to Base Filename) for Each Size outNames = ['16','24','32','48','16@2x','24@2x','32@2x','48@2x'] for fileName in os.listdir(dir1): if fileName.endswith(".png"): img = Image.open(dir1 + "\\" + fileName) for i, outName in enumerate(outNames): img_out = img.resize(outSizes[i], Image.BICUBIC) img_out.save(dir2 + "\\" + fileName[:-4] + outName + '.png')
That’s all there is to it. Design each icon at a convenient size larger than 96 pixels (the size of the “48@2x” file), then run the script to generate all the necessary sizes of all the icons. Lastly, fine tune the 16×16 icons to keep them looking sharp despite the rendering issues in the list and tree widgets.
What Exactly’s in the BIER Add-On?
If you want to scope it out before you download it for yourself, here’s some more examples of what’s in the pack and how it looks once you add it to BeerSmith:
I replaced the beer and wine color scales with a new nonic pint glass & wine glass of my own design. Having found that my recipes in BeerSmith were a smidge off from the color I expected, I made small tweaks to the colors used in the icons for each SRM value (new scale shown to the right, along with red and white wine colors). Of course, if you want to adjust it further, you can do so by simply changing the filenames of the icons.
BeerSmith also conveniently has an option labeled “Use New Beer Glass Icons” option under Look & Feel Options > BeerSmith Color Theme. The BIER add-on will replace the new icon set, but not the old. So, when this option is checked and BIER is installed, you’ll see the glasses above, but you can also uncheck it to revert to BeerSmith’s older stock pint glasses.
Lastly, here’s just a few examples of BeerSmith with the BIER add-on (left) and without (right):
I hope that you find the BIER pack useful and enjoy the new streamlined look in your BeerSmith life. It was a fun project to tackle. Cheers!
Made Possible by The Noun Project
This project uses some original designs in concert with a variety of icon styles from The Noun Project either as-is, with some color adjustment, or with other modifications. In any case, many thanks and credit to the wonderful designers of TNP who made the BIER icon pack possible:
Appearance by Ayub Irawan
Apple by Lyhn
Arrow Left by Mike Rowe
Binoculars by Kiran
Bubbles by Rudez Studio
Calendar by Adrien Coquet
Carboy by Mark Caron
Check by Focus
Clock by Yo! Baba
Cloud by Humantech
Copy by Mochammad Kafi
Dollar by Musmellow
Flag by Vectors Point
Floppy by Markus
Folder by Saifurrijal
Gauge by Alexander Skowalsky
Gear by Humantech
Globe by Piotrek Chuchla
Heart by Ben Iconator
Home by Frey Wazza
Honey by Styleku
Hops by David Lamm
Key by Kyle Dodson
Magnifying Glass by Vectors Market
Measuring Cup by Jake Park
Monitor by TS Graphics
Note by Benny Forsberg
Options by Marie Van den Broeck
Package by Kokota
Paper Bag by Arthur Shlain
Paperclip by Zulfahmi Al Ridhawi
Paste by Omar Safaa
Pillow by Milko BG
Pint Glass by Mark Caron
Plus or Minus by Muneer A Safiah
Print by Georgiana Ionescu
Profile by ghufronagustian
Puzzle by Bluetip Design
Scissors by Icon Lauk
Shopping Cart by Adrien Coquet
Thermometer by Guillem Sevilla
Tools by HrBonPro
Undo by Farrel Putra
Vial by Arafat Uddin
Vials by Yo! Baba
Warning by Gregor Cresnar
Water by Bluetip Design
Weight by Styleku
Wheat by Alice Design
Window by Icon 54
Wizard by Ralf Schmitzer
X by Fardan
| https://zembacraftworks.com/author/zembacraftworks/ | CC-MAIN-2020-16 | refinedweb | 2,269 | 65.46 |
Yes this is for my homework.
I am not lazy getting other people to do it for me i am just stuck.
This is the code i have. It sux and has too many errors to even list the errors on my compiler.
I am trying to create two functions to define the x,y and z co-ordinates of a line at its two ends, and store them in a matrix.
Very boring and difficult as I'm new to ++ but my talents lie elsewhere.
Someone who is good with ++ would probably be able to sort this code out in a second.
So someone please help me if anyone feels like it.
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
double line[2][3];
double x,y;
int menu_option;
printf("Please choose from the menu\n\n");
printf("1.\t\tTranslate the line\n");
printf("2.\t\tScale the line\n");
printf("3.\t\tRotate the line\n");
printf("4.\t\tChange position of L0 (Where P=0)\n");
printf("5.\t\tChange position of L1 (Where P=1)\n");
printf("6.\t\tEvaluate a point on the line\n");
printf("7.\t\tExit the program\n\n");
printf("Enter your choice here\n\n\n");
scanf("%lf", &menu_option);
printf("\n\n\n");
}
//Function defining 1st point of array
{
void enteringp1(int [0][0], int [0][1], int [0][2]);
printf("Please enter the set of co-ordinates for the first point, P1, separated by spaces.\n\n");
scanf("%lf %lf %lf", &[0][0] &[0][1] &[0][2]);
printf("\n\nThe co-ordinates for the first point, P1 are\t\t %lf, %lf, %lf\n\n" [0][0] [0][1] [0][2]);
}
//Function defining 2nd of the array
{
void enteringp2(int [1][0], int[1][1], int [1][2]);
printf("Please enter the set of co-ordinates for the second point, P2, seperated by spaces.\n\n");
scanf("%lf %lf %lf", &[1][0] &[1][1] &[1][2]);
printf("\n\nThe co-ordinates for the second point, P2 are\t\t %lf, %lf, &lf\n\n" [1][0] [1][1] [1][2]);
} | http://cboard.cprogramming.com/cplusplus-programming/73012-defining-matricies-printable-thread.html | CC-MAIN-2015-18 | refinedweb | 353 | 75.3 |
:
import aiohttp import())
Server.get('/{name}', handle)]) web.run_app(app)
Documentation
Demos
External links
Feel free to make a Pull Request for adding your link to these pages!
Communication channels
aio-libs google group:
Feel free to post your questions and ideas here.
gitter chat
We support Stack Overflow. Please add aiohttp tag to your question there.
Requirements
Python >= 3.5.3
-
-
-
-
-
Optionally you may install the cChardet and aiodns libraries (highly recommended for sake of speed).
License
aiohttp is offered under the Apache 2 license.
Keepsafe
The aiohttp community would like to thank Keepsafe () for its support in the early days of the project.
Source code
The latest developer version is available in a GitHub repository:
Benchmarks
If you are interested in efficiency, the AsyncIO community maintains a list of benchmarks on the official wiki:
Changelog
3.5.2 (2019-01-08)
Features
Bugfixes
Preserve MultipartWriter parts headers on write.
Refactor the way how Payload.headers are with collections.abc.MutableMapping to avoid a deprecation warning. #3480
Payload.size type annotation changed from Optional[float] to Optional[int]. #3484
Ignore done tasks when cancels pending activities on web.run_app finalization. #3497
Improved Documentation
Misc
3.5.1 (2018-12-24)
Fix a regression about ClientSession._requote_redirect_url modification in debug mode. for which was not logged, when it is caught in the handler. (#3414)
Improved Documentation
Deprecations and Removals and connector.loop properties. ( and conn_timeout in ClientSession constructor. (#3438)
Misc
#3341, #3351
Project details
Release history Release notifications | RSS feed
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/aiohttp/4.0.0a0/ | CC-MAIN-2022-40 | refinedweb | 271 | 53.07 |
Hello everybody, I'm pretty much a beginner at using C, so my problem shouldn't be too difficult for you to solve, I hope. I wrote this program to sum all the even numbers in the fibonacci sequence below 4 million:
When I run this program, it returns "The answer is 0.", and I can't figure out why. Any ideas?When I run this program, it returns "The answer is 0.", and I can't figure out why. Any ideas?Code:
#include <stdio.h>
int main()
{
int current = 0;
int prev = 1;
int prev2 = 0;
int sum = 0;
do {
current += (prev + prev2);
prev2 = prev;
prev = current;
if (current%2==0){
sum += current;
}
} while (current < 4000000);
printf("The answer is %d.", sum);
getchar();
return 0;
} | http://cboard.cprogramming.com/c-programming/111669-simple-program-not-working-dont-know-why-printable-thread.html | CC-MAIN-2015-18 | refinedweb | 126 | 73.68 |
As with my first Introduction to COM article, I have written this tutorial for programmers who are just starting out in COM and need some help in understanding the basics. This article covers COM from the server side of things, explaining the steps required to write your own COM interfaces and COM servers, as well as detailing what exactly happens in a COM server when the COM library calls into it.
If you've read my first Intro to COM article, you should be well-versed in what's involved in using COM as a client. Now it's time to approach COM from the other side - the COM server. I'll cover how to write a COM server from scratch in plain C++, with no class libraries involved. While this isn't necessarily the approach usually taken nowadays, seeing all the code that goes into making a COM server - with nothing hidden away in a pre-built library - is really the best way to fully understand everything that happens in the server.
This article assumes you are proficient in C++ and understand the concepts and terminology covered in the first Intro to COM article. The sections in the article are:
Quick Tour of a COM Server - Describes the basic requirements of a COM server.
Server Lifetime Management - Describes how a COM server controls how long it remains loaded.
Implementing Interfaces, Starting With IUnknown - Shows how to write an implementation of an interface in a C++ class, and describes the purpose of the IUnknown methods.
IUnknown
Inside CoCreateInstance() - An overview of what happens when you call CoCreateInstance().
CoCreateInstance()
COM Server Registration - Describes the registry entries needed to properly register a COM server.
Creating COM Objects - The Class Factory - Describes the process of creating COM objects for your client program to use.
A Sample Custom Interface - Some sample code that illustrates the concepts from the previous sections.
A Client to Use Our Server - Demonstrates a simple client app we can use to test our server.
Other Details - Notes on the source code and debugging.
In this article, we'll be looking at the simplest type of COM server, an in-process server. "In-process" means that the server is loaded into the process space of the client program. In-process (or "in-proc") servers are always DLLs, and must be on the same computer as the client program.
An in-proc server must meet two criteria before it can be used by the COM library:
HKEY_CLASSES_ROOT\CLSID
DllGetClassObject()
This is the bare minimum you need to do to get an in-proc server working. A key with the server's GUID as its name must be created under the HKEY_CLASSES_ROOT\CLSID key, and that key must contain a couple of values listing the server's location and its threading model. The DllGetClassObject() function is called by the COM library as part of the work done by the CoCreateInstance() API.
There are three other functions that are usually exported as well:
DllCanUnloadNow()
DllRegisterServer()
DllUnregisterServer()
Of course, it's not enough to just export the right functions - they have to conform to the COM spec so that the COM library and the client program can use the server.
One unusual aspect of DLL servers is that they control how long they stay loaded. "Normal" DLLs are passive and are loaded/unloaded at the whim of the application using them. Technically, DLL servers are passive as well, since they are DLLs after all, but the COM library provides a mechanism that allows a server to instruct COM to unload it. This is done through the exported function DllCanUnloadNow(). The prototype for this function is:
HRESULT DllCanUnloadNow();
When the client app calls the COM API CoFreeUnusedLibraries(), usually during its idle processing, the COM library goes through all of the DLL servers that the app has loaded and queries each one by calling its DllCanUnloadNow() function. If a server needs to remain loaded, it returns S_FALSE. On the other hand, if a server determines that it no longer needs to be in memory, it can return S_OK to have COM unload it.
CoFreeUnusedLibraries()
S_FALSE
S_OK
The way a server tells if it can be unloaded is a simple reference count. An implementation of DllCanUnloadNow() might look like this:
extern UINT g_uDllRefCount; <FONT color=#009900>// server's reference count</FONT>
HRESULT DllCanUnloadNow()
{
return (g_uDllRefCount > 0) ? S_FALSE : S_OK;
}
I will cover how the reference count is maintained in the next section, once we get to some sample code.
Recall that every interface derives from IUnknown. This is because IUnknown covers two basic features of COM objects - reference counting and interface querying. When you write a coclass, you also write an implementation of IUnknown that meets your needs. Let's take as an example a coclass that just implements IUnknown -- the simplest possible coclass you could write. We will implement IUnknown in a C++ class called CUnknownImpl. The class declaration looks like this:
CUnknownImpl
class CUnknownImpl : public IUnknown
{
public:
<FONT color=#009900>// Construction and destruction</FONT>
CUnknownImpl();
virtual ~CUnknownImpl();
<FONT color=#009900>// IUnknown methods</FONT>
ULONG AddRef();
ULONG Release)();
HRESULT QueryInterface( REFIID riid, void** ppv );
protected:
UINT m_uRefCount; <FONT color=#009900>// object's reference count</FONT>
};
The constructor and destructor manage the server's reference count:
CUnknownImpl::CUnknownImpl()
{
m_uRefCount = 0;
g_uDllRefCount++;
}
CUnknownImpl::~CUnknownImpl()
{
g_uDllRefCount--;
}
The constructor is called when a new COM object is created, so it increments the server's reference count to keep the server in memory. It also initializes the object's reference count to zero. When the COM object is destroyed, it decrements the server's reference count.
These two methods control the lifetime of the COM object. AddRef() is simple:
AddRef()
ULONG CUnknownImpl::AddRef()
{
return ++m_uRefCount;
}
AddRef() simply increments the object's reference count, and returns the updated count.
Release() is a bit less trivial:
Release()
ULONG CUnknownImpl::Release()
{
ULONG uRet = --m_uRefCount;
if ( 0 == m_uRefCount ) <FONT color=#009900>// releasing last reference?</FONT>
delete this;
return uRet;
}
In addition to decrementing the object's reference count, Release() destroys the object if it has no more outstanding references. Release() also returns the updated reference count. Notice that this implementation of Release() assumes that the COM object was created on the heap. If you create an object on the stack or at global scope, things will go awry when the object tries to delete itself.
Now it should be clear why it's important to call AddRef() and Release() properly in your client apps! If you don't call them correctly, the COM objects you're using may be destroyed too soon, or not at all. And if COM objects get destroyed too soon, that can result in an entire COM server being yanked out of memory, causing your app to crash the next time it tries to access code that was in that server.
If you've done any multithreaded programming, you might be wondering about the thread-safety of using ++ and -- instead of InterlockedIncrement() and InterlockedDecrement(). ++ and -- are perfectly safe to use in single-threaded servers, because even if the client app is multi-threaded and makes method calls from different threads, the COM library serializes method calls into our server. That means that once one method call begins, all other threads attempting to call methods will block until the first method returns. The COM library itself ensures that our server will never be entered by more than one thread at a time.
++
--
InterlockedIncrement()
InterlockedDecrement()
QueryInterface(), or QI() for short, is used by clients to request different interfaces from one COM object. Since our sample coclass only implements one interface, our QI() will be easy. QI() takes two parameters: the IID of the interface being requested, and a pointer-sized buffer where QI() stores the interface pointer if the query is successful.
QueryInterface()
QI()
HRESULT CUnknownImpl::QueryInterface ( REFIID riid, void** ppv )
{
HRESULT hrRet = S_OK;
<FONT color=#009900>// Standard QI() initialization - set *ppv to NULL.</FONT>
*ppv = NULL;
<FONT color=#009900>// If the client is requesting an interface we support, set *ppv.</FONT>
if ( IsEqualIID ( riid, IID_IUnknown ))
{
*ppv = (IUnknown*) this;
}
else
{
<FONT color=#009900>// We don't support the interface the client is asking for.</FONT>
hrRet = E_NOINTERFACE;
}
<FONT color=#009900>// If we're returning an interface pointer, AddRef() it.</FONT>
if ( S_OK == hrRet )
{
((IUnknown*) *ppv)->AddRef();
}
return hrRet;
}
There are three different things done in QI():
*ppv = NULL;
riid
if ( IsEqualIID ( riid, IID_IUnknown ))
((IUnknown*) *ppv)->AddRef();
Note that the AddRef() is critical. This line:
*ppv = (IUnknown*) this;
creates a new reference to the COM object, so we must call AddRef() to tell the object that this new reference exists. The cast to IUnknown* in the AddRef() call may look odd, but in a non-trivial coclass' QI(), *ppv may be something other than an IUnknown*, so it's a good idea to get in the habit of using that cast.
IUnknown*
*ppv
Now that we've covered some internal details of DLL servers, let's step back and see how our server is used when a client calls CoCreateInstance().
Back in the first Intro to COM article, we saw the CoCreateInstance() API, which creates a COM object when a client requests one. From the client's perspective, it's a black box. Just call CoCreateInstance() with the right parameters and BAM! you get a COM object back. Of course, there's no black magic involved; a well-defined process happens in which the COM server gets loaded, creates the requested COM object, and returns the requested interface.
Here's a quick overview of the process. There are a few unfamiliar terms here, but don't worry; I'll cover everything in the following sections.
CreateInstance()
For anything else to work, a COM server must be properly registered in the Windows registry. If you look at the HKEY_CLASSES_ROOT\CLSID key, you'll see a ton of subkeys. HKCR\CLSID holds a list of every COM server available on the computer. When a COM server is registered (usually via DllRegisterServer()), it creates a key under the CLSID key whose name is the server's GUID in standard registry format. An example of registry format is:
HKCR\CLSID
CLSID
{067DF822-EAB6-11cf-B56E-00A0244D5087}
The braces and hyphens are required, and letters can be either upper- or lower-case.
The default value of this key is a human-readable name for the coclass, which should be suitable for display in a UI by tools like the OLE/COM Object Viewer that ships with VC.
More information can be stored in subkeys under the GUID key. Which subkeys you need to create depends greatly on what type of COM server you have, and how it can be used. For the purposes of our simple in-proc server, we only need one subkey: InProcServer32.
InProcServer32
The InProcServer32 key contains two strings: the default value, which is the full path to the server DLL; and a ThreadingModel value that holds (what else?) threading model. Threading models are beyond the scope of this article, but suffice it to say that for single-threaded servers, the model to use is Apartment.
ThreadingModel
Apartment
Back when we were looking at the client side of COM, I talked about how COM has its own language-independent procedures for creating and destroying COM objects. The client calls CoCreateInstance() to create a new COM object. Now, we'll see how it works on the server side.
Every time you implement a coclass, you also write a companion coclass which is responsible for creating instances of the first coclass. This companion is called the class factory for the coclass and its sole purpose is to create COM objects. The reason for having a class factory is language-independence. COM itself doesn't create COM objects, because that wouldn't be language- and implementation-independent.
When a client wants to create a COM object, the COM library requests the class factory from the COM server. The class factory then creates the COM object which gets returned to the client. The mechanism for this communication is the exported function DllGetClassObject()..
COleObjectFactory
When the COM library calls DllGetClassObject(), it passes the CLSID that the client is requesting. The server is responsible for creating the class factory for the requested CLSID and returning it. A class factory is itself a coclass, and implements the IClassFactory interface. If DllGetClassObject() succeeds, it returns an IClassFactory pointer to the COM library, which then uses IClassFactory methods to create an instance of the COM object the client requested.
IClassFactory
The IClassFactory interface looks like this:
struct IClassFactory : public IUnknown
{
HRESULT CreateInstance( IUnknown* pUnkOuter, REFIID riid,
void** ppvObject );
HRESULT LockServer( BOOL fLock );
};
CreateInstance() is the method that creates new COM objects. LockServer() lets the COM library increment or decrement the server's reference count when necessary.
LockServer()
For an example of class factories at work, let's start taking a look at the article's sample project. It's a DLL server that implements an interface ISimpleMsgBox in a coclass called CSimpleMsgBoxImpl.
ISimpleMsgBox
CSimpleMsgBoxImpl
Our new interface is called ISimpleMsgBox. As with all interfaces, it must derive from IUnknown. There's just one method, DoSimpleMsgBox(). Note that it returns the standard type HRESULT. All methods you write should have HRESULT as the return type, and any other data you need to return to the caller should be done through pointer parameters.
DoSimpleMsgBox()
HRESULT
struct ISimpleMsgBox : public IUnknown
{
);
};
struct __declspec(uuid("{7D51904D-1645-4a8c-BDE0-0F4A44FC38C4}"))
ISimpleMsgBox;
(The __declspec line assigns a GUID to the ISimpleMsgBox symbol, and that GUID can later be retrieved with the __uuidof operator. Both __declspec and __uuidof are Microsoft C++ extensions.)
__declspec
__uuidof
The second parameter of DoSimpleMsgBox() is of type BSTR. BSTR stands for "binary string" - COM's representation of a fixed-length sequence of bytes. BSTRs are used mainly by scripting clients like Visual Basic and the Windows Scripting Host.
BSTR
This interface is then implemented by a C++ class called CSimpleMsgBoxImpl. Its definition is:
class CSimpleMsgBoxImpl : public ISimpleMsgBox
{
public:
CSimpleMsgBoxImpl();
virtual ~CSimpleMsgBoxImpl();
);
protected:
ULONG m_uRefCount;
};
class __declspec(uuid("{7D51904E-1645-4a8c-BDE0-0F4A44FC38C4}"))
CSimpleMsgBoxImpl;
When a client wants to create a SimpleMsgBox COM object, it would use code like this:
SimpleMsgBox
ISimpleMsgBox* pIMsgBox;
HRESULT hr;
hr = CoCreateInstance( __uuidof(CSimpleMsgBoxImpl), <FONT color=#009900>// CLSID of the coclass</FONT>
NULL, <FONT color=#009900>// no aggregation</FONT>
CLSCTX_INPROC_SERVER, <FONT color=#009900>// the server is in-proc</FONT>
__uuidof(ISimpleMsgBox), <FONT color=#009900>// IID of the interface
// we want</FONT>
(void**) &pIMsgBox ); <FONT color=#009900>// address of our
// interface pointer</FONT>
Our SimpleMsgBox class factory is implemented in a C++ class called, imaginatively enough, CSimpleMsgBoxClassFactory:
CSimpleMsgBoxClassFactory
class CSimpleMsgBoxClassFactory : public IClassFactory
{
public:
CSimpleMsgBoxClassFactory();
virtual ~CSimpleMsgBoxClassFactory();
<FONT color=#009900>// IUnknown methods</FONT>
ULONG AddRef();
ULONG Release();
HRESULT QueryInterface( REFIID riid, void** ppv );
<FONT color=#009900>// IClassFactory methods</FONT>
HRESULT CreateInstance( IUnknown* pUnkOuter, REFIID riid, void** ppv );
HRESULT LockServer( BOOL fLock );
protected:
ULONG m_uRefCount;
};
The constructor, destructor, and IUnknown methods are done just like the earlier sample, so the only new things are the IClassFactory methods. LockServer() is, as you might expect, rather simple:
HRESULT CSimpleMsgBoxClassFactory::LockServer ( BOOL fLock )
{
fLock ? g_uDllLockCount++ : g_uDllLockCount--;
return S_OK;
}
Now for the interesting part, CreateInstance(). Recall that this method is responsible for creating new CSimpleMsgBoxImpl objects. Let's take a closer look at the prototype and parameters:
HRESULT CSimpleMsgBoxClassFactory::CreateInstance ( IUnknown* pUnkOuter,
REFIID riid,
void** ppv );
pUnkOuter is only used when this new object is being aggregated, and points to the "outer" COM object, that is, the object that will contain the new object. Aggregation is way beyond the scope of this article, and our sample object will not support aggregation.
pUnkOuter
riid and ppv are used just as in QueryInterface() - they are the IID of the interface the client is requesting, and a pointer-sized buffer to store the interface pointer.
ppv
Here's the CreateInstance() implementation. It starts with some parameter validation and initialization.
HRESULT CSimpleMsgBoxClassFactory::CreateInstance ( IUnknown* pUnkOuter,
REFIID riid,
void** ppv )
{
<FONT color=#009900>// We don't support aggregation, so pUnkOuter must be NULL.</FONT>
if ( NULL != pUnkOuter )
return CLASS_E_NOAGGREGATION;
<FONT color=#009900>// Check that ppv really points to a void*.</FONT>
if ( IsBadWritePtr ( ppv, sizeof(void*) ))
return E_POINTER;
*ppv = NULL;
We've checked that the parameters are valid, so now we can create a new object.
CSimpleMsgBoxImpl* pMsgbox;
<FONT color=#009900>// Create a new COM object!</FONT>
pMsgbox = new CSimpleMsgBoxImpl;
if ( NULL == pMsgbox )
return E_OUTOFMEMORY;
Finally, we QI() the new object for the interface that the client is requesting. If the QI() fails, then the object is unusable, so we delete it.
HRESULT hrRet;
<FONT color=#009900>// QI the object for the interface the client is requesting.</FONT>
hrRet = pMsgbox->QueryInterface ( riid, ppv );
<FONT color=#009900>// If the QI failed, delete the COM object since the client isn't able
// to use it (the client doesn't have any interface pointers on the
// object).</FONT>
if ( FAILED(hrRet) )
delete pMsgbox;
return hrRet;
}
Let's take a closer look at the internals of DllGetClassObject(). Its prototype is:
HRESULT DllGetClassObject ( REFCLSID rclsid, REFIID riid, void** ppv );
rclsid is the CLSID of the coclass the client wants. The function must return the class factory for that coclass.
rclsid
riid and ppv are, again, like the parameters to QI(). In this case, riid is the IID of the interface that the COM library is requesting on the class factory object. This is usually IID_IClassFactory.
IID_IClassFactory
Since DllGetClassObject() creates a new COM object (the class factory), the code looks rather similar to IClassFactory::CreateInstance(). We start off with some validation and initialization.
IClassFactory::CreateInstance()
HRESULT DllGetClassObject ( REFCLSID rclsid, REFIID riid, void** ppv )
{
<FONT color=#009900>// Check that the client is asking for the CSimpleMsgBoxImpl factory.</FONT>
if ( !InlineIsEqualGUID ( rclsid, __uuidof(CSimpleMsgBoxImpl) ))
return CLASS_E_CLASSNOTAVAILABLE;
<FONT color=#009900>// Check that ppv really points to a void*.</FONT>
if ( IsBadWritePtr ( ppv, sizeof(void*) ))
return E_POINTER;
*ppv = NULL;
The first if statement checks the rclsid parameter. Our server only contains one coclass, so rclsid must be the CLSID of our CSimpleMsgBoxImpl class. The __uuidof operator retrieves the GUID assigned to CSimpleMsgBoxImpl earlier with the __declspec(uuid()) declaration. InlineIsEqualGUID() is an inline function that checks if two GUIDs are equal.
__declspec(uuid())
InlineIsEqualGUID()
The next step is to create a class factory object.
CSimpleMsgBoxClassFactory* pFactory;
<FONT color=#009900>// Construct a new class factory object.</FONT>
pFactory = new CSimpleMsgBoxClassFactory;
if ( NULL == pFactory )
return E_OUTOFMEMORY;
Here's where things differ a bit from CreateInstance(). Back in CreateInstance(), we just called QI(), and if it failed, we deleted the COM object. Here is a different way of doing things.
We can consider ourselves to be a client of the COM object we just created, so we call AddRef() on it to make its reference count 1. We then call QI(). If QI() is successful, it will AddRef() the object again, making the reference count 2. If QI() fails, the reference count will remain 1.
After the QI() call, we're done using the class factory object, so we call Release() on it. If the QI() failed, the object will delete itself (because the reference count will be 0), so the end result is the same.
<FONT color=#009900>// AddRef() the factory since we're using it.</FONT>
pFactory->AddRef();
HRESULT hrRet;
<FONT color=#009900>// QI() the factory for the interface the client wants.</FONT>
hrRet = pFactory->QueryInterface ( riid, ppv );
<FONT color=#009900>// We're done with the factory, so Release() it.</FONT>
pFactory->Release();
return hrRet;
}
I showed a QI() implementation earlier, but it's worth seeing the class factory's QI() since it is a realistic example, in that the COM object implements more than just IUnknown. First we validate the ppv buffer and initialize it.
HRESULT CSimpleMsgBoxClassFactory::QueryInterface( REFIID riid, void** ppv )
{
HRESULT hrRet = S_OK;
<FONT color=#009900>// Check that ppv really points to a void*.</FONT>
if ( IsBadWritePtr ( ppv, sizeof(void*) ))
return E_POINTER;
<FONT color=#009900>// Standard QI initialization - set *ppv to NULL.</FONT>
*ppv = NULL;
Next we check riid and see if it's one of the interfaces the class factory implements: IUnknown or IClassFactory.
<FONT color=#009900>// If the client is requesting an interface we support, set *ppv.</FONT>
if ( InlineIsEqualGUID ( riid, IID_IUnknown ))
{
*ppv = (IUnknown*) this;
}
else if ( InlineIsEqualGUID ( riid, IID_IClassFactory ))
{
*ppv = (IClassFactory*) this;
}
else
{
hrRet = E_NOINTERFACE;
}
Finally, if riid was a supported interface, we call AddRef() on the interface pointer, then return.
<FONT color=#009900>// If we're returning an interface pointer, AddRef() it.</FONT>
if ( S_OK == hrRet )
{
((IUnknown*) *ppv)->AddRef();
}
return hrRet;
}
Last but not least, we have the code for the one and only method of ISimpleMsgBox, DoSimpleMsgBox(). We first use the Microsoft extension class _bstr_t to convert bsMessageText to a TCHAR string.
_bstr_t
bsMessageText
TCHAR
HRESULT CSimpleMsgBoxImpl::DoSimpleMsgBox ( HWND hwndParent,
BSTR bsMessageText )
{
_bstr_t bsMsg = bsMessageText;
LPCTSTR szMsg = (TCHAR*) bsMsg; <FONT color=#009900>// Use _bstr_t to convert the
// string to ANSI if necessary.</FONT>
After we do the conversion, we show the message box, and then return.
MessageBox ( hwndParent, szMsg, _T("Simple Message Box"), MB_OK );
return S_OK;
}
So now that we've got this super-spiffy COM server all done, how do we use it? Our interface is a custom interface, which means it can only be used by a C or C++ client. (If our coclass also implemented IDispatch, then we could write a client in practically anything - Visual Basic, Windows Scripting Host, a web page, PerlScript, etc. But that discussion is best left for another article.) I've provided a simple app that uses ISimpleMsgBox.
IDispatch
The app based on the Hello World sample built by the Win32 Application AppWizard. The File menu contains two commands for testing the server:
File
The Test MsgBox COM Server command creates a CSimpleMsgBoxImpl object and calls DoSimpleMsgBox(). Since this is a simple method, the code isn't very long. We first create a COM object with CoCreateInstance().
Test MsgBox COM Server
void DoMsgBoxTest(HWND hMainWnd)
{
ISimpleMsgBox* pIMsgBox;
HRESULT hr;
hr = CoCreateInstance ( __uuidof(CSimpleMsgBoxImpl), <FONT color=#009900>// CLSID of coclass</FONT>
NULL, <FONT color=#009900>// no aggregation</FONT>
CLSCTX_INPROC_SERVER, <FONT color=#009900>// use only in-proc
// </FONT><FONT color=#009900>servers</FONT>
__uuidof(ISimpleMsgBox), <FONT color=#009900>// IID of the interface
// we want</FONT>
(void**) &pIMsgBox ); <FONT color=#009900>// buffer to hold the
// interface pointer</FONT>
if ( FAILED(hr) )
return;
Then we call DoSimpleMsgBox() and release our interface.
pIMsgBox->DoSimpleMsgBox ( hMainWnd, _bstr_t("Hello COM!") );
pIMsgBox->Release();
}
That's all there is to it. There are many TRACE statements throughout the code, so if you run the test app in the debugger, you can see where each method in the server is being called.
TRACE
The other File menu command calls the CoFreeUnusedLibraries() API so you can see the server's DllCanUnloadNow() function in action.
There are several macros used in COM code that hide implementation details and allow the same declarations to be used by C and C++ clients. I haven't used the macros in this article, but the sample project does use them, so you need to understand what they mean. Here's the proper declaration of ISimpleMsgBox:
struct ISimpleMsgBox : public IUnknown
{
<FONT color=#009900>// IUnknown methods</FONT>
STDMETHOD_(ULONG, AddRef)() PURE;
STDMETHOD_(ULONG, Release)() PURE;
STDMETHOD(QueryInterface)(REFIID riid, void** ppv) PURE;
<FONT color=#009900>// ISimpleMsgBox methods</FONT>
STDMETHOD(DoSimpleMsgBox)(HWND hwndParent, BSTR bsMessageText) PURE;
};
STDMETHOD() includes the virtual keyword, a return type of HRESULT, and the __stdcall calling convention. STDMETHOD_() is the same, except you can specify a different return type. PURE expands to "=0" in C++ to make the function a pure virtual function.
STDMETHOD()
virtual
__stdcall
STDMETHOD_()
PURE
STDMETHOD() and STDMETHOD_() have corresponding macros used in the implementation of methods - STDMETHODIMP and STDMETHODIMP_(). For example, here's the implementation of DoSimpleMsgBox():
STDMETHODIMP
STDMETHODIMP_()
STDMETHODIMP CSimpleMsgBoxImpl::DoSimpleMsgBox ( HWND hwndParent,
BSTR bsMessageText )
{
...
}
Finally, the standard exported functions are declared with the STDAPI macro, such as:
STDAPI
STDAPI DllRegisterServer()
STDAPI includes the return type and calling convention. One downside to using STDAPI is that you can't use __declspec(dllexport) with it, because of how STDAPI expands. You instead have to export the function using a .DEF file.
__declspec(dllexport)
The server implements the DllRegisterServer() and DllUnregisterServer() functions that I mentioned earlier. Their job is to create and delete the registry entries that tell COM about our server. The code is all boring registry manipulation, so I won't repeat it here, but here's a list of the registry entries created by DllRegisterServer():
Key name
Values in the key
HKEY_CLASSES_ROOT
CLSID
{7D51904E-1645-4a8c-BDE0-0F4A44FC38C4}
InProcServer32
The included sample code contains the source for both the COM server and the test client app. There is a workspace file, SimpleComSvr.dsw, which you can load to work on both the server and client app at the same time. At the same level as the workspace are two header files that are used by both projects. Each project is then in its own subdirectory.
SimpleComSvr.dsw
The common header files are:
ISimpleMsgBox.h
SimpleMsgBoxComDef.h
As mentioned earlier, you need a .DEF file to export the four standard exported functions from the server. The sample project's .DEF file looks like this:
EXPORTS
DllRegisterServer PRIVATE
DllUnregisterServer PRIVATE
DllGetClassObject PRIVATE
DllCanUnloadNow PRIVATE
Each line contains the name of the function and the PRIVATE keyword. This keyword means the function is exported, but not included in the import lib. This means that clients can't call the functions directly from code, even if they link with the import lib. This is a required step, and the linker will complain if you leave out the PRIVATE keywords.
PRIVATE
If you want to set breakpoints in the server code, you have two ways of doing it. The first way is to set the server project (MsgBoxSvr) as the active project and then begin debugging. MSVC will ask you for the executable file to run for the debug session. Enter the full path to the test client, which you must already have built.
The other way is to make the client project (TestClient) the active project, and configure the project dependencies so that the server project is a dependency of the client project. That way, if you change code in the server, it will be rebuilt automatically when you build the client project. The last detail is to tell MSVC to load the server's symbols when you begin debugging the client.
The Project Dependencies dialog should look like this:
To load the server's symbols, open the TestClient project settings, go to the Debug tab, and select Additional DLLs in the Category combo box. Click in the list box to add a new entry, and then enter the full path to the server DLL. Here's an example:
The path to the DLL will, naturally, be different depending on where you extract. | https://www.codeproject.com/Articles/901/Introduction-to-COM-Part-II-Behind-the-Scenes-of-a?fid=1828&df=90&mpp=25&sort=Position&spc=Relaxed&tid=2555504 | CC-MAIN-2017-26 | refinedweb | 4,457 | 52.09 |
Tiers are used to organize subnetworks into groups within a domain network. A domain network is composed of one or more tiers forming either a hierarchy of tiers or partitioned groups of tiers. A single tier defines a collection of individual subnetworks that all have the same subnetwork definition.
The Add Tier tool is used to define a tier within a domain network.
Requirements
To define a tier, the following requirements must be met:
- The network topology must be disabled.
- The name of the tier must be unique within the domain network.
- When working with an enterprise geodatabase, ensure the following:
- The Input Utility Network parameter must be from a database connection established as the database utility network owner.
- The connected ArcGIS Enterprise portal account must be the portal utility network owner.
- The network classes must be empty.
Caution:
It is important to perform all of the network configuration before appending data to the network classes. The Add Tier tool creates a subnetwork name field with a nonnullable property to the underlying network feature classes and tables. This add field process can only be completed if the network feature classes and tables are empty.
Define a tier
To define a tier, complete the following steps:
- On the Analysis tab, in the Geoprocessing group, click Tools
to open the Geoprocessing pane.
- In the Geoprocessing pane, search for and select Add Tier.
- For the Input Utility Network parameter, choose a utility network.
- For the Domain Network parameter, choose the domain network.
- For hierarchical domain networks, provide an existing Tier Group Name.
If the domain network does not have a Tier Group, use the Add Tier Group tool as a prerequisite.
- For the Name parameter, specify a tier name.
The name must be a unique tier name within the entire utility network and cannot exceed 64 characters. The following special characters are invalid:
- Grave accent (`)
- Tilde (~)
- At sign (@)
- Dollar sign ($)
- Percent sign (%)
- Caret (^)
- Asterisk (*)
- Plus sign (+)
- Equal sign (=)
- Vertical bar (|)
- Backslash (\)
- Open-angle bracket (<)
- Close-angle bracket (>)
- Question mark (?)
- Open brace ({)
- Close brace (})
- Period (.)
- Exclamation point (!)
- Single quotation mark (')
- Open bracket ([)
- Close bracket (])
- Semicolon (;)
- Carriage return (\r)
- New line (\n)
- Double colon (::)
- Provide a rank for the tier in the Rank parameter.
- Specify a type for the Topology Type parameter.
Choices are determined by the tier definition for the domain network. Hierarchical domain networks are automatically assigned a Mesh topology type, while partitioned networks can be assigned Mesh or Radial.
Learn more about the topology type for a tier
- For hierarchical domain networks, provide a field value for Subnetwork Field Name.
When adding the initial tier group and tiers for the domain network, provide a new subnetwork field name to add for each domain network feature class and table. When the domain network contains multiple tier groups, existing subnetwork name fields can be reused when adding tiers that represent the same logical aggregation of a subsystem of the domain. If using an existing field, the field must be one that was previously added via the Add Tier tool itself. This field exists within all domain network classes with the following specifications:
Type: esriFieldTypeString IsNullable: VARIANT_FALSE DomainFixed: VARIANT_FALSE Length: 2000 IsIndexed: true IsUniqueIndex: false IsEditable: VARIANT_FALSE Default value: "Unknown"
- Click Run.
The specified domain network now has a new tier. To view the new tier definition, open the network properties for the utility network.
Next, set the subnetwork definition for the tier. | https://pro.arcgis.com/en/pro-app/latest/help/data/utility-network/define-a-tier.htm | CC-MAIN-2022-33 | refinedweb | 568 | 54.63 |
Lesson 7 - Birthday reminder in C# .NET WPF - Logic layer
In the previous lesson, Birthday reminder in C# .NET WPF - Designing windows, we designed the forms needed for our application in WPF. In today's tutorial, we're going to talk about logic layer design and create C# classes that will carry the application logic.
Person
Our application is based on people's birthdays, so they will need a class all
to themselves. Make sure you add the
public modifier before the
class name.
Properties
Each person will have four properties:
- name (string Name)
- birthday (DateTime Birthday)
- age (int Age)
- number of days remaining until their next birthday (int RemainingDays)
The first two properties are simple:
public string Name { get; set; } public DateTime Birthday { get; set; }
We'll set these properties using a parametrized constructor. After which, the class will look something like this:
public class Person { public string Name { get; set; } public DateTime Birthday { get; set; } public Person(string name, DateTime birthday) { Name = name; Birthday = birthday; } }
The other two properties will contain additional logic, and will be displayed on the form using bindings.
Age
The Age property calculates and returns a person's current age. You can't just subtract two dates and expect to get the right answer. A TimeSpan cannot determine the number of years, only a number of days, remember? We will perform the age calculation as follows:
- Get the current date (excluding time) using DateTime.Today.
- Calculate the age as by subtracting the years from the current date and the date of birth. Which will not give an accurate result. If you were born on February 1, 1990, and now it's January 1, 2010, it is not 20 years, but only 19. Which is why there are more steps to the calculation.
- For the cases where the current date is lower (earlier) than the date of birth after adding the years up, we will subtract a year from the age.
- Return the final age.
The Age property code will be as follows:
public int Age { get { DateTime today = DateTime.Today; int age = today.Year - Birthday.Year; if (today < Birthday.AddYears(age)) age--; return age; } }
RemainingDays
The RemainingDays property returns how many days are left until the person's birthday. To do so we will have to include the following steps:
- Get the current date (without time).
- Get the date the birthday lands on by adding the age + 1 and the person's date of birth.
- Subtract the dates and return the difference in days. Since the difference returns a double, we will have to convert it to an int.
public int RemainingDays { get { DateTime today = DateTime.Today; DateTime nextBirthday = Birthday.AddYears(Age + 1); TimeSpan difference = nextBirthday - DateTime.Today; return Convert.ToInt32(difference.TotalDays); } }
ToString()
The people will be listed, so overriding the class' ToString() method to make it return the person's name will prove to be very useful:
public override string ToString() { return Name; }
Person manager
Another logical component we will have to add to the application is the "person manager". The class will be able to add, remove and save a list of people into a file and load it afterward. Also, it'll be able to find the person that has the nearest upcoming birthday.
Add a PersonManager class to the project and make it public.
Properties and attributes
The person manager will have three public properties.
The first is a list of people of the ObservableCollection type. An ObservableCollection is a more efficient sort of List that can raise a change event when its contents. Thanks to this mechanism, all of the form controls that have an ObservableCollection set as their data source would then refresh automatically. Which is great because it would be very confusing to refresh dozens of form controls manually when something is altered externally. Once we add a new person to our application, it will immediately be visible in the person list and will refresh automatically. In this case, we will initialize the ObservableCollection() in the constructor.
If we wanted to be able to edit people, the Person class would have to implement the INotifyPropertyChanged interface. Any change, e.g. the person's Name, would then automatically be propagated to all of the form controls where this person is used. However, we're going to keep it simple for now, and not add that sort of feature.
After adding all of the content stated above, the PersonManager class will look something like this:
public class PersonManager { public ObservableCollection<Person> Persons { get; set; } public PersonManager() { Persons = new ObservableCollection<Person>(); } }
The rest of the necessary properties are:
- TodaysDate that returns the current date.
- NearestPerson that returns the person with the upcoming birthday.
Whose code will look like this:
public Person NearestPerson { get; set; } public DateTime TodaysDate { get { return DateTime.Now; } }
Methods
Other than adding and removing people, the class will also be able to find the person with the nearest upcoming birthday. We'll cover loading/saving people into/from a file later on.
FindNearest()
The FindNearest() method finds and stores the person who has the nearest
upcoming birthday. To find that person in the list we'll use the LINQ OrderBy()
method which will sort people based on how many days are left until their
birthday. We'll store the result into a collection and use the
var
keyword instead of specifying the data type of the collection (as is a common
practice in LINQ). Then, we'll return the first person that is found. The method
should only be called when the list is not empty. We will also set the method as
private since we would only call it from within the class.
private void FindNearest() { var sortedPersons = Persons.OrderBy(o => o.RemainingDays); if (sortedPersons.Count() > 0) NearestPerson = sortedPersons.First(); else NearestPerson = null; }
Add()
The Add() method adds a new person to the ObservableCollection. Since the person will be added from the form, we will make the method take person properties as parameters and create a new instance on using the data provided by the user. We will only store the date from the date of birth (exclude time).
Before adding a person to the list, we will have to check whether the name is too short or the date selected has not passed. In any of these cases, we'll throw an exception. Exceptions are the only proper way to handle errors in object-oriented applications. If you haven't met them yet, just know that an exception is done using the throw keyword followed by an exception instance. There are several types of exceptions (you could even make your own). In our case, we'll throw an ArgumentException (attributed to argument errors). We'll enter the error message in the exception constructor. Once an exception is thrown, a method is terminated. We will get to reacting to the exception once we call the method from the form.
A date entered by a DatePicker form control is of the DateTime? type. If you went through the object-oriented course up until the end, you know that a question mark refers to the nullable type. A nullable type is an extension of the value data type makes it so it can contain the null value (which is normally not allowed). If the date is null, a date has not been entered and we will have to throw an exception. The value of a nullable type can be accessed through the Value property.
public void Add(string name, DateTime? dateOfBirth) { if (name.Length < 3) throw new ArgumentException("Name is too short"); if (dateOfBirth == null) throw new ArgumentException("Date of birth wasn't entered"); if (dateOfBirth.Value.Date > DateTime.Today) throw new ArgumentException("Date of birth can't be in the future"); Person person = new Person(name, dateOfBirth.Value.Date); Persons.Add(person); FindNearest(); }
At the end of the method, we run the FindNearest() method since it could be the one that was just added.
Remove()
The Remove() method removes a person from the ObservableCollection. Since all this method will do is remove a person instance, the method will take a Person as a parameter. Once the person has been removed, we will run the FindNearest() method once again.
public void Remove(Person person) { Persons.Remove(person); FindNearest(); }
In the next lesson, Birthday reminder in C# .NET WPF - Wiring layers, we'll continue with our application and make it runnable.
Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.
DownloadBy downloading the following file, you agree to the license terms
Downloaded 45x (449.95 kB)
Application includes source codes in language C#
1 messages from 1 displayed. | https://www.ictdemy.com/csharp/wpf/course-birthday-reminder-in-csharp-net-wpf-logic-layer | CC-MAIN-2021-31 | refinedweb | 1,455 | 64.51 |
Scurses, terminal drawing API for Scala, and Onions, a Scurses framework for easy terminal UI
Scurses and Onions are frameworks for drawing nice things in your terminal using simple, elegant Scala. Scurses provides a low-level drawing and event handling API while Onions provides a high-level UI API with useful widgets.
Contents:
High-level Scurses framework for easy terminal UI
Dependency:
libraryDependencies += "net.team2xh" %% "onions" % ""
To see an example application showcasing all the widgets, run:
$ sbt onions/run
Make sure that your terminal is sized big enough, scrolling is not supported yet.
Goal is to provide an API full of widgets to make it really easy for users to quickly set up a dashboard to monitor their services in the terminal (graphs, histograms, logs, etc.). It works great through SSH as well!
Scurses { implicit screen => val frame = Frame("Example UI") // Three columns val colA = frame.panel val colB = colA.splitRight val colC = colB.splitRight // Split second column in three rows val colB2 = colB.splitDown val colB3 = colB2.splitDown // Split third row of second column into two columns val colB3B = colB3.splitRight val colB3B2 = colB3B.splitDown // Split last column into two rows val colC2 = colC.splitDown
// Add a label in the first column Label(colA, Lorem.Ipsum, TextWrap.JUSTIFY)
val r = Random val points = (1 to 50) map (i => { val x = r.nextInt(40) val y = 50 - x + (r.nextGaussian() * 5).toInt - 2 (x, y max 0) })
// Add a scatter plot in the first row of third column ScatterPlot(colC, points, "Time", "Sales")
// Show a heat map of the same values in the second row HeatMap(colC2, points, "Time", "Sales")
// Display and launch event loop frame.show() }
For examples regarding all widgets, see
ExampleUI.scala
Low-level terminal drawing API for Scala
Dependency:
libraryDependencies += "net.team2xh" %% "scurses" % ""
$ sbt "scurses/runMain net.team2xh.scurses.examples.HelloWorld"
$ sbt scurses/run
$ sbt "scurses/runMain net.team2xh.scurses.examples.StressTest"
import net.team2xh.scurses.Scurses
Scurses { screen => // The screen will only be in Scurses mode inside this block // Scurses will reset the terminal buffer and everything when outside
// Get the current terminal size val (w, h) = screen.size
val greeting = "Hello, world!" val prompt = "Press a key to continue..." // Put some strings in the middle of the screen screen.put(w/2 - greeting.length/2, h/2, greeting) screen.put(w/2 - prompt.length/2, h/2 + 1, prompt, Colors.BRIGHT_BLACK) // Flush the buffer screen.refresh() // Wait for an input without storing it screen.keypress() } | https://xscode.com/Tenchi2xh/Scurses | CC-MAIN-2021-10 | refinedweb | 411 | 59.9 |
Array help807603 Nov 6, 2007 1:35 AM
how would you make a program with two arrays that calculates the values of the two areas. The sum and product.
Here is an example of two arrays that I need to find the sum and product.
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int b[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
Should I use some kind of loop or something?
Here is an example of two arrays that I need to find the sum and product.
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int b[] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
Should I use some kind of loop or something?
This content has been marked as final. Show 8 replies
1. Re: Array help807603 Nov 6, 2007 1:40 AM (in response to 807603)Probably.
It would help to know how you want or have been told to calculate the sum and product using those arrays. For example, you could take the product of values in corresponding positions in the arrays. Or, you could take the product of all the values in a single array. Or, you could take the product of the lengths of the arrays.
What did the assignment say to do, exactly?
2. Re: Array help807603 Nov 6, 2007 1:41 AM (in response to 807603)it seems like you have a vauge understanding of what an array is, but where your knowledge is lacking is how to use them. What you gotta understand is that when the program hears a[0] it finds the first value in the arrray. In this case it is 1. so a[1] =2, a[2] =3...
so if you want to add up the sum of them in this closed situation you should just be able to go
sumA = a[0]+a[1] a[2]a[3]+a[4]+a[5]+a[6]+a[7]+a[8]+a[9]
however thats a terrible solution and a simple loop would work perfectly but i'll leave that part up to you
3. Re: Array help807603 Nov 6, 2007 1:43 AM (in response to 807603)here is what the assignment is:
Write a program that reads data from two arrays a[ ] and b[ ], both of type integer and containing 10 elements, and calculates the values of two arrays, sum[ ] and product[ ], which contain the corresponding sum and product of the a and b arrays.
sum[i] = a[i] + b; product[i] = a[i] * b[i]
4. Re: Array help807603 Nov 6, 2007 1:45 AM (in response to 807603)Use a for loop. Use the index variable of the loop to index both input arrays as well as the sum and product arrays.
5. Re: Array help807603 Nov 6, 2007 1:48 AM (in response to 807603)some like this?:
for(int i= 0 ;i<len1;i++){
a3[i] = a1[i] + a2;
a3[i] = a1[i] * a2[i];
}
6. Re: Array help807603 Nov 6, 2007 2:25 AM (in response to 807603)Yeah, but you probably don't want to assign the results of both calculations to the same array.
Also, when you post code, wrap it in [code][/code] tags so it's more legible.
7. Re: Array help807603 Nov 6, 2007 3:12 AM (in response to 807603)This is not working, can you tell me whats wrong with it?
public class help { public static void main (String args[] ){ int[] a1 = {4,27,7,4,7}; int[] a2 = {1,2,3,4,5}; int len1= a1.length; int len2= a2.length; int sum, product; for(int i= 0 ;i<len1;i++){ sum = a1[i] + a2;
product = a1[i] * a2[i];
}
System.out.println(sum);
}
}
8. Re: Array help807603 Nov 6, 2007 6:18 AM (in response to 807603)It looks like you put a space or something in the code tags, thus preventing it from formatting your code properly, thus making it hard to read.
But it looks like:
1) You never declare sum or product.
2) you assign the sum of each pair of numbers to sum (similarly with product), overwriting any previous value. You probably want to add the sum of each pair, as in:
sum += a1[i] + a2;
which means, add a1 and a2, and add the result to whatever value sum has, and assign the result to sum.
Or maybe you meant to do this?
sum[i] = a1[i] + a2;
in which case, you'd end up with an array of sums.
Note that in this case you'd need to declare sum differently than before. | https://community.oracle.com/message/8875605 | CC-MAIN-2017-13 | refinedweb | 778 | 78.18 |
#include <TImageButton.h>
Inheritance diagram for TImageButton:
This HIView control subclass works like a standard pushbutton, but supports the use of any image or images for its various states. In addition, it supports drawing a text string over the image for a title.
Because the control's actual title is used to configure the image file names, the text to be drawn as the visible title must be set using SetControlData with the data tag kControlEditTextCFStringTag or kControlStaticTextCFStringTag.
The text will be drawn in the small system font by default. You can change the text style by setting the kControlFontStyleTag data, a structure of type ControlFontStyleRec. | http://augui.sourceforge.net/class_t_image_button.html | CC-MAIN-2017-22 | refinedweb | 106 | 50.36 |
Line Collection¶
Plotting lines with Matplotlib.
LineCollection allows one to plot multiple
lines on a figure. Below we show off some of its properties.
import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from matplotlib import colors as mcolors)) segs[:, :, 1] = ys segs[:, :, 0] = x # Mask some values to test masked array support: segs = np.ma.masked_where((segs > 50) & (segs < 60), segs) # We need to set the plot limits. fig, ax = plt.subplots() ax.set_xlim(x.min(), x.max()) ax.set_ylim(ys.min(), ys.max()) # . colors = [mcolors.to_rgba(c) for c in plt.rcParams['axes.prop_cycle'].by_key()['color']] line_segments = LineCollection(segs, linewidths=(0.5, 1, 1.5, 2), colors=colors, linestyle='solid') ax.add_collection(line_segments) ax.set_title('Line collection with masked arrays') plt.show()
In order to efficiently plot many lines in a single set of axes, Matplotlib has the ability to add the lines all at once. Here is a simple example showing how it is done.
N = 50 x = np.arange(N) # Here are many sets of y to plot vs. x ys = [x + i for i in x] # We need to set the plot limits, they will not autoscale fig, ax = plt.subplots() ax.set_xlim(np.min(x), np.max(x)) ax.set_ylim(np.min(ys), np.max # Make a sequence of (x, y) pairs. line_segments = LineCollection([np.column_stack([x, y]) for y in ys], linewidths=(0.5, 1, 1.5, 2), linestyles='solid') line_segments.set_array(x) ax.add_collection(line_segments) axcb = fig.colorbar(line_segments) axcb.set_label('Line Number') ax.set_title('Line Collection with mapped colors') plt.sci(line_segments) # This allows interactive changing of the colormap. plt.show()
References¶
The use of the following functions, methods, classes and modules is shown in this example:
Out:
<function sci at 0x7fcc162f0040>
Keywords: matplotlib code example, codex, python plot, pyplot Gallery generated by Sphinx-Gallery | https://matplotlib.org/3.3.4/gallery/shapes_and_collections/line_collection.html | CC-MAIN-2022-21 | refinedweb | 305 | 53.68 |
/
README.md
Flamenco Manager
This is the Flamenco Manager implementation in Go.
Author: Sybren A. Stüvel <sybren@blender.studio>
Getting started
To run Flamenco Manager, follow these steps:
- Download Flamenco Manager for your platform.
- Extract the downloaded file.
- Edit the configuration file (see "Configuration" below).
- Optional: Install MongoDB 3.2 or newer. This is only required if you want to run using a self-installed MongoDB database. If you skip this step, the MongoDB server that's bundled with Flamenco Manager will be used.
- Optional: To use the "Last Rendered Image" feature, you need to have ImageMagick installed, with support for the type of images you render. The Manager needs to be able to execute the convert command. The exact version doesn't matter, since the command it executes is simple: convert ${rendered_image} -quality 85 latest-image.jpg
- Start the flamenco-manager (Linux, macOS) or flamenco-manager.exe executable.
- Connect a browser, and you should see a (probably empty) status dashboard.
Configuration
This describes the minimal changes you'll have to do to get Flamenco Manager running.
- Copy flamenco-manager-example.yaml to flamenco-manager.yaml if you haven't done that yet.
- Update own_url to point to the IP address or hostname by which your machine can be reached by the workers.
- Set the manager_id and manager_secret to the values obtained from the Blender Cloud configuration panel. manager_id can be obtained by clicking the "ID" button at the top. For manager_secret use the "Authentication token" at the bottom of the page.
- Optionally generate TLS certificates and set the path in the tlskey and tlscert configuration options. Transport Layer Security (TLS) is the we-are-no-longer-living-in-the-90ies name for SSL.
- Update the variables for your render farm. The blender variable should point to the Blender executable where it can be found *on the workers*.
- Update the path_replacement variables for your render farm. This allows you to set different paths for both Clients (like the Blender Cloud Add-on) and Workers, given their respective platforms.
Note that variables and path_replacement share a namespace -- variable names have to be unique, and cannot be used in both variables and path_replacement sections. If this happens, Flamenco Manager will log the offending name, and refuse to start.
Intervals (like download_task_sleep) can be configured in seconds, minutes, or hours, by appending a suffix s, m, or h. Such a suffix must always be used..
- install; this will create an executable flamenco-manager in $FM/bin
- Copy flamenco-manager-example.yaml and name it flamenco-manager.yaml and then update it with the info generated after creating a manager document on the Server
- Run the Manager with $FM/bin/flamenco-manager -verbose. It may be a good idea to add $FM/bin to your PATH environment variable.
Testing
To run all unit tests, run go test ./... . | https://developer.blender.org/source/flamenco-manager/browse/hotfix-v2.3/;e7e0d4cae746e7de00e3263ac63fdda8e54aa42b | CC-MAIN-2020-10 | refinedweb | 473 | 50.73 |
Continuing in our discussion of Silverlight 3 and the update to .NET RIA Services. I have been updating.
I was very surprised recently when someone mentioned that RIA Services only worked with Entity Framework. That is of course not true, but then I realized that we have not been demoing it with LinqToSql nearly enough. So I thought I’d update my demo app to use LinqToSql rather than Entity Framework.
There are lots of reasons you might be using LinqToSql.. Some folks have found it lighterweight and easier to moch making testablity more simple. Others standardized on it for a project and others just prefer it. Either way, RIA Services works great with LinqToSql.
Let’s switch over the example application to use LinqToSql. First let’s add a new edmx..
And drag the SuperEmployee table over..
Save and build!
Now we make some very minor changes to the SuperEmployeeDomainService..
1: [EnableClientAccess()]
2: public class SuperEmployeeDomainService : LinqToSqlDomainService<SuperEmployeeDataContext>
3: {
4:
5: public IQueryable<SuperEmployee> GetSuperEmployees()
6: {
7: return this.Context.SuperEmployees
8: .Where(emp=>emp.Issues>100)
9: .OrderBy(emp=>emp.EmployeeID);
10: }
No changes to the client at all.. Build hit F5 and the app runs
Notice in line 2, we are using the LinqToSqlDomainService as a base class rather than the EntityFrameworkDomainService.
In line 7, notice that nothing changes here.. the power of Linq!
That is really all we had to do… hit F5 and the main Silverlight App we were building keeps working..
And all the other goodness just keeps working as well… let’s revisit them all just to remind ourselves how cool RIA Services is 😉
The ASP.NET page that is our sitemap
The ASP.NET page that renders downlevel\SEO content
The ADO.NET Data Services (Astoria) REST based view
And of course, the WinForms view
Brad,
This has been a great series. By far the most informative about .NET RIA Services and on a level I can still understand ;-). Especially this Linq to SQL, thank you as that’s what I’m using for unit testing purposes.
I have two questions regarding .NET RIA Services that I’ve yet to see answered anywhere. I thought it may be good for this series and wanted to know what you think.
1) How does the .NET RIA Services tools deal with changes to the database? If as I’m going along in my development I decide I need to add a new column to a database table, how can I get my .edmx or .dbml to pick up this change? If I decide to add in a new table, what’s the best way to add this into my DomainService? The heart of this question is getting at .NET RIA Services being great for RAD but I’d like to see how if performs in the application update/maintenance phase.
2) What is the best way to deal with a large number of tables? If I bring them into one .edmx or .dbml it will be huge, is that okay? What about the DomainService? Should it be split out using partial classes? But it’s auto generated code so if I change anything I’ll have lost all that work.
Any guidance would be appreciated.
Bryan G Campbell – Great.. I am glad you are enjoying the series.. I am too! And I am learning a ton along the way..
The evolution question is a good one.. .one that could be another whole post. The short answer is that it is up to the DAL.. If you add a new column then, you need to update your model. In entity framework, there is an “update from Database” context menu that you can do a table at a time.. If you add a while new table, this can easily be added to the model just by using the wizard or dragging it out from server explorer. Once the model is updated the client types will also be updated, so all you should need to do is add some binding code to the UI to start showing the new data… When a new table is added, you will need to add the appropriate methods to the DomainService to query and update those new tables. Once that is done, the new type will be accessible to the client and you can bind away.
I have heard several people ask about the best practice on factoring your DomainService.. The way I think about this is that you want one DomainService per “screen” in your client UI.. for example if you have a screen for dealing with orders and another suppliers, then I’d suggest factoring those into two different DS classes.. The other thing to think about is what is the unit of work in your application? Do you need to update table X and Y in the same batch, if so, maybe those should be in the same DS..
Hope that helps!
Hi,
To continue on question #2, maybe the solution could be to have a domainService per Use Case. This way your UML model could have is counterpart in the code and maintaining both models and code could be easier…
JeanGab
@Brad,
Thanks for the response, very helpful. I’ve been trying to implement Test Driven Development in this .NET RIA Services world. Thanks to your feedback as well as a post on Vijay’s blog called "Unit Testing Business Logic in .NET RIA Services" I believe I have a better handle on how to do this. I’m sure my approach will continue to evolve, but at least I have a starting point.
@JeanGab – Thanks for the input. It’s always great to get additional perspectives on a problem, helps me break out of my tunnel vision.
Bryan
JeanGab – Yup a "use case" seems like a good way to think about this..
Brad,
Thanks for this series — very useful!
I would like to see some additional guidance on how best to use RIA with Prism.
Ozzy
Ozzy – Yup, I have been talking to the Prism folks about a sample and I think that is on the radar.. stay tuned!
Hi Brad!
How can we determine the total of items of DomainDataSource ?
I would like to display in a text box the number of records of the database (next to the pager of the grid), so the user would have an idea of the size of data.
Thanks,
Rachida Dukes
Hi Brad,
I have troubles deleting an item with LinqToSql. In the delete method I have the following code:
this.Context.Questions.Attach( q );
this.Context.Questions.DeleteOnSubmit( q );
where q is a Question object.
The object is deleted from the db, but the DataGrid bound to the DomainDataSource is not updated correctly. I can see that the item disappears from the DataGrid at first, but in the next moment it is shown again. If I reload the page, thus causing the DomainDataSource to load the data again, the item is deleted.
In XAML I have the exact same case as in your demo: DDS set as ItemsSource to both DataGrid and DataForm, DataForm’s CurrentItem is bound to DataGrid’s SelectedItem. I handle the DataView.CollectionChanged event of the DDS and in case the Action is Remove I call SubmitChanges().
Thanks!
Hi Emil,
I stumbled across this page while looking for a fix for the same issue, except in my case, a ListBox is the master view. The deleted record moves to the end of the list, and trying to delete it again gives WSOD.
For me, calling myDomainDataSource.Load(); after the SubmitChanges() call in the CollectionChanged event handler seems to fix it.
I still get artifacts in the listbox sometimes if I cancel an Add operation, however.
Cheers,
Mark
Microsoft MVP – Visual C++ | https://blogs.msdn.microsoft.com/brada/2009/07/23/business-apps-example-for-silverlight-3-rtm-and-net-ria-services-july-update-part-10-linqtosql/ | CC-MAIN-2017-13 | refinedweb | 1,298 | 74.79 |
reboot - reboot or enable/disable Ctrl-Alt-Del
#include <unistd.h> #include <linux/reboot.h>
int reboot (int magic, int magic2, int flag, void *arg);
#include <unistd.h> #include <sys/reboot.h>
int reboot (int flag);) are permitted as value for magic2. (The hexadecimal values of these constants are meaningful.) The flag argument can have the following values:
:LINUX_REBOOT_CMD_CAD_ON: (RB_ENABLE_CAD, 0x89abcdef). CAD is enabled. This means that the CAD keystroke will immediately cause the action associated to LINUX_REBOOT_CMD_RESTART.
Only the super-user.
On success, zero is returned. On error, -1 is returned, and errno is set appropriately.
reboot(2) is Linux specific, and should not be used in programs intended to be portable.
sync(2), bootparam(7), ctrlaltdel(8)?, halt(8), reboot(8)
3 pages link to reboot(2): | http://wiki.wlug.org.nz/reboot(2) | CC-MAIN-2015-14 | refinedweb | 129 | 55.4 |
Some time ago, I investigated the process of creating a mechanism that would allow me to create an effective two-way communication between two separate applications on different machines. There aren't that many articles that describe this process in detail, and the ones I found stopped short at raising an event on a server machine which would pass a signal back to the client.
In this article, I have extended this, and included a way for any number of clients to register their existence at a host machine, that will then allow the host to communicate back via any user defined type. The sample server and client app I made should resemble a MSN chat type of setup, for demonstration purposes.
I have used the principles demonstrated in this article to allow me to automatically register client applications on start up and verify their license and/or login credentials. Since each client deposits a callback to the client app, I can send messages back to the global client base, or a specific user, or ... (much more fun) perform a forced shut-down in case back-end databases need work doing and all users should have logged out.
Start up the server and client apps on different machines (or on the same localhost), and make sure the machine names are correctly set. Then, enter a user ID, and hit Register which will register your existence at the server. The client and server are now able to communicate to one another.
Please note that many excellent articles are already available on Remoting and the various ways of configurations, so I will largely skip over that part in this discussion. Details on how I have configured remoting are described via comment blocks within the code itself. The way I have set up this two-way communication is by having separate client and server executables. Then, there are three additional classes necessary: CommsInfo, ServerTalk, and CallbackSink; see figure below.
CommsInfo
ServerTalk
CallbackSink
Serializable
MarshalByRefObject
This class exposes an event that the client hooks into to listen for messages from the server. The client also registers a callback to the HandleToClient method within this instance of CallbackSink during registration, via the ServerTalk proxy, so the server now has a valid handle to a method of an object that was created and lives at the client. This works since the server already knows about the CallbackSink type, and when being passed a callback to a method on this type, it is actually being given the proxy to this type, which again works since this object is anchored on the client!
HandleToClient
So, we ended up with a server object (ServerTalk) that lives at the server, and a client that has a handle on this via a proxy, and vice versa; the client has created an instance of CallbackSink that the server got a handle on but is anchored at the client. The server listens for events via static members of ServerTalk. The client listens by simply hooking into the event of the CallbackSink instance.
Since both the server and the client need to be aware of the above described three classes, we need to group them into a separate assembly and ensure that both have references to this. So we need to see this assembly in the bin\debug on both the server and the client!!
Now, we have a good understanding of the approach and overall design, let's look at the full code-listings below.
The class below describes the ServerTalk object:
public delegate void delUserInfo(string UserID);
public delegate void delCommsInfo(CommsInfo info);
// This class is created on the server and allows
// for clients to register their existance and
// a call-back that the server uses to communicate back.
public class ServerTalk : MarshalByRefObject
{
private static delUserInfo _NewUser;
private static delCommsInfo _ClientToHost;
private static List<ClientWrap> _list =
new List<ClientWrap>();
public void RegisterHostToClient(string UserID,
delCommsInfo htc)
{
_list.Add(new ClientWrap(UserID, htc));
if (_NewUser != null)
// make sure there is a delegate to call!
_NewUser(UserID);
}
/// <SUMMARY>
/// The host should register a function
/// pointer to which it wants a signal
/// send when a User Registers
/// </SUMMARY>
public static delUserInfo NewUser
{
get { return _NewUser; }
set { _NewUser = value; }
}
/// <SUMMARY>
/// The host should register a function pointer
/// to which it wants the CommsInfo object
/// send when the client wants
/// to communicate to the server
/// </SUMMARY>
public static delCommsInfo ClientToHost
{
get { return _ClientToHost; }
set { _ClientToHost = value; }
}
// The static method that will be invoked
// by the server when it wants to send a message
// to a specific user or all of them.
public static void RaiseHostToClient(string UserID,
string Message)
{
foreach (ClientWrap client in _list)
{
if ((client.UserID == UserID || UserID == "*")
&& client.HostToClient != null)
client.HostToClient(new CommsInfo(Message));
}
}
// This instance method allows a client
// to send a message to the server
public void SendMessageToServer(CommsInfo Message)
{
if (_ClientToHost != null)
// make sure there is a delegate to call!
_ClientToHost(Message);
}
// Small private class to wrap
// the User and the callback together.
private class ClientWrap
{
private string _UserID = "";
private delCommsInfo _HostToClient = null;
public ClientWrap(string UserID,
delCommsInfo HostToClient)
{
_UserID = UserID;
_HostToClient = HostToClient;
}
public string UserID
{
get { return _UserID; }
}
public delCommsInfo HostToClient
{
get { return _HostToClient; }
}
}
}
The CommsInfo class below facilitates the content exchange between the server and the client. It currently contains a single property 'Message' of type string which can easily be extended to carry as much or as little information as is needed. The last class we need is the CallbackSink class enabling the server to callback to the client, which is further explained in The server code section.
string
[Serializable()]
public class CommsInfo
{
private string _Message = "";
public CommsInfo(string Message)
{
_Message = Message;
}
public string Message
{
get { return _Message; }
set { _Message = value; }
}
}
/// <SUMMARY>
/// This CallbackSink object will be 'anchored'
/// on the client and is used as the target for a callback
/// given to the server.
/// </SUMMARY>
public class CallbackSink : MarshalByRefObject
{
public event delCommsInfo OnHostToClient;
public CallbackSink()
{ }
[OneWay]
public void HandleToClient(CommsInfo info)
{
if (OnHostToClient != null)
OnHostToClient(info);
}
}
public fServer()
{
InitializeComponent();
// Register a server channel on the Server where we
// will listen for clients who wish to communicate
RegisterChannel();
// Register callbacks to the static
// properties on the ServerTalk object
ServerTalk.NewUser = new delUserInfo(NewUser);
ServerTalk.ClientToHost = new delCommsInfo(ClientToHost);
}
// The method that will be called when a new User registers.
private void NewUser(string UserID)
{
// since it originated from a different thread
// we need to marshal this back to the current UI thread.
if (this.cboUsers.InvokeRequired)
this.cboUsers.Invoke(new delUserInfo(NewUser),
new object[] { UserID });
else
{
this.cboUsers.Items.Add(UserID);
// select the last added user
this.cboUsers.Text = UserID;
}
}
// A helper method that will marshal a CommsInfo from the client to
// our UI thread.
private void ClientToHost(CommsInfo Info)
{
// since it originated from a different thread
// we need to marshal this back to the current UI thread.
if (this.txtFromClient.InvokeRequired)
this.txtFromClient.Invoke(new
delCommsInfo(ClientToHost),
new object[] { Info });
else
this.txtFromClient.Text = "from client: " +
Info.Message + Environment.NewLine +
this.txtFromClient.Text;
}
private void RegisterChannel()
{
// Set the TypeFilterLevel to Full since
// callbacks require additional security
// requirements
SoapServerFormatterSinkProvider serverFormatter =
new SoapServerFormatterSinkProvider();
serverFormatter.TypeFilterLevel =
System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;
// we have to change the name since we can't
// have two channels with the same name.
Hashtable ht = new Hashtable();
ht["name"] = "ServerChannel";
ht["port"] = 9000;
// now create and register our custom HttpChannel
HttpChannel channel = new HttpChannel(ht, null, serverFormatter);
ChannelServices.RegisterChannel(channel, false);
// register a WKO type in Singleton mode
string identifier = "TalkIsGood";
WellKnownObjectMode mode = WellKnownObjectMode.Singleton;
WellKnownServiceTypeEntry entry =
new WellKnownServiceTypeEntry(typeof(ServerTalk),
identifier, mode);
RemotingConfiguration.RegisterWellKnownServiceType(entry);
}
private void btnSend_Click(object sender, EventArgs e)
{
if (cboUsers.Items.Count == 0)
{
MessageBox.Show("No registered Users!", "No users");
return;
}
string UserID = cboUsers.Text;
if (chkAll.Checked) UserID = "*";
ServerTalk.RaiseHostToClient(UserID, this.txtToClient.Text);
this.txtFromClient.Text = "To client " + UserID + ": " +
this.txtToClient.Text + Environment.NewLine +
this.txtFromClient.Text;
}
The class below describes the client process. When the registration takes place, a callback is given, pointing to a method on the CallbackSink instance which is anchored on the client. We then attach an event handler relaying the CommsInfo to our client executable.
The client should also open a channel in order to allow the server to communicate back. In this case, I am opening port 9001 over an HttpChannel. The actual port number is not important as long as it is over 1024 and the port number is not exposed on the server (i.e., 9000). I use the Activator's GetObject static method to ask the server to supply me with an instance of the ServerTalk object. Since it comes back as type object, I need to cast this back to my known type of ServerTalk. Now that we have the ServerTalk proxy, we can register our existence. The activation URL identifies the channel type of the server and the server machine name called 'marcel'. Clearly replace this with your machine name. TalkIsGood is the Well Known Object (WKO) string the server knows, and will map to the ServerTalk class, allowing it to create the actual instance.
HttpChannel
Activator
GetObject
object
TalkIsGood
// this object lives on the server
private ServerTalk _ServerTalk = null;
// this object lives here on the client
private CallbackSink _CallbackSink = null;
private void btnRegister_Click(object sender, EventArgs e)
{
// creates a client object that 'lives' here on the client.
_CallbackSink = new CallbackSink();
// hook into the event exposed on the Sink
// object so we can transfer a server
// message through to this class.
_CallbackSink.OnHostToClient +=
new delCommsInfo(_EventSink_OnHostToClient);
// Register a client channel so the server
// can communicate back - it needs a channel
// opened for the callback to the CallbackSink
// object that is anchored on the client!
HttpChannel channel = new HttpChannel(9001);
ChannelServices.RegisterChannel(channel, false);
// now create a transparent proxy to the server component
object obj = Activator.GetObject(typeof(ServerTalk),
"");
// cast returned object
_ServerTalk = (ServerTalk)obj;
// Register ourselves to the server
// with a callback to the client sink.
_ServerTalk.RegisterHostToClient(this.txtUserID.Text,
new delCommsInfo(CallbackSink.HandleToClient));
// make sure we can't register again!
btnRegister.Enabled = false;
}
void CallbackSink_OnHostToClient(CommsInfo info)
{
if (this.txtFromServer.InvokeRequired)
this.txtFromServer.Invoke(new delCommsInfo(
CallbackSink_OnHostToClient),
new object[] { info });
else
this.txtFromServer.Text = "From server: " +
info.Message + Environment.NewLine +
this.txtFromServer.Text;
}
private void btnSend_Click(object sender, EventArgs e)
{
_ServerTalk.SendMessageToServer(new
CommsInfo(this.txtToServer.Text));
this.txtFromServer.Text = "To server: " +
this.txtToServer.Text + Environment.NewLine +
this.txtFromServer.Text;
}
The prudent threading expert will undoubtedly have spotted a design flaw that can cause subtle bugs to occur. Since the server hooks into static events exposed by the ServerTalk class that can be invoked by many instances of this class, there is the potential of threading conflicts. I am speaking from experience since when I tried to use this design to log database requests that are taking place on a middle-ware Business Objects server, unexpected threading exceptions were thrown which are difficult to trace since they never occur at set scenarios or intervals!
To address this problem, I introduced a static synchronized Queue within the ServerTalk class where many threads (instances of this class, i.e., clients) can deposit their CommsInfo objects that should be passed on to the server. The ServerTalk class also spins off a worker thread whose single task in life is to monitor for contents within the Queue. If any objects are found on this Queue (of type CommsInfo), it will dequeue these and pass it on to the event (or any other call-back deposited to the server).
Queue
public class ServerTalk : MarshalByRefObject
{
// existing code.....
// Static constructor that ensures
// a workerthread is started to monitor
// the _ClientToServer queue
static ServerTalk()
{
Thread t = new Thread(new ThreadStart(CheckClientToServerQueue));
t.IsBackground = true;
// Thanks to Colin Myles!! If we don't set
// this statement the thread will
// prevent the app from shutting down!
t.Start();
}
// a thread-safe queue that will contain
// any message objects that should
// be send to the server
private static Queue _ClientToServer =
Queue.Synchronized(new Queue());
// this instance method allows
// a client to send a message to the server
public void SendMessageToServer(CommsInfo Message)
{
_ClientToServer.Enqueue(Message);
}
// an endless loop invoked by a worker-thread
// which will monitor the tread-safe ClientToServer queue
// and passes on any CommsInfo objects that are placed here.
private static void CheckClientToServerQueue()
{
while (true)
{
// allow rest of the system
// to continue whilst waiting...
Thread.Sleep(50);
if (_ClientToServer.Count > 0)
{
CommsInfo message =
(CommsInfo)_ClientToServer.Dequeue();
if (_ClientToHost != null)
_ClientToHost(message);
}
}
}
}
A second threading issue that needs to be resolved is the arrival of a CommsInfo object that per definition has been created on a different thread and thus needs to be marshaled in order to process its content. This can easily be done by using the InvokeRequired property of the target control. If this signals it can't deal with the incoming CommsInfo object, then this object should be send again to itself on the Invoke method, which will re-route the request on the thread that actually created the target control, which in most cases will be the main UI thread.
InvokeRequired
Invoke
In response to fred pittroff's valid comment that 'after a certain amount of inactivity, the server can no longer communicate to the client but can still accept messages from the client', I am inserting the response I wrote to him:
The reason for this behaviour is the ServerTalk object lifetime.
It takes five minutes to be precise - that is, when the default Lease expires, and the server offers the actual ServerTalk object to the Garbage Collector. Since I am creating instances of the ServerTalk class on the server as WKO (Well Known Object) singleton objects, they will hold state (same would apply to client activated objects). Single-call objects would be destroyed after each call, which therefore won't work in the above article.
The server initially has no idea of how long the ServerTalk instances should be kept alive, and therefore, will offer them to the Garbage Collector after 5 minutes of inactivity.
The .NET framework creates a Lease for each object that is created outside the boundaries of the application domain. A lease will have a default life-time of 5 minutes, and when its time is up, it will be removed.
There are a number of ways of renewing the Lease of a remote object and thus preventing the server from removing the object:
ILease
ILease lease = (ILease)_ServerTalk.GetLifetimeService();
(ILease lives in the System.Runtime.Remoting.Lifetime namespace) and call its Renew() method which will give us another 5 minutes.
System.Runtime.Remoting.Lifetime
Renew()
InitializeLifetimeService()
public override object InitializeLifetimeService()
{
ILease lease = (ILease) base.InitializeLifetimeService();
lease.InitialLeaseTime = new TimeSpan(8, 0, 0);
return lease;
}
ISponsor
Right then, that's it. Whilst I have enjoyed putting together this article, I realise that this has simply been my approach to address effective communication between a host server and many clients using .NET's powerful remoting. Feel free to chip in with ideas of how things could be improved, and any other feedback. | https://www.codeproject.com/Articles/13847/Two-way-Remoting-with-Callbacks-and-Events-Explain?fid=294625&df=90&mpp=10&sort=Position&spc=None&select=3309491&tid=4171196 | CC-MAIN-2017-30 | refinedweb | 2,496 | 52.09 |
I find a lot of value in having code files organized. This means adhering to a certain order of elements (member variables up top, followed by properties, constructors, etc.), and listing variables/methods alphabetically where appropriate. This helps to quickly browse the file and to see what it contains, especially if it's large or is a file I've never worked with before. As you might imagine, then, I'm a fan of regions. They lend themselves nicely to this organization, and allow for a collapsed, "floorplan"-type view of the file.
However, many developers don't feel the same way. A lot of people greatly dislike regions due to their ability to hide code, or find no value in such organization. While I feel such problems can be mitigated simply by sticking to some best practices (no nesting regions, for example), the fact is, many developers and teams don't want them. Additionally, it can take a lot of effort to maintain regions properly and consistently. Tools like ReSharper can help, but can still be time-consuming with large, multi-thousand-line files.
For these reasons, I started thinking that the IDE should just do this for me. Like the navigation bar, I should be able to see a list of all elements in my file and navigate to them, but organized into logical, collapsible sections. Such a tool would allow me to forgo regions in my code, not force them onto other developers, but still receive their benefits.
This tool explores a number of concepts. First, it involves creating a Visual Studio add-in and tool window hosting a custom control, as well as hosting a WPF control inside a WinForms control. Second, it uses the Visual Studio automation model and code model to explore the code programmatically. Finally, the main control is written in WPF, so we learn some basic things there.
To run this add-in, simply build the project and drop its DLL and add-in file (DocOutlineCSharp.AddIn in the root of the project) into your Visual Studio add-ins directory (%UserProfile%\My Documents\Visual Studio 20xx\AddIns). Just create this folder if it doesn't exist. Then, when you open Visual Studio, go to Tools -> Add-in Manager, check the add-in, enable it on Startup if you wish, and click OK. If the window doesn't automatically pop up, or if you close it and want to pull it back up later, you can find a command for the window under View -> Other Windows -> Document Outline (C#). This is tested as working in VS2010 and 2008. It probably won't work in 2005 due to it using WPF.
If you wish to load the solution and be able to see it in action simply by pressing F5, just modify the add-in file you place in the add-ins directory to point to the DLL in the solution's output folder, as opposed to the local folder as it's set currently.
Okay, now on to the code!
The heart of a Visual Studio add-in is its Connect class. This is created for you when you make a new add-in, but in an effort to better understand it and "make it my own", I went through and reformatted/renamed things to better reflect my own programming style. This may or may not help you understand what the Connect class does if you haven't used it before.
Connect
For our purposes, there are a few points of interest in the standard Connect class. We must hook into the WindowActivated and WindowClosing events of the IDE so we know when to start outlining code. We do this in the OnConnection method, and we'll unhook them in the OnDisconnection method. What these event handlers do will be described later.
WindowActivated
WindowClosing
OnConnection
OnDisconnection
// get environment window events and hook into WindowActivated and WindowClosing
winEvents = (WindowEvents)app.Events.get_WindowEvents(null);
winEvents.WindowActivated += new
_dispWindowEvents_WindowActivatedEventHandler(winEvents_WindowActivated);
winEvents.WindowClosing += new
_dispWindowEvents_WindowClosingEventHandler(winEvents_WindowClosing);
Now we must create the tool window, where we specify the user control the window should host. Originally, this control was written in WPF. This caused two issues. First, because it inherited from WPF's UserControl which is not COM-visible, the normal ref object ControlObject that Windows2.CreateToolWindow2 populates with a reference to an instance of our user control always came back null, which required providing a reference to the instance of our user control from inside the control itself as a workaround. Second, it curiously made the caption text of our tool window disappear when docked with other windows. Making the base user control WinForms and hosting a WPF control inside of that using an ElementHost fixes both problems. Now the caption works correctly, and ref object ControlObject is populated correctly as well.
UserControl
ref object ControlObject
Windows2.CreateToolWindow2
null
ElementHost
Finally, in OnConnection, provide the user control with the reference to the environment app, and perform our first code outline operation (detailed later).
In the WindowActivated event handler we hooked up earlier, we want to re-outline the code since we switched to a new window, but only if:
void winEvents_WindowActivated(Window GotFocus, Window LostFocus)
{
if (OutlineWindow != null && GotFocus.Document != null &&
(OutlineWindow.CurrentDoc == null ||
(OutlineWindow.CurrentDoc != null &&
OutlineWindow.CurrentDoc.Name != GotFocus.Caption)))
OutlineWindow.OutlineCode();
}
The above conditions ensure that we re-outline code when switching documents, and that we don't unnecessarily do it again if we've just switched to a tool window and back to the code file we were already working in.
In the WindowClosing event handler, we simply clear out the outline tree, and let it re-populate from the WindowActivated event handler of the next activated window.
void winEvents_WindowClosing(Window Window)
{
if (OutlineWindow != null)
OutlineWindow.ClearElements();
}
That's it for the Connect class; now on to our custom control that will perform the code outlining.
The control that the Visual Studio tool window will host is a WinForms control called DocOutlineHost. Inside of that, we have an ElementHost hosting the WPF control that will do the work. It's written in WPF to take advantage of some extra UI flexibility, and also because I wanted to get more familiar with it. Let's start with its constructor, which is pretty basic:
DocOutlineHost
public DocOutline()
{
InitializeComponent();
Application.ResourceAssembly = Assembly.GetExecutingAssembly();
refreshButton.Click += new RoutedEventHandler(refreshButton_Click);
expandButton.Click += new RoutedEventHandler(expandButton_Click);
collapseButton.Click += new RoutedEventHandler(collapseButton_Click);
}
This gets called when the hosting WinForms control is referenced in the CreateToolWindow2 method from the Connect class mentioned previously. We set the ResourceAssembly here to allow us to use short, relative resource paths later. It seems it won't default to its own assembly, possibly because we're inside a Visual Studio add-in. We also hook up the Refresh, Expand, and Collapse buttons that we have.
CreateToolWindow2
ResourceAssembly
Our main entrance into this control after its creation is via the OutlineCode method, which gets called initially from the OnConnection method as well as every time we activate a new document window. This is the meat of the logic of the tool.
OutlineCode
First, we get all code elements in the file provided to us through the Visual Studio code model.
elements = DTE.ActiveDocument.ProjectItem.FileCodeModel.CodeElements;
For each element, we "expand" it, seeing what it has, adding items to our outline tree if necessary, and expanding further child items within it (details later).
for (int i = 1; i <= elements.Count; i++)
ExpandElement(elements.Item(i), null);
Once all the nodes have been added to the tree, we want to sort them. The "kind" nodes (our groups, such as Fields, Properties, Public Methods, etc.) we want to sort according to a prescribed order that we define. We do this using a custom comparer, which I won't get into the details of here. The element nodes inside of each group node, we want to just sort alphabetically. Because a node can be either a grouping (containing code elements), or a class (containing grouping elements), and classes can be nested infinitely, we must perform the sort recursively, doing it alphabetically or using our custom comparer depending on the parent node type.
private void SortNodes(ItemCollection items, IComparer<TreeViewItem> comparer = null)
{
List<TreeViewItem> itemList = new List<TreeViewItem>();
foreach (TreeViewItem item in items)
itemList.Add(item);
items.Clear();
if (comparer != null)
{
itemList.Sort(comparer);
}
else
{
try
{
itemList = itemList.OrderBy(i =>
GetTreeViewItemNameBlock(i).Text.ToString()).ToList();
}
catch { }
}
foreach (TreeViewItem item in itemList)
items.Add(item);
foreach (TreeViewItem item in items)
{
if (item.Items != null && item.Items.Count > 0)
{
SortNodes(item.Items, item.Name == "GroupNode" ? null : new KindComparer());
}
}
}
Finally, we expand all nodes so the user can see the full outline, and set this document as our "current document" for tracking purposes.
ExpandCollapseChildren(elementTree.Items, true);
CurrentDoc = DTE.ActiveDocument;
Now we will see how we examine each code element and decide what to do with it.
For each code element we encounter, we may or may not want to add it to our outline tree, and we definitely want to expand it further to see what else is below it. The latter part is pretty easy, and just requires a recursive call. CodeElement.Kind will tell us what kind of code element we're dealing with. If the code element is a namespace, we don't want to add it to our tree, so it's as simple as grabbing its members (classes, enums, etc.) and expanding each of them.
CodeElement.Kind
if (element.Kind == vsCMElement.vsCMElementNamespace)
{
CodeElements members = ((CodeNamespace)element).Members;
for (int i = 1; i <= members.Count; i++)
ExpandElement(members.Item(i), parent);
}
If it's a class, we do want to add it to our tree, and we also want to expand each of its members. We grab the class' name, add a TreeViewItem for it, and also add it to our list of encountered elements along with its position in the file for navigating later.
TreeViewItem
CodeClass cls = (CodeClass)element;
string fullName = cls.FullName;
string name = cls.FullName.Split('.').Last();
TreeViewItem classItem = CreateTreeViewItem(fullName, name, string.Empty,
string.Empty, false, "Classes", new vsCMAccess());
items.Add(classItem);
treeElements.Add(new EncounteredCodeElement() {
FullName = fullName, Name = name, Location = element.StartPoint });
Details of the CreateTreeViewItem method and how we will navigate to these items later is coming up. We then expand each child element with similar code as before.
CreateTreeViewItem
The other element types are "everything else": fields, properties, methods, and so on. We have a giant switch statement for the purpose of casting the element based on its kind, and then we do a number of things. We want to grab its name, its type, whether or not its static (IsShared == true), whether or not it's constant (in the case of fields), and any access modifiers it may have. Based on this, we create a "kind" string, which is the "kind" (group) we are going to put this element into. The code for the "variable" type is below (kind is a string representing the name of the group we want this in).
switch
IsShared == true
kind
string
CodeVariable var = (CodeVariable)element;
name = var.Name;
fullName = var.FullName;
fullType = var.Type.AsString;
if (var.IsShared)
kind += "Static ";
if (var.IsConstant)
kind += "Constants";
else
kind += "Fields";
access = var.Access;
There is some extra logic to do for function elements. We'd like the text on the TreeViewItem to display the entire method signature, instead of just the name of the method, so we must build this string ourselves by iterating CodeFunction.Parameters and adding parentheses and commas as necessary. We also add the access modifier to the "kind" string via a Dictionary mapping. If the name of the method is the same as the class we're within, we set the kind to "Constructors". We set the kind to "Event Handlers" if the following is true: the method has a return type of void and has two parameters, the first of which is of type System.Object and the second of which is derived from System.EventArgs. The code for all this is pretty straightforward, and can be seen in the attached source.
CodeFunction.Parameters
Dictionary
void
System.Object
System.EventArgs
At this point, after gathering all relevant information from our code element and building our "kind"/group string, if we have a regular code item (not a class or namespace, we can tell this by checking if the "kind" string is not empty), we want to add it to our TreeView. First, we must decide which set of nodes to add the new node to. If we provided a parent element to the ExpandElement method, we use that parents' children. Otherwise, we use the root of the tree.
TreeView
ExpandElement
ItemCollection items = parent != null ? parent.Items : elementTree.Items;
Now we find the "kind" item to add our element to, and if we can't find it, we create it. In this process, we use a method, GetTreeViewItemNameBlock, to grab the TextBlock element containing the user-visible name of each node we pass. You might think using the Name property of the TreeViewItem itself would be an easier solution for this, but that property would not allow for things like . and <> in the name, which we need to uniquely identify a method signature, etc. Also, sometimes we need both the user-visible name and the fully qualified name (stored in the TextBlock ToolTip, shown in the CreateTreeViewItem method), for example to find the element when clicked on later, so this method would be useful regardless.
GetTreeViewItemNameBlock
TextBlock
Name
ToolTip
We want to add the element's type to our TreeViewItem in bold. If it's a simple type, we just un-qualify it for readability and we're done. If it's a "typed" type (with <>), we want to un-qualify each type within the angle brackets, which takes a little logic which you can find in the source.
<>
Finally, we can create our TreeViewItem and add it to our group's children, and add the element to our list of encountered elements and positions.
The final things to cover are our method for creating TreeViewItems, as well as the code to navigate to items from the tree.
In this method, we provide a list of things such as qualified and unqualified name and type, the kind/group, and any access modifiers, and create a TreeViewItem. This is essentially simple WPF UI manipulation in code. First, we create a new TreeViewItem, and a StackPanel, setting its Orientation to Horizontal.
StackPanel
Orientation
Horizontal
TreeViewItem item = new TreeViewItem();
StackPanel stack = new StackPanel();
stack.Orientation = Orientation.Horizontal;
stack.Height = 16;
Next we create a grid for icons. We grab icon resources from our assembly based on the "kind"/group and any access modifiers using a simple Dictionary mapping for each, and use a BitmapImage with a Uri to set this as the as the Source of an Image. The nice thing is we can grab multiple images, for example, the blue cube for fields and the padlock for private, and add them both to the grid and they will properly overlay each other.
BitmapImage
Uri
Source
Image
private
Image kindImage = new Image();
kindImage.Name = "kindImage";
kindImage.Source = new BitmapImage(new Uri(@"/Resources/" +
kindImageMapping[kind] + ".png", UriKind.Relative));
grid.Children.Add(kindImage);
Next we create TextBlocks for the name and type, italicizing the name if it's a class and bolding it if it's a group, and bolding the type. We also set the ToolTip of each to be the fully qualified name for reference for the user. Finally, we add the image grid and both TextBlocks to the StackPanel, and set the StackPanel to the TreeViewItem's Header. We hook up events for MouseDoubleClick and Selected, and return the TreeViewItem.
Header
MouseDoubleClick
Selected
The final step is navigation from the outline window. As with the normal Visual Studio navigation bar, we want the user to be able to double click an item and be taken to it in the source. Unfortunately, it seems that the MouseDoubleClick event behaves unusually in that it fires separately on every element from the origin up the visual tree to the highest parent, and thus cannot be stopped by handling the event. So, no matter what item we double click, we always get navigated to the highest parent instead. This can be stopped by caching the selected TreeViewItem when it's chosen, and only performing the navigation if the selected item matches the source of the double click event. In the Selected event handler:
void item_Selected(object sender, RoutedEventArgs e)
{
selected = sender as TreeViewItem;
e.Handled = true;
}
And in our MouseDoubleClick event handler:
if (selected != e.Source)
return;
Next, we get the TextBlock containing the name in the selected TreeViewItem. We use this to find the element in our list of encountered elements and positions.
TextBlock nameBlock = GetTreeViewItemNameBlock((TreeViewItem)sender);
EncounteredCodeElement foundElement = treeElements.Find(el =>
el.Name == nameBlock.Text && el.FullName == nameBlock.ToolTip.ToString());
Then it's as simple as moving the DTE.ActiveDocument.Selection to the specified point.
DTE.ActiveDocument.Selection
EnvDTE.TextSelection selection = (EnvDTE.TextSelection)DTE.ActiveDocument.Selection;
selection.MoveToPoint(foundElement.Location);
There is one other small piece of logic. By default, the above code moves the cursor to the beginning of the line of the code element. To get it to the beginning of the name of the element, as with the built-in navigation bar and to trigger VS 2010's highlighting feature, we must move the cursor to the first found parenthesis or the end of the line, and then find the first instance of the unqualified name, without any parentheses, moving backwards from that point. It must be done in this way to ensure we don't put the cursor on a type of the same name or on a parameter by mistake.
if (!selection.FindPattern("("))
selection.EndOfLine();
string name = foundElement.FullName.Split('.').Last();
selection.FindPattern(name, (int)vsFindOptions.vsFindOptionsMatchCase |
(int)vsFindOptions.vsFindOptionsBackwards);
selection.CharLeft();
And we're done!
All in all, it's a relatively straightforward tool, but it does contain a few quirks and a good bit of logic. Notable oddities are needing the WinForms host to avoid the null ControlObject when creating the tool window and the missing caption, and the unique behavior of MouseDoubleClick as compared to other regular bubble-type WPF events. Also, getting the Aero look and feel on XP required explicitly including the Presentation.Aero DLL as a merged resource dictionary. There was definitely a good bit of learning to do, but most of this was related to Visual Studio add-in quirks and WPF itself (resource Uris, TreeView, events, etc.). The Visual Studio code model itself is pretty simple.
null ControlObject
I find this tool very useful for navigating and browsing code files, and hopefully you will too! This is my first submission to The Code Project, so I would appreciate any feedback. Thanks!
<T>
struct
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
public class AdHocSearchViewModel : ViewModelBase
{
private readonly INavigationService navigationService;
private Job job = null;
private bool isExistingJob = false;
+ Constants
- navigationService INavigationService
+ Fields
- isExistingJob bool
- job Job
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/96311/A-Document-Outline-Window-for-C-Files-in-WPF?fid=1580517&df=90&mpp=10&sort=Position&spc=None&tid=3626858 | CC-MAIN-2015-22 | refinedweb | 3,222 | 54.42 |
In my Next.js based website had the need to fetch data from an API at build time.
I tried various solutions, nothing worked. Then after lots of research and trial and error, here’s what worked.
The solution works both on localhost (development) and on Vercel (production).
This is the scenario: I have the emails of the “members” stored somewhere. It can be a remote database, Airtable, anything.
I only want to download this data once, and then have it available on the website, until I trigger the next build.
This members list is very static. It might change once a day max. If this list changes, I will just programmatically trigger a redeploy on Vercel using their Deploy Hooks.
Here’s the plan. We’ll create a local cache of the data, in a
.members file.
A function in the
lib/members.js file will take care of fetching the data and storing it in the cache as JSON when it’s first called, and subsequently it will read the data from the cache:
import fs from 'fs' import path from 'path' function fetchMembersData() { console.log('Fetching members data...') return [{ email: 'test1@email.com' }, { email: 'test12@email.com' }] } const MEMBERS_CACHE_PATH = path.resolve('.members') export default async function getMembers() { let cachedData try { cachedData = JSON.parse( fs.readFileSync(path.join(__dirname, MEMBERS_CACHE_PATH), 'utf8') ) } catch (error) { console.log('Member cache not initialized') } if (!cachedData) { const data = fetchMembersData() try { fs.writeFileSync( path.join(__dirname, MEMBERS_CACHE_PATH), JSON.stringify(data), 'utf8' ) console.log('Wrote to members cache') } catch (error) { console.log('ERROR WRITING MEMBERS CACHE TO FILE') console.log(error) } cachedData = data } return cachedData }
Now inside any page we can add
import getMembers from 'lib/members'
and inside
getStaticProps():
const members = await getMembers()
Now with this data we can do what we want.
A quick example is to add
members to the
props object returned by
getStaticProps, adding it to the props received by the page component, and we can iterate over it in the page:
{members?.map((member) => { return ( <p key={member.email} {member.email} </p> ) })}
Download my free Next.js Handbook!
Check out my Web Development Bootcamp. Next cohort is in April 2022, join the waiting list! | https://flaviocopes.com/nextjs-cache-data-globally/ | CC-MAIN-2021-49 | refinedweb | 365 | 61.53 |
import java.util.ArrayList; public class PrimeDirective{ public ArrayList<Integer> fib(int x){ ArrayList<Integer> fibonacci = new ArrayList<Integer>(); fibonacci.add(0); fibonacci.add(0); if(x < 2) return fibonacci; for(int i = 2;i<=x;i++){ int sum = (i - 1) + (i - 2); fibonacci.add(sum); } return fibonacci; } public static void main(String[] args){ PrimeDirective pd = new PrimeDirective(); System.out.println(pd.fib(3)); } }
Very nice
How does it handle negative input though?
One question, how could both first and second term be zero? They will always add up to zero.
because in fibonacci series first 2 term are 0. So I have added these to elements manually and I have started my loop from 2. If I start my loop from 0 then first 2 elements will be negative.
but i guess fibonacci series only takes positive input.
but in my code if user inputs negative no then it will return [0,0].(I have not done anything for negative input. lol).
Haha, I was not too serious, getting fibonacci to work is great! But usually in code challenges you have to lay out handling of cases that break the code like this. It’s a useful thing to think about in your own programs and it’s a good issue to openly process if you’re coding in an interview.
If you have a base case that immediately identifies it’s an invalid input, then you don’t have to waste the time of your code processing dud input. If the code were a lot larger it could become a pain…
import java.util.ArrayList; public class PrimeDirective{ public ArrayList<Integer> fib(int x){ ArrayList<Integer> fibonacci = new ArrayList<Integer>(); if(x<0) System.out.print("invalid input"); if(x < 2 && x > -1) { fibonacci.add(0); fibonacci.add(0); return fibonacci; } if(x < 2 && x > -1) return fibonacci; for(int i = 2;i<=x;i++){ int sum = (i - 1) + (i - 2); fibonacci.add(sum); } return fibonacci; } public static void main(String[] args){ PrimeDirective pd = new PrimeDirective(); System.out.println(pd.fib(-1)); } }
what about this?
Yea that does the trick, it’s a simple but crucial step (and in other scenarios it won’t be as simple as catching the negative
I speak from a place of suffering…)
The first two terms should be either
0 and
1, or
1 and
1. Both will yield the same terms but one will be shifted by one from the other.
0 1 1 2 3 5 8 13 1 1 2 3 5 8 13 21
I don’t know what you are saying but let me explain what my program does.
firstly lets understand what a fibonacci series is: it is a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers.
for ex f2= 1 + 0. f3 = 2+1
now what my program does: I have created a method that returns an Arraylist and has a single parameter(int x). Now I have added the first two term of fibonacci series manually which are [0,0]. after that I have created a loop for fibonacci series which you can see.
Now still if you have a doubt please reply.
How do we get
1 from adding
0 and
0?
you dont get 1 by 0 and 0 see
f0 = 0
f1 = 0+0
f2 = 0+1=1
got it?
if not then read about fibonacci series on wifipedia
Whoa there. He’s just trying to help out.
My understanding is that the first two terms are 0, 1 (or in some old books, 1 and 1, which is corroborated by wikipedia).
my bad I thought the first two terms are 0,0. yes @mtf you are right fir two terms are 0,1 my bad. Sorry for the inconvenience.
No problem. Made you look… | https://discuss.codecademy.com/t/solution-for-fibonacci-series/512027 | CC-MAIN-2020-45 | refinedweb | 643 | 73.88 |
How to Patrol Recent Changes on wikiHowmission.
Steps
- Read the Writer's Guide. Familiarize yourself with the standards to which wikiHow articles are held. The Writer's Guide outlines what each section is for, what kinds of articles are not welcomed, how to begin each step, what kinds of verbiage are to be avoided, etc. You will need to have a good grasp of the Guide in order to be sure that all articles are in compliance.
- Log into wikiHow and find Recent Changes in one of two ways:
- Click the link to Recent Changes at the top of the Navigation menu in the left of each wikiHow page.
- Power patrollers who use the Mozilla Firefox browser may prefer to download and use the wikiHow Editor's Toolbar to make the process easier. Once installed it appears at the top of your browser window. If you are using the toolbar, all you need to do is click on the sun or clouds or the number immediately to the right of it (0 in the example below!) to be brought to the page showing recent unpatrolled edits.
- Look for changes showing a red exclamation point. This symbol indicates that the contribution hasn't been patrolled yet. You will be the first one to see it. Clicking on the "diff" link will show you what changes have been made. Exception: If you are looking at a new article, there will be a capital "N" in front of the title, and the "diff" link won't work; in this case, clicking on the title of the article will permit you to patrol the new article).
- Click on the "diff" link. You will be brought to a screen which will show the old version of the page on the left and the current version on the right. Specific changes will be highlighted in red. Entirely new paragraphs will show in a new green box and will not be highlighted in red. Entirely deleted paragraphs will be shown in yellow. Pay careful attention to each of these elements.
- Keep this in mind as you read each new edit: the goal of patrolling recent changes is to ascertain that every edit improves the quality of wikiHow.
- Ask yourself whether the edit improved the quality of the page. If so, nothing else is needed. Simply choose "mark as patrolled" by clicking the text under the Current Revision of saying [Mark as patrolled]
At this point, you will automatically be taken to the next unpatrolled edit.
- Decide what action to take if you are unsatisfied with the current edit. At this point, you have four options:
- Fix the problem by pressing edit and making the needed changes (see step 8 for additional guidance on this). Fixing problems is the preferred option.
- Skip this edit if you are uncertain how to fix it. Simply click the "Skip" button to move on to the next unpatrolled edit. If in doubt at all, press skip to leave it to next person.
- Use Page History to edit a previous version of the page. Using this page history revert technique can allow you to mix the good and bad elements of a series of edits.
- Rollback this edit to the previous edit. Do this with reservations and reluctance. Only if: 1) The current version has zero redeeming value and 2) The old version is good. Do not roll the edit back if both edits are bad; this can lead to problems later on.
- Follow these steps when patrolling all articles:
- Do the easy fixes. Many edits can be quickly improved by correcting any number of common mistakes. For example, you can quickly fix a spelling error, move language that should be in tips out of the steps section, remove personal references, delete extra wording to make the page more concise or delete low quality external links.
- Scan for vandalism and spam. Revert any vandalism you find. Vandalism comes in many forms, such as profanity, obscene comments, random characters, nonsense and even the deletion of entire pages or sections. You can also warn the vandal on their talk page by writing {{warning}} on their talk page. Admins can block disruptive users for any period up to 1 month without previous incident or longer in special cases. To report something that needs immediate administrator attention, please post it on our Administrator Notice Board.
- Remove subtle external links added by people who did not also edit the article as per our external link guidelines. Remember that external links are to be used primarily to reference source material for the article.
- Decide if an article needs special attention because it violates wikiHow's deletion policy, is seriously incomplete, very poorly written or inaccurate. If so, you can either take the time to improve the article or apply the appropriate template to bring the article to the attention of admins and other editors. There are many templates used on wikiHow to help ensure prompt attention to problem articles, e.g., {{copyedit}}, {{format}}, {{accuracy}}, {{nfd}} and many others. You can find a list of templates and information on how they should be used on WikiHow:Drawing-Attention.
- Pay attention to these points for all articles, but especially when patrolling new articles. The first check of a new article is especially critical to quality control, preventing vandalism and to ensuring that the article gets the attention it needs from admins or other editors.
- Check to see if we already have an article on that topic. Search wikiHow and check frequently duplicated articles for keywords and phrases related to the article and determine if, according to the merge policy, the new article should be merged. If so, write {{merge|title of existing article}} at the very beginning of the article.
- Determine if the article needs to be tagged with one of our templates for drawing special attention to it. Many new articles are incomplete, poorly worded or inaccurate and need additional work before they can become useful wikiHows. Some new articles are inappropriate for wikiHow or are jokes. Tag the article with the appropriate template when you don't have the time, desire, or ability to improve the page.
- Check the title. The title should be clear, specific, concise, grammatically correct, and properly capitalized. Generally, every word in the title should be capitalized except articles such as "and," "the," and "a." It's also a good idea to avoid symbols like "&" as well as any other kind of punctuation (no periods, exclamation points, etc.). If you think the title should be changed and you're not an admin, place the new title template to suggest the change.
- Remember: If you don't feel comfortable addressing any particular edit, feel free to click on "Skip" and return to recent changes. This will leave the page as unpatrolled to be caught by a future editor.
Tips
- If an editor is adding strange looking links to the bottom of articles, like "[[nl:Een vis noemen]] to a translated version of the article.
- These links will begin with a two letter language code (e.g., es, de, ar, nl, fr, pt) followed by a colon and title words in a language other than English.
- When these links are added, you should see the new language being listed in the "In other languages" section on the left hand side of the page.
- If you prefer to dip your toes in, as opposed to jumping all the way into the patrolling waters, you might like to try to Patrol Discussion Pages on wikiHow for a while first.
- Note that clicking "rollback" will revert all consecutive edits made by one particular user. This makes it easier to revert one user's multiple acts of vandalism targeted toward an individual article. If you want to revert one edit made in a series of multiple edits, use the "undo" feature so that you preserve the other edits.
- The "undo" feature will not work if there are conflicting intermediary edits (e.g. attempting to undo a misspelling in an early edit when the word was deleted in the most recent edit).
- Every wikiHow contributor has his or her own method of patrolling. Some patrollers prefer to work quickly by simply making easy fixes and tagging articles with more serious problems with templates. Others may choose to spend more time on each article. Please do not hesitate to find your own method of patrolling. Every positive contribution helps polish wikiHow into a more productive, informative site.
- After patrolling on a regular basis, you'll start to notice when new contributors show up. Take the time to visit their user pages and leave a welcome on their talk pages. Leave a personal note expressing your appreciation for their contributions followed by the {{welcome}} template. More information on welcoming new contributors can be found here.
- Bookmark recent changes so that you can quickly come back to the page during the day. Even a few minutes of patrolling can make a real difference.
- You can customize many of the patrolling settings to allow you to be a more effective patroller.
- One of the most helpful things you can do is patrol the oldest changes first; this helps to minimize the length of time that vandalism or other problems remain on wikiHow. To do this, just click to check the "Reverse Order" box and then click "Go." The oldest unpatrolled edits will now show up on the top of the page.
- If you have a fast internet connection, you may want to set the default number of changes displayed to 250 or 500 from the default 50. These settings can be changed in My Preferences.
- Bookmarking Featured Article Patrol and checking it occasionally throughout the day is one of the best ways to keep low quality edits off the most popular and most vandalized pages.
- You can also choose to patrol wikiHows from the Main namespace, which are the pages most likely to be vandalized by selecting "(Main)" under the "Namespace pop-down menu and clicking "Go."
- Keep in mind that nobody has singular control of a wikiHow page. While one author may have started it, we can all contribute, change, and delete in the spirit of improvement. Often the best wikiHow pages end up being totally different from the page written by the initial author.
- There is also a Recent Changes Patrollers Team, so feel free to join it and help. Just add yourself to the page.
- To report something that needs immediate administrator attention, please post it on our Administrator Notice Board.
- As with other things on wikiHow, feel free to ask any experienced editor, admin or member of the help team for assistance, or post in the help forum if you have a question.
- For faster patrolling, you can use these keyboard shortcuts to mark articles as patrolled:
- Windows IE 7 - ALT+P+ENTER
- Windows IE 6 - ALT+P+ENTER
- Windows Firefox 2.0 - SHIFT+ALT+P
- Windows Firefox 1.x - ALT+P
- Mac OS X Firefox 2.0 - CTRL + P
Warnings
- Try not to mark pages as patrolled unless you have gone over them with a fine toothed comb. Patrolling too hastily will allow low-quality articles to slip through the cracks and lower the quality of wikiHow content. When in doubt, use the SKIP button and don't mark the edit as patrolled.
- Be sure to check that articles that you revert/edit are NOT in use. | http://www.wikihow.com/Patrol-Recent-Changes-on-wikiHow | crawl-001 | refinedweb | 1,906 | 62.98 |
This week we’re addressing a bunch of customer requests. If you’re lucky, maybe you’ll see your favorite new feature in here! Remember, keep the feedback coming – with your help we plan to make brainCloud the most flexible and friendly BaaS on the planet!
Release Highlights
Highlights of this week’s release include:
- Leaderboard Monitoring – you can now view your game’s leaderboards in the Global Monitoring section of the portal. Super useful during development, support/operations (catching cheaters!) and even for manually administering tournaments. Features include:
- Paging through the leaderboards
- View previous leaderboard versions
- Reset leaderboard – deletes all entries (only works for the active leaderboard, not for previous versions)
- Delete leaderboard entry
- View user – jumps to a view of the user associated with the score
- Updated Javascript Client – we’ve revamped the Javascript Client to use native HTTP calls (instead of JQuery). Useful for embedded client environments where JQuery is not a viable option.
- Cloud Code Enhancements – we’ve enhanced and improved the ability to call cloud code scripts from other scripts. (Yay!). We’ve also normalized the returns from the cloud code API methods vs. the native client API methods. Basically, both now have separate <result> and <data> sections. Because this will break existing scripts, we’ve implemented a settings in Advanced Settings called [x] Use Legacy Script Result Format. This setting defaults to [x] True for all existing apps with cloud code, but [ ] False for everyone else. We recommend migrating your scripts to work with the [ ] False setting when you have a chance.
Portal Changes
- Global Property Categories – You probably already know that Global Properties are super useful. They allow you to define all sorts of configuration and tuning parameters for your app, that can be adjusted and tweaked to adjust how the app behaves, without requiring new builds and client installs. Now – because some folks were building up large-ish libraries of these properties, we thought we’d give you a way to better organize them. Voila: Categories! Note – categories do not affect the namespace of properties – all property names are global to your app.
- New Leaderboard Monitoring – go to Monitoring | Global Monitoring | Leaderboards to view your players’ accomplishments in all their glory! (see highlights section for details!)
- New Compatibility section in the Design | Advanced Settings page
API Changes / Additions
- Leaderboard API optimization – the json data returned by GetGlobalLeaderboardPage() and GetGlobalLeaderboardView() now includes the current Friend Summary Data for the players referenced by the leaderboard entries. Useful for when you want to display additional information about the ranked player in the leaderboard (i.e. xp level, faction, etc.) without requiring an additional brainCloud call for each entry.
- Matchmaking optimization – Friend Summary Data has also been added to matchmaking results (for the same reason we did it for leaderboards!)
- HTTP Client Service improvement – we’ve enhanced the HTTP client Service accessible from Cloud Code to allow passage of query parameters as a map
- GetGlobalProperties() return data fixed – it no longer returns description data. It was a defect (and a bandwidth hog) – so we’ve fixed it.
Misc. Changes / Fixes
- Server optimizations – we’ve fixed our cloud code hook caching, so that it well, actually caches stuff now (whoopsie!). The unsurprising result is even faster processing of all API calls
- Client packet retry improved – our clients now point to a new server end-point which better supports packet retries.
- The API Explorer’s GetShieldExpiry() method has been fixed
- Misc fixes and optimizations | https://getbraincloud.com/apidocs/release-2-10-0/ | CC-MAIN-2019-47 | refinedweb | 576 | 53.21 |
Introduction
In this article we will show you how to utilize Code Contracts in the .NET framework 4.0 using the Design By Contract principle. Code Contracts are included in the .NET framework 4.0 base class libraries by default. If you are using the .NET 3.5 framework then you may have to download it separately.
For our discussion, we are going to use the code contracts with .NET framework 4.0--we won't be focusing on previous versions.
Code Contracts in .NET Framework 4.0
Design by Contract (DbC) or Programming by Contract is an approach to designing computer software. It presc.
Code Contract classes exist in the .NET framework under the namespace System.Diagnostics.Contracts. In code contracts there are three ways of defining contracts. They are listed below:
- Pre-Condition - The contract condition is validated prior to the execution of the method. The Contract.Requires method helps in creating a pre-condition.
- Post-Condition - Ensures the validity after the execution of the method code. Contract.Ensures helps in creating a post-condition. Even if the ensures statement is placed at the beginning of a method for the post-condition to modify the IL to perform the contract validation, after all is said and done, the method code gets executed.
- Invariants - Invariants are the contract which should always evaluate to true before and after the execution of the code.
The information above will be much easier to understand when you take a look at the sample code provided below.
Having mentioned the types of contracts, now comes the question of when these contracts would be invoked.
- Static Checking - The check is made during the compile time and the messages are displayed as warnings.
- Runtime Checking - The check is made during the runtime and the messages are thrown as exceptions.
Go to properties of the project and select Code Contracts tab. Select the options based on the needs as shown in Fig 1.0 below:
Fig 1.0
An Explanation Using Code Samples
In this section I will provide the sample code. Create a Console application using Visual Studio 2010 and .NET framework 4.0. Name it CodeContractsSample. In the Program.cs file, place the code shown below:
namespace CodeContractsSample { class Program { static void Main(string[] args) { CalculatorPreCondition preCondition = new CalculatorPreCondition(); preCondition.Add(7, 101); CalculatorPostCondition postCondition = new CalculatorPostCondition(); postCondition.Add(20, 120); CalculatorInvariant invariant = new CalculatorInvariant(); invariant.Value1 = 100; invariant.Value2 = 20; invariant.Sub(); } } public class CalculatorPreCondition { public int Add(int value1, int value2) { //Check for the parameter validation using precondition Contract.Requires(value1 > 10, "Value 1 should be greater than 10"); Contract.Requires(value2 > 100, "Value 2 should be less than 100"); return value1 + value2; } } public class CalculatorPostCondition { int value3 = 0; public int Add(int value1, int value2) { //Check for the return value using post condition //Post-condition would work even though the ensures statement is //placed above the line where the actual value for Value3 is set. Contract.Ensures(value3 < 110, "Value 3 should be less than 110"); return value3 = value1 + value2; } } public class CalculatorInvariant { public int Value1 { get; set; } public int Value2 { get; set; } public int Sub() { return Value1 - Value2; } [ContractInvariantMethod] private void ContractInvariant() { Contract.Invariant(this.Value1 > this.Value2, "Value 1 should always be greater than Value 2"); } } }
Now enable both static and runtime checking. Fig 2.0 below shows the warnings displayed during compilation as a result of static checking.
Fig 2.0
If you run the application you will notice the exception messages in the Console window as shown in Fig 2.1 below.
Fig 2.1
Conclusion
I hope this article clearly highlights the use of code contracts in the .NET framework and how it becomes so handy when building components and applications through the design-by-contract principle. Please make use of the comments section below to provide your valuable comments.
Originally published on.
| http://www.developer.com/net/net/learn-about-code-contracts-in-.net-framework-4.0.html | CC-MAIN-2016-26 | refinedweb | 646 | 51.14 |
Hi all,
First time poster from Ireland here.
Anything i know from programming is based off a very quick dip into codeacademy and the first lecture given thus far.
Below is my code for taking the radius of a circle from the user and then going ahead to give radius, area, circumference.
I keep getting a "couldn't find symbol" error when compiling, which i have hunted down to be an issue with my variables.
For the life of my i cannot figure out how to get the scanner element working.
Any and all advice is welcome,
CC.
import java.util.scanner;
class CalculateCircleUserInput
{
public static void main(String[] args)
{
Scanner radius = new Scanner(System.in);
System.out.println("Please input the circle's radius: ");
double radius = radius.nextdouble();
double pi = 3.1416;
double area = pi*radius*radius;
double circumference = pi*radius*2;
System.out.println("You have defined the circle's radius as: " + radius);
System.out.println("It's area is " + area);
System.out.println("It's circumference is " + circumference);
}
} | http://www.javaprogrammingforums.com/whats-wrong-my-code/32488-user-input-trouble.html | CC-MAIN-2015-48 | refinedweb | 171 | 51.85 |
Build Error when Uploading Notebooks in Sage
Running Fedora 26 as a virtual machine, I recently installed Sage 8.0 from source (and was thrilled to see support for Jupiter....amazing!). Besides a minor error coming from Open SSL which I'll try to run down later, Sage seems to work perfectly, until I try to upload one or more zipped notebook files into the Sage Notebook. On screen, after uploading, I get a non descriptive "500:internal error" message. In the terminal, I get the message "Build Error:Could not build url for endpoint 'home' with values ['username']. Did you mean 'worksheet_listing.home' instead?" If the notebook is a new notebook (one which I didn't just download from Sage and reimport for diagnostic purposes) clicking on "continue" allows me to see and interact with the new notebooks. However, if I then exit Sage and restart it and the notebook, I get a 500:internal error in both the sage and jupiter notebooks and nothing else displayed (no link to "continue" to the notebooks or anything else). In the terminal I get a much longer error, which I've copied at the end of my message. Does anyone have any suggestions as to where to start trying to fix this? I've searched the forum, and not seen similar errors, but maybe I missed something. (I read that for a while Sage had import errors with files containing nonascii characters, so I'll add that I can recreate this behavior using a file called "Test" with the single line "1+1" contained in it, as well as using files exported from both a Sage 8.0 server and an older server I am still running.)
Any advice would be greatly appreciated!
(Longer error follows here:)
[E 10:45:37.351 NotebookApp] Uncaught exception GET /sagenb?token=06fdd6ab20a2cd845ccc2c9a972faa770df9dcf12814aeb8 (::1) HTTPServerRequest(protocol='http', host='localhost:8888', method='GET', uri='/sagenb?token=06fdd6ab20a2cd845ccc2c9a972faa770df9dcf12814aeb8', version='HTTP/1.1', remote_ip='::1', headers={'}) Traceback (most recent call last): File "/home/ashicks/Sage/sage-8.0/local/lib/python2.7/site-packages/tornado/web.py", line 1443, in _execute result = method(*self.path_args, **self.path_kwargs) File "/home/ashicks/Sage/sage-8.0/local/lib/python2.7/site-packages/tornado/web.py", line 2800, in wrapper return method(self, *args, **kwargs) File "/home/ashicks/Sage/sage-8.0/local/lib/python2.7/site-packages/sagenb_export/nbextension/list_handler.py", line 35, in get notebooks=tuple(self.notebook_iter()), File "/home/ashicks/Sage/sage-8.0/local/lib/python2.7/site-packages/sagenb_export/nbextension/list_handler.py", line 22, in notebook_iter for notebook in NotebookSageNB.all_iter(dot_sage) File "/home/ashicks/Sage/sage-8.0/local/lib/python2.7/site-packages/sagenb_export/nbextension/list_handler.py", line 22, in <genexpr> for notebook in NotebookSageNB.all_iter(dot_sage) File "/home/ashicks/Sage/sage-8.0/local/lib/python2.7/site-packages/sagenb_export/sagenb_reader.py", line 217, in sort_key return (self.conf['owner'], self.conf['id_number']) KeyError: 'owner' [E 10:45:37.381 NotebookApp] { " } [E 10:45:37.381 NotebookApp] 500 GET /sagenb?token=06fdd6ab20a2cd845ccc2c9a972faa770df9dcf12814aeb8 (::1) 37.04ms referer=None
A useful piece of information may be that the "default" notebook in 8.0 is now a notebook exporter which allows you to export sagenb notebooks to Jupyter. But I don't recognize this particular error.
Thanks, I'm aware, and thanks for taking a look. I was hoping to import old notebooks from an old server, then export them to the Jupyter (as needed/wanted), but I've given up at this point. I'll add for the benefit of anyone in a similar situation in the future that I finally just manually copied the files containing my old notebooks into Sage notebook's standard location on the new server, just long enough to export them to Jupiter, as kcrisman suggests. This avoided the need for an "import", but wouldn't be a long term fix if I wanted to continue to use the old Sage notebook server, as copying files without "importing" them messes with Sage's counter of the number of created notebooks.
Hmm. You are right about this, of course. When you say "zipped", though, I have a couple questions. 1) Are you importing just .sws files or zipped collections thereof? 2) Are you importing through the "Notebook Exporter" or through the actual GUI of the sagenb? The latter shouldn't even be referencing
NotebookApp, once started.
Importing a zipped collection in the GUI of sagenb triggers an "internal error" (the build error in the text above). Restarting sage AFTER the internal error and then running sage -n gets me to the Notebook Exporter, which is then inoperable with it's own "internal error" (and the big box of errors at the end of my post). The notebook exporter has been inoperable ever since (I had to use a different VM to hack my eventual export to Jupyter), but interestingly, I just realized that both the sagenb GUI and Jupyter start fine. So whatever internal error importing in the sagenb causes only is problematic when I run Notebook Exporter afterward. (Weird!) If others post with a similar error, I'll submit a bug report; for now, I'll move on out of respect for everyone's (volunteer) time. Thanks!
Yes, in fact you can do
sage --notebook=sagenb, I think, to just run it without the exporter. My guess is that the exporter doesn't know how to deal with the upload signals from sagenb for the zip. Glad you have a workaround! | https://ask.sagemath.org/question/38486/build-error-when-uploading-notebooks-in-sage/?sort=latest | CC-MAIN-2020-05 | refinedweb | 921 | 56.86 |
0
I've been working on an assignment:
Write a program that produces a bar chart of population growth for a small town, at 20 year intervals during the past 100 years. It should read the populations rounded to the nearest 1000 people. for each year it should display the date and bar consisting of one asterisk for each 1000 people.
the data file contains:
2157
4289
5317
7215
10789
12974
This is what I have so far
#include "stdafx.h" #include <iostream> #include <fstream> using namespace std; int main() { ifstream inputFile; int pop; int count = 0; inputFile.open("c://people.dat"); if (!inputFile) { cout << "Error opening file.\n"; } else { cout << "\t\t\tPrarieville Population Growth\n"; while (count <= 6) { inputFile >> pop; count++; } for (int years = 1900; years <= 2000; years = years + 20) { cout<<years<<endl; } if ( pop >= 1499 || pop <= 2499) { cout << "**\n"; } else if (pop >= 3499 || pop <= 4499) { cout << "****\n"; } else if (pop >= 4499 || pop <= 5499) { cout << "*****\n"; } else if (pop >= 6499 || pop <= 7499) { cout << "*******\n"; } else if (pop >= 10499 || pop <= 11499) { cout << "***********\n"; } else if (pop >= 12499|| pop <= 13499) { cout << "*************\n"; } } return 0; }
But I'm not getting the correct asterisk amounts, and I need the asterisk to be beside the year to show the population. =/ I'm a beginner ... | https://www.daniweb.com/programming/software-development/threads/208944/need-help-with-reading-values-from-a-file | CC-MAIN-2017-47 | refinedweb | 211 | 71.89 |
digitalmars.D.learn - Any way to use static foreach on multiple types?
- Andrej Mitrovic <andrej.mitrovich gmail.com> Oct 02 2011
import std.typetuple; alias TypeTuple!(int, double) Types; void main() { foreach (T1, T2; Types, Reverse!Types) { } } That right there is buggy code on my part, T1 ends up being an index variable and this is another one of those cases where the comma doesn't do anything but confuse people (or just me :p). Anyway, I need some sort of static lockstep, is there such a thing in Phobos? It's not mission-critical, but I want to write a nice stress-test of conversions between my own custom types, and it would be cool if I could do it in a foreach loop with terse syntax.
Oct 02 2011 | http://www.digitalmars.com/d/archives/digitalmars/D/learn/Any_way_to_use_static_foreach_on_multiple_types_29920.html | CC-MAIN-2014-42 | refinedweb | 131 | 74.9 |
Col.“
OSes suffer serious security hole through CPUs
2005-05-13 Privacy, Security 32 Comments
So far all of the examples he seems to have offered are BSDs, and while this is completely understandable (BSD seems to be his area of expertise) perhaps he should’ve taken the time to address more explicitly Windows concerns.
It would be interesting to see if an analagous problem exists for G/Power series processors.
“The flaw affects all operating systems, and for a secure multi-user environment essentially requires that Hyper-Threading be disabled. More information can be found on Colin’s web page on the topic.”
#1 Do I need to worry about my home computer?
Probably not. This security flaw is primarily a problem for servers.
Therefore, most users aren’t concerned.
From what I’ve read, the security problem regards the HT implementation on some Intel processors. He signaled the issue to the OS vendors, which are the ones who should investigate the extent to which they’re affected.
So, I think it’s up to the Windows, Linux, etc. security teams to address the issue on their OS, exactly like the *BSDs have promptly done.
Kudos to Colin Percival, from FreeBSD’s security team. This is a great service, both to FreeBSD users and to the users of other OSes sharing a similar implementation – from what I understand, Windows and Linux are included.
”
So, I think it’s up to the Windows, Linux, etc. security teams to address the issue on their OS, exactly like the *BSDs have promptly done. ”
what makes you think it affects any OS other than BSD’s which have copied from each other to make their implementation a security hole
I know you’re just trolling, but to clarify – it’s a problem with the *hardware*. So it will affect all OSes on HTT boxes.
what makes you think it affects any OS other than BSD’s
This sentence from CP makes me think they *might* be affected:
“Hyper-Threading, as currently implemented on Intel Pentium Extreme Edition, Pentium 4, Mobile Pentium 4, and Xeon processors, suffers from a serious security flaw.”
Also, the kerneltrap article:
“The flaw affects all operating systems, (…)”
… which have copied from each other to make their implementation a security hole
I would slow down on that.. It’s universally acknowledged that the BSDs are among the most secure OSes in the world.
This is just one study:
“The world’s safest and most secure 24/7 online computing environment – operating system plus applications – is proving to be the Open Source platform of BSD (Berkeley Software Distribution) and the Mac OS X based on Darwin.”
How complicated is the exploit? I have seen alot of these problems surface that althought they may be a problem it is not practical to exploit it.
“I know you’re just trolling, but to clarify – it’s a problem with the *hardware*. So it will affect all OSes on HTT boxes.
”
thats NOT clear at all.
“I would slow down on that.. It’s universally acknowledged that the BSDs are among the most secure OSes in the world.
This is just one study: ”
it would very nice if you people stop quoting Laura didio from Yankee group and Mi2g. these two are the top on the list of unreliable sources. I am not claiming that BSD is not secure btw just that you guys should stop assuming that every OS is affected.
>these two are the top on the list of unreliable sources
Well.. actually, I’d say the top of that list is occupied by the people who decide not to show their IP.
“Well.. actually, I’d say the top of that list is occupied by the people who decide not to show their IP.
”
matter of privacy really and the fact that I dont control my DHCP gateway
How did you do that?!?
if you read the source you’ll see the repeated need for the rdtsc instruction which can only be executed with a cpl of zero, if you had that privilege level you could just core dump the entire process.
if you read the source you’ll see the repeated need for the rdtsc instruction which can only be executed with a cpl of zero, if you had that privilege level you could just core dump the entire process.
The purpose of this exploit is to create a covert channel. Causing the process you’re spying on to dump core is a sure give away and doesn’t lend to gathering keys covertly.
rdtsc can be executed by non-priveldged processes on most OSes that I’m aware of:
#include <stdio.h>
#include <sys/types.h>
#include <machine/cpufunc.h>
int main(int argc, char **argv)
{ printf(“tsc is %lld
“, rdtsc()); }
Works on FreeBSD as a non-priveldged user. mph must be mistaken that it requires special privs to run.
This is a hardware problem. The shared cache of the HTT is what the problem is.
Intel recommends that, for performance reasons, one schedule from the same address space on the different HTTs. However, all OSes that I’m aware of schedule different processes (address spaces) on the different HTTs. In fact, I believe that HTTs show up as CPUs unless the OS goes to measure to notice that they are just virtual CPUs. This is why OpenBSD users need to disable HTT in the BIOS, for example.
Linux definitely does scheduling in an unsafe manner for HTT processors.
Confirmed. Runs outside of ring 0.
What the hell is FreeBSD Core doing wasting their time here :-P.
the info for rdtsc in ring-0 was from the intel docs, which if executed generates a GPF if executed outside of the ring. the method used to call rdtsc from within the OS appears to be a function call which in itself would add latency to the procedure and rendering it in its current form useless.
First, you should look at the generated code for the program I posted. The following code:
uint64_t x1=rdtsc(); uint64_t x2=rdtsc();
produces:
rdtsc
movl %eax, %esi
movl %edx, %edi
rdtsc
movl %eax, %ecx
subl %esi, %ecx.
Do you have other HARD NUMBERS to backup your claim that tsc is useless for timing from userland? These simple experiments show on its surface appears to support Collin’s claims.
I’m sure that if this guy spent three hard-working months investigating and contacting people about this, he wouldn’t have overlooked the fact that rdtsc was ring 0 (if that was the case).
I didn’t claim that tsc was useless from userland, the point that I was trying to get accross was the utilisation of the rdtsc instruction within ring-3 when I beleive that it should be disabled (CR4), then in order to retreive a rdtsc value one must use a call gate which would increase the latency of the instruction.
Perhaps even outside of the limited 100 cycle window depending on the implementation.
… someone asked if he/she should worry about his/her home computer. This flaw only matters if multiple people use the same machine, and those people want privacy from each other. Given two users, Alice and Bill, Alice might be able to run a program that can steal Bill’s private RSA key.
But if Bill is the only user of his machine, he can hyperthread to his heart’s content, even if there’s a way that he can spy on himself.
Also, for a home machine, there are other, easier ways to defeat security. So even for shared home machines this doesn’t matter.
One possible workaround is to modify kernels so that two processes can’t share the same physical CPU, in different hyperthreads, unless both are run by the same user and neither is privileged. But this might not be necessary for all processes; we might want to mark processes with an attribute that says whether we care about this kind of information leak.
How many Windows users run true multi-untrusted-user machines? I’ve seen it occasionally, but you can only run so many remote desktop sessions on a single OC3 line
.
Setting the tsd flag is not the way to fix this problem. There are legitimate uses for rdtsc outside of exploits obviously.
#1 Do I need to worry about my home computer?
Probably not. This security flaw is primarily a problem for servers.
Therefore, most users aren’t concerned.
Until your favourite website goes down :p
.
Hopefully you didn’t just run the timing ONCE per program invocation ? If so, yes, you got “lucky” , the program executed all the handfuls of instructions in its timeslice, and you got similar time each time.
Now consider doing the timings in a loop a few million times, and comparing the times. Or trying to time something that takes a while, and think you can measure it with some nanoseconds resolution…
What if the scheduler kicks in, and schedules another process to run for some milliseconds. Or the OS decides to spend some time processing network packets. Or …
From the documentation:
———————————————————–
RDTSC Read from Time Stamp Counter
Copies the contents of the Time Stamp Counter (TSC) into EDX EAX. (The Pentium maintains a 64-bit Time Stamp Counter (TSC) that is incremented every clock cycle.) When the Current Privilege Level is 0, the state of the TSD bit in CR4 does not affect the operation of this instruction. When the CPL is equal to 1, 2, or 3, the TSC may be read only if the TSD bit in CR4 is 0. Only a supervisor level program may modify the value of the TSC.
Flags: No flags affected.
Encoding: 00001111 00110001
Syntax Example Clock Cycles
RDTSC rdtsc 6, 11
———————————————————–
So as the above indicates, rdtsc is allowed to run from user level if the OS permits it. No exception is generated. I don’t know of an OS that does not permit the use of rdtsc by user level code.
HTT: threads are shared though out the pipeline, no thanks!
It would be more in action of the x86 cpus could not reorder instructions – it might be more effective on Itanium.
With respect to worrying about home computers:
You _should_ worry if you are not 100.00% sure there is no spyware or trojans on your computer and you use the computer for financial transactions (home-banking etc).
On the other hand, the spyware and trojans should make you worry already in that scenario, so this just gives them another tool with which to screw you.
The important thing here is _not_ if the computer is single user, but if you can trust all the code that runs on it or not.
Poul-Henning
In one of the Pentium programming books from 1997, “inner loops” by Rick Booth he goes to great lengths to show us how to optimize asm code and time it to see that the optimization was worth doing.
After seeing that I used it right away, far more accurate down to the cycle than the system clock. I suspect its widely used today and taking it away would be bad idea.
If you know how the cache works and want to snoop its activity then RDTSC could certainly tell you indirectly what it is doing. If this fella hadn’t thought of it, somebody else would have sooner or later. | https://www.osnews.com/story/10582/oses-suffer-serious-security-hole-through-cpus/ | CC-MAIN-2021-49 | refinedweb | 1,909 | 70.23 |
This short tutorial introduces you how to install a C compiler plus a text editor to do C programming on Ubuntu. The compiler is GNU gcc and the editor is Geany. Don't worry, this tutorial is intended for beginners and easy to follow. I will show you how to compile a .c source code file until executing it using Geany. Happy learning!
1. Install Compiler
Do it:
$ sudo apt-get install -V gcc
2. Install Editor
Do it too:
$ sudo apt-get install geany
3. Write
Now run Geany and write this short lines of code. Save it as program.c.
#include <stdio.h>
int main()
{
printf("hello, C programming!\n"); // print to screen
return 0;
}
4. Compile
Now, compile your source code. Press Compile button, then press Build button. If your source code is free from errors, this compilation should produce a file named program without extension on the same folder as your .c file. See GIF animation below.
- What's Compile button? Pressing this button is the same as gcc -c program.c that produces a file named program.o. This file is called object file.
- What's Build button? Pressing this button is the same as gcc -o program program.c that produces the final file named program. This file is called binary executable file.
- What's Run button? Pressing this button is the same as ./program that is executing the binary executable file.
5. Run
Now press Run button. This should open a Terminal and show the output of your code. The output should say hello, c programming! . If this is your first experience with programming, welcome to C and keep learning!
C Source Code Examples
Where to get .c sources on the net? If you have a textbook about C, just type the source code available there. But if you don't have any, go to. They have enough C source codes arranged in chapter by chapter that are suitable for beginners. Learn them one by one! | https://www.ubuntubuzz.com/2017/09/setup-c-programming-tools-on-ubuntu-for-beginners.html | CC-MAIN-2020-50 | refinedweb | 333 | 79.36 |
Export a GeoDataFrame to Spatialite
I have been doing some geospatial analysis in the last few months, and since I came back from GeoPython in Basel (really good conference by the way, definitely recommended) I kept playing around with several Python libraries.
One of my favourite talks at the conference was by John A Stevenson, a Scottish volcanologist.
Apart from the scans of his amazing field notebooks, beautifully filled with annotations and drawings, I was impressed by his technical expertise and passion for his work.
John mentioned that a common issue for researches that have to showcase their work at conferences is to deal with shapefiles. Instead of having to juggle with many different folders, files, and versions, he suggested to use a portable geospatial database. He mentioned two software solutions: Geopackage and Spatialite.
Given that I had already heard about Spatialite, I decided to try it.
In a toy project of mine I used some shapefiles available on the Open Data portal of Tuscany. I loaded the shapefiles with GeoPandas, performed some really simple geospatial analysis, and created a few maps with GeoViews and Cartopy. I decided to use Spatialite to export the geometries created by GeoPandas to a SQLite database.
The
GeoPandas’s
GeoDataFrame class inherits from
Pandas’s
DataFrame, so it has a
to_sql() method. I thought: “I just have to call that method and pass the connection URI to my SQLite database, easy peasy!”.
Well, turns out it wasn’t actually that easy… so I am writing this post to remember what I did.
Install SpatialiteInstall Spatialite
Spatialite is actually a geospatial extension of SQLite, namely a set of functions that allow to store geospatial data in a SQLite database.
If you are on a Ubuntu-based distro, you can install Spatialite with:
sudo apt-get update
sudo apt-get install spatialite-bin
Check your geometriesCheck your geometries
Check the geometry type of each row in the
GeoDataFrame. In my case, all geometries were of type
Polygon. I think that if you have mixed geometry types (e.g.
Polygon and
MultiPolygon) you have to use shapely methods (via GeoPandas) to convert them. Or maybe use different columns for different geometries that you want to store in the database.
# gdf is a GeoPandas DataFrame
print(gdf.geometry.type)
>>> Polygon
Create a database table with no geospatial datatypesCreate a database table with no geospatial datatypes
Even if you cannot use
gdf.to_sql() if you have some geospatial data, it’s fine if your
GeoDataFrame doesn’t actually contain geospatial data (so it’s basically just like any other Pandas
DataFrame).
Connect to your SQLite database and create a new table.
import os
import sqlite3
DB_PATH = os.path.join(os.getcwd(), 'your-database.db')
# Drop all geospatial data
df = gdf.drop(['geometry', 'AREA', 'PERIMETER'], axis=1)
# Create the table and populate it with non-geospatial datatypes
with sqlite3.connect(DB_PATH) as conn:
df.to_sql('your_table_name', conn, if_exists='replace', index=False)
Note: This is like any other “standard” export from a pandas DataFrame into a SQLite database table. There is no Spatialite functionality involved here. Not yet.
Add a new column to store the geometryAdd a new column to store the geometry
Now that you have your table, you can use the Spatialite extension to add a new table column to store your geometry (i.e. your geospatial data.
You might wonder: why do I have to add this column now? Couldn’t I have added the column when I created the table?
According to the Spatialite documentation, you always must first create the table, then add the Geometry-column in a second time and as a separate step.
Another thing you have to is to load the Spatialite extension and to initialize your spatial metadata.
Let’s say that your geometry is a
Polygon, you want to use EPSG:3857 as a projected coordinate system, and you want to name your column
wkb_geometry (see next step why this name). This is what you have to do:
with sqlite3.connect(DB_PATH) as conn:
conn.enable_load_extension(True)
conn.load_extension("mod_spatialite")
conn.execute("SELECT InitSpatialMetaData(1);")
conn.execute(
"""
SELECT AddGeometryColumn('your_table_name', 'wkb_geometry', 3857, 'POLYGON', 2);
"""
)
So, to recap:
InitSpatialMetaData()and
AddGeometryColumn()are functions from Spatialite, so you have to load it as a SQLite extension.
InitSpatialMetaData()must be called before attempting to call any other Spatial SQL function.
- You just need to call
InitSpatialMetaData()once; calling it multiple times is useless but completely harmless.
- First create the table, then add the Geometry-column as a separate step.
Convert each shapely geometry into a WKB representationConvert each shapely geometry into a WKB representation
SQLite 3 supports only a few storage classes (i.e. datatypes). You need to store your geospatial data as BLOB.
GeoPandas stores geospatial data as shapely geometries, so you have to convert them somehow. Thanks to this answer on GIS Stack Exchange I found that the
shapely.wkb module provides
dumps() and
loads() functions that work almost exactly as their
pickle and
simplejson module counterparts. See here for details.
Each geometry in a GeoPandas
GeoDataFrame is a
GeoSeries. A
GeoSeries is basically a shapely geometry with some additional properties. This means that you can convert a geometry into a binary string with something like this:
wkb = swkb.dumps(gdf.geometry.iloc[0]
Since the database column is already there (until now it’s filled with
NULL), you have to use a SQL
UPDATE SET statement.
I wanted to use
executemany to perform a batch update, but in order to do that I also needed a
WHERE clause and an identifier to understand which table cell to update.
When you use
executemany you have to pass a tuple of tuples as a query parameter, so I prepared my data like this:
import shapely.wkb as swkb
records = [
{'some_id': gdf.some_id.iloc[i], 'wkb': swkb.dumps(gdf.geometry.iloc[i])}
for i in range(gdf.shape[0])
]
As you can see, each shapely geometry has been converted into its own Well Known Binary representation.
print(type(gdf.geometry.iloc[0]))
>>> <class 'shapely.geometry.polygon.Polygon'>
print(type(records[0]['wkb']))
>>> <class 'bytes'>
Populate the column with binary dataPopulate the column with binary data
One last step before populating the table is to create the tuple of tuples to use as a query parameter (because I’m doing a batch update with
executemany).
tuples = tuple((d['wkb'], d['some_id']) for d in records)
Finally, the batch update query:
with sqlite3.connect(DB_PATH) as conn:
conn.enable_load_extension(True)
conn.load_extension("mod_spatialite")
conn.executemany(
"""
UPDATE your_table_name
SET wkb_geometry=GeomFromWKB(?, 3857)
WHERE your_table_name.some_id = ?
""", (tuples)
)
Double check that it workedDouble check that it worked
There are several ways to double check that the database contains the right geospatial data.
You can perform a simple query:
with sqlite3.connect(DB_PATH) as conn:
conn.enable_load_extension(True)
conn.load_extension("mod_spatialite")
cur = conn.execute(
"""
SELECT wkb_geometry FROM your_table_name
"""
)
results = cur.fetchall()
print(results)
or you can use a Spatialite viewer like Spatialite GUI and use its Map Preview feature.
ReferenceReference
Jupyter notebook where I used Spatialite.
ExtraExtra
Joris Van den Bossche and Levi John Wolf also gave two excellent talks about GeoPandas, PySal, and geospatial analysis. Be sure to check out their tutorials here and here. The best thing is that you can run their notebooks with binder without having to install anything on your machine! | https://www.giacomodebidda.com/posts/export-a-geodataframe-to-spatialite/ | CC-MAIN-2021-21 | refinedweb | 1,226 | 56.35 |
The main purpose of the pyublas module is to make the automatic to- and from-Python converters available upon being imported.
Issue a warning if the array val will not successfully convert to a numpy_vector or numpy_matrix. Return val unchanged.
When debugging an overload failure, simply insert a call to this function in the argument list of the failing call:
do_stuff(pyublas.why_not(myarray))
If set to true, prints diagnostic messages upon each failed vector conversion explaining what went wrong. (Note that each argument may go through a number of failed conversions before the correct one is found.)
CAUTION: In PyUblas version 0.91 and later, the sparse wrappers are an optional feature that has to be enabled at configure time with the option --with-sparse-wrappers. You may check for their presence using this function:
Return a bool indicating whether PyUblas was compiled with sparse matrix wrappers.
In addition to numpy_vector and numpy_matrix, PyUblas also wraps Ublas’s powerful sparse matrix machinery into Python objects. The interface to these functions is somewhat like numpy‘s own and is found in the pyublas name space.
Here’s a brief demo:
import numpy import pyublas a = pyublas.zeros((5,5), flavor=pyublas.SparseBuildMatrix, dtype=float) a[4,2] = 19 b = numpy.random.randn(2,2) a.add_block(2, 2, b) a_fast = pyublas.asarray(a, flavor=pyublas.SparseExecuteMatrix) vec = numpy.random.randn(5) res = a_fast * vec print a_fast print res
This prints something like:
sparse({2: {2: 0.774217588463, 3: -1.5320702452}, 3: {2: 0.118048365647, 3: 1.05028340411}, 4: {2: 19.0}}, shape=(5, 5), flavor=SparseExecuteMatrix) [ 0. 0. -0.60793048 0.13384055 -8.28513612]
The SparseBuildMatrix flavor is designed for fastest possible assembly of sparse matrices, while the SparseExecuteMatrix flavor is made for the fastest possible matrix-vector product. There’s much more functionality here–don’t be afraid to peek into the source code. | https://documen.tician.de/pyublas/pymodule.html | CC-MAIN-2021-39 | refinedweb | 315 | 59.6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.