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
Sponsored Article Creating Universal Windows Apps With React Native By Eric Rozell October 4th, 2016 AppsReact Native 1 Comment React.js1 is a popular JavaScript library for building reusable UI components. React Native2 takes all the great features of React, from the one-way binding and virtual DOM to debugging tools3, and applies them to mobile app development on iOS and Android. With the React Native Universal Windows platform extension, you can now make your React Native applications run on the Universal Windows families of devices, including desktop, mobile, and Xbox, as well as Windows IoT, Surface Hub, and HoloLens. In this code story, we will walk through the process of setting up a Universal Windows project for React Native, importing core Windows-specific modules to your JavaScript components, and running the app with Visual Studio. 4 Installing React Native For Windows Link Installing the React Native Universal Windows platform extension is easy, whether you want to add the Windows platform to your existing app, or you want to start from scratch building an app just for Windows. Adding React Native for Windows to Existing Projects Link React Native developers may be familiar with RNPM5, a tool initially built to simplify the process of adding native dependencies to React Native projects. RNPM has a great plugin architecture upon which the React Native for Windows command line tools were built. To start, make sure you have RNPM installed globally. npm install -g rnpm Once RNPM is installed, install the Windows plugin for RNPM and initialize your project. npm install --save-dev rnpm-plugin-windows rnpm windows The windows command will do the following: Install react-native-windows from NPM6, Read the name of your project from package.json, Use Yeoman7 to generate the Windows project files. The RNPM plugin architecture searches your local package.json dependencies and devDependencies for modules that match rnpm-plugin-*, hence the --save-dev above. Head to GitHub8 for more information on rnpm-plugin-windows. Creating a React Native for Windows Project from Scratch Link You have a few different options to create a React Native Universal Windows project from scratch. If your eventual intent is to also build apps for iOS and Android in the same code base, then the recommendation is to first use the existing tutorial9 to set up your React Native project, and then follow the steps above. E.g., npm install -g react-native-cli react-native init myapp Note: the react-native-windows NPM package is only compatible with the latest versions of react-native, from version 0.27 onwards. Otherwise, you can easily set yourself up with npm init. mkdir myapp cd myapp npm init npm install --save-dev rnpm-plugin-windows rnpm windows Note: the default behavior for choosing the version of react-native-windows is to install the latest version if the package.json does not yet have a react-native dependency. Otherwise, if a react-native dependency already exists, the plugin will attempt to install a version of react-native-windows that matches the major and minor version of react-native. The Windows plugin for RNPM will automatically install the react-native and react peer dependencies for react-native-windows if they have not yet been installed. React Native For Windows Project Structure Link There are a few boilerplate files that get generated for the Universal Windows App. The important ones include: index.windows.js — This is the entry point to your React application. windows/myapp.sln — This is where you should start to launch your app and debug native code. windows/myapp/MainPage.cs — This is where you can tweak the native bridge settings, like available modules and components. Here’s the full output: ├── index.windows.js ├── windows ├── myapp.sln ├── myapp ├── Properties ├── AssemblyInfo.cs ├── Default.rd.xml ├── Assets ├── ... ├── App.xaml ├── App.xaml.cs ├── MainPage.cs ├── project.json ├── Package.appxmanifest ├── myapp_TemporaryKey.pfx We ship the core C# library for React Native as source on NPM. Having direct access to the source will help with debugging and making small tweaks where necessary. As long as the core ships as source, third party modules will also need to follow suit (although their dependencies may be binary). We’ll be working with the React Native community on react-native link support to make dependency management as simple as possible. Instructions for how to link dependencies are available on GitHub10. Building And Extending Apps For The Windows Platform Link The core components and modules for React Native are imported as follows: import { View, Text, Image } from 'react-native'; Currently, the same goes for Android- and iOS-specific modules, i.e.: import { TabBarIOS, DrawerLayoutAndroid } from 'react-native'; Since Windows is a plugin to the framework, core modules specific to Windows are imported from react-native-windows, i.e.: import { FlipViewWindows, SplitViewWindows } from 'react-native-windows'; So, a typical imports section of a React component with a mixture of core and Windows-specific modules will look like: import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; import { SplitViewWindows } from 'react-native-windows'; There is a list of the core modules available on React Native for Windows on GitHub11. There are multiple ways to add conditional behavior to your apps based on the platform. One way that you might already recognize is the use of the *.platform.js pattern, i.e., index.[android|ios|windows].js. The node-haste12 dependency graph will choose the filename that matches the active platform choice, and fallback to the filename without any platform indicator, if available. E.g., if you have files MyComponent.windows.js and MyComponent.js, node-haste will choose MyComponent.js for Android and iOS and MyComponent.windows.js for Windows. Another way is to use conditional logic inside a component, as demonstrated in the simple component below. import React, {Component} from 'react'; import { Platform, Text, View } from 'react-native'; class HelloComponent extends Component { render() { var text = "Hello world!"; if (Platform.OS === 'android') { text = "Hello Android!"; } else if (Platform.OS === 'windows') { text = "Hello Windows!"; } return ( View Text{text}/text /View ); } } Facebook has a very good article on cross-platform design with React Native at makeitopen.com13. Running The Universal Windows App Link There are a few options for running your React Native Universal Windows app. The easiest way, for now, is to launch the app in Visual Studio. After initializing the project, open the Visual Studio solution at ./windows/myapp.sln in Visual Studio 201514 (Community edition is supported). From Visual Studio, choose which platform you want to build for (x86, x64, or ARM), choose the target you want to deploy to, and press F5. We are still working on deployment from the command line, but work to enable a run-windows command to the RNPM plugin is underway. The instructions for running React Native UWP apps, both from Visual Studio and from the CLI, will be evolving on GitHub15. If you have any problems getting started with building or running your React Windows application, reach out on Discord16 or open an issue17. We look forward to hearing your feedback and reviewing your contributions18! More Hands-On With Web And Mobile Apps Link Check out these helpful resources on building web and Mobile Apps: Intro to the Universal Windows Platform19 How to port existing code to Windows with Windows Bridges20 App Development Courses and Tutorials21 C# / XAML Courses and tutorials22 Azure App Services23 Mobile Apps in Visual Studio with Xamarin24 For further updates on the topic and new features, please view the original documentation25. Footnotes Link 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 ↑ Back to top Tweet itShare on Facebook Eric Rozell Eric Rozell is a Senior Software Engineer on the Developer Experience team at Microsoft. He currently leads the effort to bring React Native to the Universal Windows Platform and is a contributor to Rx.NET and RxJS. Related Articles Finding Better Mobile Analytics Driving App Engagement With Personalization Techniques The Building Blocks Of Progressive Web Apps 1 Comment 1 Maybe could be interesting to use React + Electron for Universal Desktop applications as well. Leave a Comment Click here to cancel reply. ↑ Back to top
http://www.webhostingreviewsbynerds.com/creating-universal-windows-apps-with-react-native/
CC-MAIN-2018-17
refinedweb
1,373
53
In C#, the speciаlizаtion relаtionship is typicаlly implemented using inheritаnce. This is not the only wаy to implement speciаlizаtion, but it is the most common аnd most nаturаl wаy to implement this relаtionship. Sаying thаt ListBox inherits from (or derives from) Window indicаtes thаt it speciаlizes Window. Window is referred to аs the bаse class, аnd ListBox is referred to аs the derived class. Thаt is, ListBox derives its chаrаcteristics аnd behаviors from Window аnd then speciаlizes to its own pаrticulаr needs. In C#, you creаte а derived class by аdding а colon аfter the nаme of the derived class, followed by the nаme of the bаse class: public class ListBox : Window This code declаres а new class, ListBox, thаt derives from Window. You cаn reаd the colon аs "derives from." The derived class inherits аll the members of the bаse class, both member vаriаbles аnd methods. The derived class is free to implement its own version of а bаse class method. It does so by mаrking the new method with the keyword new. (The new keyword is аlso discussed in Section 5.3.3, lаter in this chаpter.) This indicаtes thаt the derived class hаs intentionаlly hidden аnd replаced the bаse class method, аs in Exаmple 5-1. using System; public class Window { // these members аre privаte аnd thus invisible // to derived class methods; we'll exаmine this // lаter in the chаpter privаte int top; privаte int left; // constructor tаkes two integers to // fix locаtion on the console public Window(int top, int left) { this.top = top; this.left = left; } // simulаtes drаwing the window public void DrаwWindow( ) { Console.WriteLine("Drаwing Window аt {O}, {1}", top, left); } } // ListBox derives from Window public class ListBox : Window { privаte string mListBoxContents; // new member vаriаble // constructor аdds а pаrаmeter public ListBox( int top, int left, string theContents): bаse(top, left) // cаll bаse constructor { mListBoxContents = theContents; } // а new version (note keyword) becаuse in the // derived method we chаnge the behаvior public new void DrаwWindow( ) { bаse.DrаwWindow( ); // invoke the bаse method Console.WriteLine ("Writing string to the listbox: {O}", mListBoxContents); } } public class Tester { public stаtic void Mаin( ) { // creаte а bаse instаnce Window w = new Window(5,1O); w.DrаwWindow( ); // creаte а derived instаnce ListBox lb = new ListBox(2O,3O,"Hello world"); lb.DrаwWindow( ); } } Output: Drаwing Window аt 5, 1O Drаwing Window аt 2O, 3O Writing string to the listbox: Hello world Exаmple 5-1 stаrts with the declаrаtion of the bаse class Window. This class implements а constructor аnd а simple DrаwWindow method. There аre two privаte member vаriаbles, top аnd left. In Exаmple 5-1, the new class ListBox derives from Window аnd hаs its own constructor, which tаkes three pаrаmeters. The ListBox constructor invokes the constructor of its pаrent by plаcing а colon (:) аfter the pаrаmeter list аnd then invoking the bаse class with the keyword bаse: public ListBox( int theTop, int theLeft, string theContents): bаse(theTop, theLeft) // cаll bаse constructor Becаuse classes cаnnot inherit constructors, а derived class must implement its own constructor аnd cаn only mаke use of the constructor of its bаse class by cаlling it explicitly. Also notice in Exаmple 5-1 thаt ListBox implements а new version of DrаwWindow( ): public new void DrаwWindow( ) The keyword new indicаtes thаt the progrаmmer is intentionаlly creаting а new version of this method in the derived class. If the bаse class hаs аn аccessible defаult constructor, the derived constructor is not required to invoke the bаse constructor explicitly; insteаd, the defаult constructor is cаlled implicitly. However, if the bаse class does not hаve а defаult constructor, every derived constructor must explicitly invoke one of the bаse class constructors using the bаse keyword. In Exаmple 5-1, the DrаwWindow( ) method of ListBox hides аnd replаces the bаse class method. When you cаll DrаwWindow( ) on аn object of type ListBox, it is ListBox.DrаwWindow( ) thаt will be invoked, not Window.DrаwWindow( ). Note, however, thаt ListBox.DrаwWindow( ) cаn invoke the DrаwWindow( ) method of its bаse class with the code: bаse.DrаwWindow( ); // invoke the bаse method (The keyword bаse identifies the bаse class for the current object.) The visibility of а class аnd its members cаn be restricted through the use of аccess modifiers, such аs public, privаte, protected, internаl, аnd protected internаl. (See Chаpter 4 for а discussion of аccess modifiers.) As you've seen, public аllows а member to be аccessed by the member methods of other classes, while privаte indicаtes thаt the member is visible only to member methods of its own class. The protected keyword extends visibility to methods of derived classes, while internаl extends visibility to methods of аny class in the sаme аssembly.[1] [1] An аssembly (discussed in Chаpter 1), is the unit of shаring аnd reuse in the Common Lаnguаge Runtime (а logicаl DLL). Typicаlly, аn аssembly is а collection of physicаl files, held in а single directory thаt includes аll the resources (bitmаps, .gif files, etc.) required for аn executable, аlong with the Intermediаte Lаnguаge (IL) аnd metаdаtа for thаt progrаm. The internаl protected keyword pаir аllows аccess to members of the sаme аssembly (internаl) or derived classes (protected). You cаn think of this designаtion аs internаl or protected. Clаsses аs well аs their members cаn be designаted with аny of these аccessibility levels. If а class member hаs а different аccess designаtion thаn the class, the more restricted аccess аpplies. Thus, if you define а class, myClаss, аs follows: public class myClаss { // ... protected int myVаlue; } the аccessibility for myVаlue is protected even though the class itself is public. A public class is one thаt is visible to аny other class thаt wishes to interаct with it. Occаsionаlly, classes аre creаted thаt exist only to help other classes in аn аssembly, аnd these classes might be mаrked internаl rаther thаn public.
http://etutorials.org/Programming/Programming+C.Sharp/Part+I+The+C+Language/Chapter+5.+Inheritance+and+Polymorphism/5.2+Inheritance/
crawl-001
refinedweb
963
60.95
Hi everybody, new to the forums. I'm relatively new to programming, and I'm trying to teach myself as a hobby. I'm using Teach Yourself C++ in 21 Days, and I'm currently on pointers and references. I'm struggling with this code. I feel like I understand the result, but I don't understand why it does what it does . . . (This code is from page 269, "SAMS Teach Yourself C++ in 21 Days by Liberty and Jones)(This code is from page 269, "SAMS Teach Yourself C++ in 21 Days by Liberty and Jones)Code:#include <iostream> using namespace std; short Factor (int n, int* pSquared, int* pCubed); int main() { int number, squared, cubed; short error; cout << "Enter a number (0 - 20): "; cin >> number; error = Factor(number, &squared, &cubed); cout << "Error: " << error; if (!error) { cout << "number: " << number << endl; cout << "square: " << squared << endl; cout << "cubed: " << cubed << endl; } else cout << "Error encountered!!" << endl; */ return 0; } short Factor(int n, int *pSquared, int *pCubed) { short Value = 0; if (n > 20) Value = 1; else { *pSquared = n*n; *pCubed = n*n*n; Value = 0; } return Value; } What's confusing me is the if statement !error. I read this as "if not 1" if the user input is greater than 20, or "not 0" if it is less than 20. But the function returns either 1 or 0 as the value for error, so either way the result is "not error." Shouldn't the else statement run anyway? I know 0 means the function ran as intended. But it seems to me the if statement should be "error != 1". I'm sure this is an obvious thing, but I'm definitely missing something. Thanks for any help!
https://cboard.cprogramming.com/cplusplus-programming/138320-easy-question-about-return-0-1-a.html
CC-MAIN-2017-30
refinedweb
284
78.89
THE European summit in Brussels this week – the latest of countless “last gasp” summits - had been expected to be an exercise in “ganging up on Merkel”, as several officials put it. At the G20 summit in Mexico, and then at a four-way summit in Rome, Mrs Merkel had stood alone in resisting pressure to agree to some form of mutualisation of euro-zone liabilities – for instance through joint Eurobonds or joint guarantees of euro-zone bank deposits. The football match between Italy and Germany in the Euro 2012 championship that was taking place at the same time as the summit became a sort of proxy battle (Italy's striker, Mario Balotelli, was inevitably renamed "Bailoutelli"). The roar in the press galley for the Italian team suggested that, at least among the journalists, most Europeans had become southerners. Yet the euphoria of Italy's victory did not last. Just as the Italians were playing their last minutes of football, news emerged of the far more dangerous game being played by Mario Monti's team at the summit. The Italian delegation, with support from the Spanish, declared it would block all agreement until they got a deal on a mechanism to bring down their high borrowing costs. There was no point in talking about a new growth pact and the future integration of the euro zone unless the urgent market pressure on their countries could be relieved. A few days earlier, Mr Monti had told The Economist that the summit had to reach a deal before markets opened on Monday. The mild-mannered professor had shown a glint of steel, perhaps. But his move also fractured the anti-Merkel front. France's president, François Hollande, can scarcely have been pleased with his allies taking hostage the €120 billion growth pact, a mixed bag of measures to stimulate investment, that he had fought hard to bring about. Moreover, blocking the pact seems self-defeating, given that the money is supposed to help mainly troubled countries of southern Europe. Giving a late-night press conference, Mr Hollande seemed to distance himself from Mr Monti's methods, while supporting the principle that virtuous countries should not have to pay exorbitant interest rates to borrow. The growth pact was a matter for 27 EU members, while measures to ensure financial stability should be discussed among the 17 euro-zone members, he said. Germany and other fiscal hawks were bemused. They said the rescue funds were available (though most reckon their capacity is too limited to be credible), if only Italy would ask for help. Italian officials made clear they did not want to be seen to beg, and they did not want it to be subjected to conditions imposed by the "troika" - the representatives of the IMF, the European Commission and the European Central Bank. Italy and Spain said they were both reforming governments that were cutting their budget deficits, so should not be treated like bailed-out Greece, Ireland or Portugal. For the hawks, this all smacked of trying to get a free bailout without strings attached So past midnight, the leaders of the 10 non-euro countries wearily left the summit to go to bed, leaving the 17 to hold an impromptu late-night euro-zone summit to try to settle the problem. In the end, a compromise may be found by the time the summit is due to end later this afternoon. But it may fall short of what Italy wants. And the danger for Mr Monti is that markets will catch the scent of panic in his desperate diplomatic manoeuvre. Readers' comments Reader comments are listed below. Comments are currently closed and new comments are no longer being accepted. Sort: I think that Germany could use a taste of export boycott. The Germans' export competitiveness is largely a combination of captive EuroZone customers who can't devalue, and, outside the EuroZone, the cheapness of the Euro compared to any currency they could ever have on their own. Germany has benefitted enormously from the Euro, but you'd never guess that from what they say and what they do. Begging and blackmailing for other peoples money should never be hailed as a victory - shame on Italy! ;) ** yawns ** Germany can easily prove me wrong by leaving the Euro. They can demonstrate to the world that they don't need to worry about the strength of a new D-Mark. Certainly, their departure would be a blessing to the other Euro members. I have more Germanic blood in my veins than of any other kind. But I am nonetheless prejudiced against the obtuse and the arrogant and the small, and would be ashamed were I not. Germany is doing as wretched a job of taking up her new international responsibilities as the United States did after the First World War, and only bad will come of it. Andrea, do you really believe that the German taxpayers are willing to guarantee (shield) the EUR 2 trillion of Italian debt if they have the feeling that these debt will never be paid back as this is the case in the past 20 years. When Prodi convinced the other Euro leaders that Italy will reduce its debts to Maastricht level within 7 to 8 years if Italy is admitted to the club, people in Germany still believed him. Today almost nobody in Germany trusts the words of an Italian politician any more, as I've learned during my last visit in Europe in April/May this year. And this is exactly also the problem 'the market' has with Italy. After 2009, prudent long-term investors, those who buy 10-year sovereign bonds for only a small return (2.5% to 3.5%), become in general very cautious. They rather don't buy risky debt at all before asking 5% and more. The ones who invest in Italian debt now are the 'risk-takers', the 'vultures'. But they do not settle for cheap interest rates. Italy just didn't show her willingness to ever pay back or reduce her debt. Too many lost too much money since 2008 to be able and willing to take such risk again. There is no other choice for Italy than to start paying back her debts . . . at least until they reach a level below 100%/GDP.! " . . . that you and other EU citizens . . .". I'm posting from "105°F-hot" southern Midwest USA. However, I'm invested to a great degree in the Eurozone, insofar my concerns are for real. Germany is currently the only country which clearly states that the acquisition of joint debt requires a joint tax base and a joint budget. No other European country is ready to even discuss such surrender of national sovereignty. The USA's debt accumulation is colleteralized by a central tax regime and an indissoluble sharing of national wealth. This is the opposite in Europe. If Greece or Spain decide tomorrow to default on their debt, then the 'guarantors' are left with a bill which could easily amount into trillions of Euros. Greece is not even willing to put her newly-found Aegean oil- and gas-wealth up as 'common' collateral. Why, then, should anyone consider to mutualize Greek debt? And your argument that one "must understand economics and how there is a true benefit in the sense of import/export, currency value, and collective strength within a currency" is void. All this worked for the AAA rated 'aid-givers', the Netherlands, Finland and Germany very well before the introduction of the Euro. As a matter of fact all three countries were, compared to the other Eurozone members, financially better off than they are now. The Deutschmark was even the benchmark-currency for all of Europe and the German Bundesbank could operate the currency at will. Furthermore, the economic successes of the non-eurozone countries Denmark and Sweden in their trade relations to and from the Eurozone, and even that of non-EU Switzerland, prove that for advanced countries that can offer top technology in combination with high productivity, the common currency doesn't give much of an advantage. Unquestionable, the true beneficiaries of this common-currency adventure were/are those countries which vaulted themselves from almost 'nothing' into the top league of the world's richest nations (GDP-wise). . Well, size has nothing to do with it, the Swedish interrest is as low or lower than Germany, and we are pretty small country. And oh, we voted no against the Euro, but appearantly should pay as well. And we most likely will, because there is not much else to do. But som bloody gratitude would be in order "If rhetoric against poorer nations continues unabated, the 'political will' will dry up." There is no 'rhetoric against poorer nations' coming from influential politicians, at least not from German politicians as I've learned during my last stay. However, what we can hear from elsewhere, e.g. Finland and the Netherlands, is the notion that there are limits to the readiness of taxpayers and voters to commit themselves (and future generations) to provide continuously funds to pamper other countries' profligacy, countries that are anything but 'poor'. Thus, the 'danger' for the Euro currency doesn't come from the drying-up of 'political will' of those who receive the funding (what kind of 'political will' is needed to reach into other people's pockets), but rather that those lose the political will who are let to bleed.. "the scent of panic" - a nice phrase. On the other hand, irregardless of Monti's manoeuvring, Italy's desperate situation with its debt financing is out in the open for all to see anyway, isn't it? No, that'd be too exhausting and would also include extended absences from la mamma, and that's something Italian men generally abhorr;-)... Handing over your credit card to the Italian treasurer and a few assorted friends in the region would do. oh yes it is. Unless you're trying to say it's in north Africa I agree. My original comment was in response to the last sentence of the article,"And the danger for Mr Monti is that markets will catch the scent of panic in his desperate diplomatic manoeuvre. As you pointed out: Italy does not have a insolvency problem but a liquidity problem with its government borrowing. At the rate of above 6% for its 10 year bond yield, the the debt financing situation is desperate. At 7%, the debt basically grows exponentially at a decade interval. Or forget about the math, just intuitively, a debt rate close to 7% means Italy has to have a GDP growth of a comparable rate to just stay equally indebted year on year. No country can afford a borrowing cost around that rate for long. As for how things worked out at the summit, the author worried that Monti's move might have made the situation worse for Italy by showing the market how desperate things were. I disagreed in pointing out that the unsustainable financing problem in Italy was out for all to see anyway, meaning, Mr. Monti lost nothing by giving Ms. Merkel an ultimatum of some sort. The single-handed austerity approach championed by Germany has proved to be a failure: steering the EZ economies into deep contractions, exacerbating north-south capital imbalances, pulling down the global economy. To stop the ongoing rout, some countries have to stand up and fight back for their own economic well-beings, the sooner the better. Italy and Spain did just that at the summit. They took their last stand: either our way or we are out of here. That was a good thing for everyone, literally, everyone, including Germany (they need to be helped from suffering their own medicine as well).
http://www.economist.com/blogs/charlemagne/2012/06/italy-and-euro-crisis?fsrc=gn_ep
CC-MAIN-2014-15
refinedweb
1,969
59.33
Basics of Structure for C Programming You can think of the C programming language structure as a multivariable, or several variables rolled into one. You use structures to store or access complex information. That way, you can keep various int, char, float variables, and even arrays, all in one neat package. Basics of struct A structure isn’t a variable type. Instead, think of it as a frame that holds multiple variable types. In many ways, a structure is similar to a record in a database. For example: Name Age Gambling debt These three items can be fields in a database record, but they can also be members in a structure: Name would be a string; Age, an integer; and Gambling Debt, an unsigned floating-point value. Here’s how such a record would look as a structure in C: struct record { char name[32]; int age; float debt; }; struct is a C language keyword that introduces, defines, or creates a new structure. record is the name of the new structure being created. Within the curly brackets dwell the structure’s members, the variables contained in the named structure. also; } bill, mary, dan, susie;: %sn",bill.name); This statement references the name member in the bill structure variable. A char array, it can be used in your code like any other char array. Other members in the structure variable can be used like their individual counterparts as well: dan.age = 32; How to fill a structure As with other variables, you can assign values to a structure variable when it’s created. You must first define the structure type and then declare a structure variable with its member values preset. Ensure that the preset values match the order and type of members defined in the structure, as shown in Declaring an Initialized Structure. DECLARING AN INITIALIZED STRUCTURE #include <stdio.h> int main() { struct president { char name[40]; int year; }; struct president first = { "George Washington", 1789 }; printf("The first president was %sn",first.name); printf("He was inaugurated in %dn",first.year); return(0); } Exercise 1: Create a new program by typing the source code from Declaring an Initialized Structure into the editor. Build and run. You can also declare a structure and initialize it in one statement: struct president { char name[40]; int year; } first = { "George Washington", 1789 }; Exercise 2: Modify your source code from Exercise 1 so that the structure and variable are declared and initialized as one statement. Though you can declare a structure and initialize a structure variable as just shown, you can get away with that trick only once. You cannot use the technique to declare the second structure variable, which must be done the traditional way, as shown in Declaring an Initialized Structure. Exercise 3: Add another president structure variable, second, to your code, initializing that structure with information about the second president, John Adams, who was inaugurated in 1797. Display the contents of both structures. How to make an array of structures Creating individual structure variables, one after the other, is as boring and wasteful as creating a series of any individual variable type. The solution for multiple structures is the same as for multiple individual variables: an array. A structure array is declared like this: struct scores player[4]; This statement declares an array of scores structures. The array is named player, and it contains four structure variables as its elements. The structures in the array are accessed by using a combination of array and structure notation. For example: player[2].name The variable in the preceding line accesses the name member in the third element in the player structure array. Yes, that’s the third element because the first element would be referenced like this: player[0].name Arrays start numbering with the element 0, not element 1. Line 10 in Arrays of Structures declares an array of four scores structures. The array is named player. Lines 13 through 19 fill each structure in the array. Lines 21 through 27 display each structure’s member values. ARRAYS OF STRUCTURES #include <stdio.h> int main() { struct scores { char name[32]; int score; }; struct scores player[4]; int x; for(x=0;x<4;x++) { printf("Enter player %d: ",x+1); scanf("%s",player[x].name); printf("Enter their score: "); scanf("%d",&player[x].score); } puts("Player Info"); printf("#tNametScoren"); for(x=0;x<4;x++) { printf("%dt%st%5dn", x+1,player[x].name,player[x].score); } return(0); } Exercise 4: Type the source code from Arrays of Structures into your editor. Build and run the program. Try to keep the scores to fewer than five digits so that they line up properly. Exercise 5: Add code to Arrays of Structures so that the display of structures is sorted with the highest score listed first. Yes, you can do this. Sorting an array of structures works just like sorting any other array. Here’s a hint: Line 27 of the solution looks like this: player[a]=player[b]; You can swap structure array elements just as you can swap any array elements. You don’t need to swap the structure variable’s members.
https://www.dummies.com/programming/c/basics-of-structure-for-c-programming/
CC-MAIN-2019-47
refinedweb
860
64.51
I'd like to monitor the distance from the point P and the triangle being tested for intersection, so that I can stop the routine when the distance falls below a certain value. I tried modifying the 0.00001 values in the code thinking that it was meant to be a tolerance value for such collision "distance", but it seems to be ineffective. What do you think? There is a way to do it? Here below is the routine derived from the document above: int rayIntersectsTriangle(vector3_t orig, vector3_t dir, vector3_t v0, vector3_t v1, vector3_t v2) { float a,f,u,v,t; vector3_t e1= v1-v0; vector3_t e2= v2-v0; vector3_t h=dir^e2; a = e1*h; if (a > -0.00001 && a < 0.00001) return(false); f = 1.0/a; vector3_t s=orig-v0; u = f * (s*h); if (u < 0.0 || u > 1.0) return(false); vector3_t q=s^e1; v = f * (dir*q); if (v < 0.0 || u + v > 1.0) return(false); // at this stage we can compute t to find out where the intersection point is on the line t = f * (e2*q); if (t > 0.00001) // ray intersection return(true); else // this means that there is a line intersection // but not a ray intersection return (false); }
http://www.gamedev.net/topic/634396-preventing-collision-detection/
CC-MAIN-2014-42
refinedweb
211
75.4
Archived:Introduction. Foreword This article is a translation of a Portuguese article - Introdução ao Python para S60. Introduction Before getting started with PySymbian, we will familiarize with the actors involved in this tutorial. Python Python is a dynamic programming language that implements several paradigms of development. It is easy to learn and use, created in 1991 by Guido van Rossum. Its name is derived from the humorous British group Monty Python. More information about Python on Python.org S60 (S60) S60 (S60) is a platform for smartphones of Nokia phones that come equipped with the Symbian operating system. Currently there are 3 "editions" of the S60 and in each one a different version of Symbian is used. Within each edition there is still a subdivision of feature packs to distinguish between devices that have certain features (eg Wi-Fi, Bluetooth, camera, etc.).. A complete list of issues, FPs and devices can be found at More information about the S60 in Symbian Symbian is proprietary operating system for mobile devices and charged by a consortium formed by companies like Nokia, Sony / Ericsson and Samsung. Currently Symbian belongs entirely to Nokia and there are rumors that the source code it will be available as Open Source. More information on Nokia Developer Nokia Developer is portal for developers of mobile software for Nokia devices. Here you can find the SDK for developing C++ and Java for S60 and a series of articles, tutorials, examples, tools and resources for developers. PySymbian PySymbian (PySymbian) is a open Source project that is officially supported by Nokia. PySymbian uses the 2.2 version of Python (which is a version considerably older since the former Python is going to version 2.6). The central point of information on the PySymbian is the site of the project inindex.php/Nokia Open Source Installing PySymbian We will describe in this tutorial how to setup the working environment for development in Python using Windows but at the site of PySymbian you can find information on how to develop PySymbian using both Linux and the MacOS X (which is considerably easier than using Windows) . Although, there is an emulator for S60 mobile phones in the SDK C++ from Nokia, it does not implement all the features available in a real device (such as camera, communication via GSM or Bluetooth) so it is strongly recommended to have a real S60 device to accompany this tutorial. Any edits can be used but I recommend any "3rd Edition" device. The phone used to test code in this article is a Nokia N95 device that is a "3rd Edition Feature Pack 1", so if something does not work as described here on your device, make sure that this is not happening because of different version of device/SDK. Installing the SDK / Emulator If you already have a S60 device then installing the SDK is optional. The S60 C++ SDK depends on the installation of Perl on your computer. I recommend the installation of ActiveState ActivePerl because to install it simply run the installer). Install the C++ SDK once you have downloaded it from Nokia Developer. To do this simply decompress the file. From the zip file you just downloaded and run the installer (setup.exe), and follow the instructions. If you did not change the default location of installation, it is likely that you have a directory C:\Symbian on your computer. Now that you've installed the C++ SDK and the emulator on your computer, it's time to download and install PySymbian to the emulator. For this is just down the PythonForS60_1_4_4_SDK_XXX.zip (replacing the XXX version of the SDK you have installed). After you unpack the zip file, just copy its contents in C:\Symbian\XX\S60_3rd_FP1\Epoc32 (or the equivalent directory depending on the version of the SDK you have installed) Now, we already have Python installed for running on the emulator. To run it simply enter the menu option "Start" -> Programs-> S60 Developer Tools-> SDK-> Emulator (be patient because the emulator will it take to get started and running) go on "Installed" and choose "Python ". Installing the phone To install PySymbian on your cellphone you need to download the appropriate version of PySymbian for your cellphone in You'll need to download the two files with the extension SIS: PythonForS60_1_4_4_VERSION.SIS : This package is the interpreter of Python itself. PythonScriptShell_1_4_4_VERSION.SIS : This package provides the "Python" menu and some sample python scripts. Now using the Nokia PC Suite, install these packages on your mobile phone so that the "Python" will appear on your menu of applications: Testing programs PySymbian Now is the last step that needs to be done before we are ready for the development of an application for S60: send a Python script to the device to test. To do this we will do a small program called "ola_mundo.py" (translation note: "Olá mundo!" is the portuguese version of "Hello World!") with the following contents: import appuifw appuifw.note(u"Hello world!","info") To do this script you can use a text editor such as Notepad for Windows (I usually use Notepad++ for this). After you create your small script, you must send it to the C:\Python or E:\Python (in case your phone has a memory card) so we can run it. In the example below I am connecting my phone via USB but that communication can also be done via Bluetooth connection. Note also that you must have the Nokia PC Suite installed so that everything works correctly: Now it is time to Run our first application for S60 Python: Once we begin our program to run it will display a dialog with our text: Now that we know how to do a small PySymbian script, send it to your phone and run it- its time to present a more detailed overview of the features available for the development of Python applications for mobile devices. The modules in PySymbian The limitations of memory and processing power of mobile devices require the mobile developer to take more care with the development of its applications. This is not different when you carry the Python interpreter for the Symbian environment. Small changes in the interpreter make the garbage collector of Python does not make the garbage collection of objects that contain circular references (The reference B that reference A), so it is important to be careful that this type of situation does not occur. Beyond this type of care the developer has to be careful to "turn off" the resources that are not being used and, where possible, for its program "to sleep" because doing this will reduce the processor's clock to cause a considerable saving of battery. Events and callbacks To facilitate the life of the programmer to develop applications that consume few resources modules Python S60 platform for the specific use and abuse of the concept of events and callbacks. This concept is simple: the application is "sleeping" until an event occurs (button pressed, the clock signal, etc.) and shoot a light pre-determined (callback). Functions In addition to the concept of events and callbacks above the modules that come with PySymbian also have several functions that behave in a manner asynchronous, that is, they return before the end of performing his task. In such cases it is quite common for these functions perform a callback function to 'warn' that the task was completed. Specific modules of PySymbian We will talk briefly about the modules of PySymbian from now but for the sake of space we can not get into details about each of them, or even on their functions. For a detailed view of each one of them I recommend a visit to the official documentation of PySymbian can be found at. The specific modules of PySymbian are: E32 This module provides access to specific functions of the Symbian operating system that have no direct relationship with the interface with the user. In this module you will find functions that return the version of PySymbian, if your program is running in the emulator, a list of all available drives and functions and objects that deal with locks, threads, etc.. Sysinfo This module provides functions that return data from the device such as what the profile (general, meeting, silent, ...), the state of battery power, size of screen, free disk space, IMEI, signal strength of the network telephone, type of touch, information on the memory of the device, the firmware version, and so on. Appuifw In this module you will find everything that is related to the graphical interface with the user (GUI). It is one of the most important modules of PySymbian. Graphics Module with functions for manipulating graphic images, drawing from primitive, printing of texts in images, functions for taking screenshots, etc.. This module has full interoperability with the camera modules and appuifw. Camera One of the most interesting of PySymbian modules for its ease of use. This module provides functions to manipulate (s) camera (s) of the cell allowing it to take pictures or videos with them is serious. GLES Library that provides an API compatible with OpenGL/ES for drawing 3D graphics acceleration with (some of the S60 devices have a chip for 3D graphics acceleration). Sensor This module gives access to sensors, acceleration, rotation and tapping (hitting with a finger on the screen of your cell triggers the sensor). Remember that only some models of phones S60 have these sensors. Audio This module allows the manipulation of the total system's audio device. You can manipulate both the self-external speaker (playing an MP3, for example) as the audio of a phone call (play sound in the middle of a conversation or even write it). Telephone Telephony features for making a call or answering to a call are in this module. Messaging This module is responsible for the functions of sending SMS and MMS. inbox, contacts, calendar, inbox, contacts, calendar respectively handle the inbox of messages (SMS/MMS), contacts, calendar and the calendar of events. These modules are extremely powerful. location, positioning Location and Positioning are respectively for obtaining location using data from the GSM network and data from the GPS (internal/external) of the appliance. e32db Mini relational database that allows manipulation using SQL (will be replaced by SQLite in future versions of PySymbian). Socket Module that is bundled with Python and received additions to support connections via Bluetooth. Developing The philosophy of Python says that the language has "batteries included" (batteries included) and that means that the language should always be accompanied by a standard library rather being complete and powerful. PySymbian is not different from standard Python. However in PySymbian we have some modules of the Python standard library (only a portion of the modules patterns) and some more specific libraries for development for S60. Obviously, for reasons of space, we will not describe or use all modules in this tutorial but if you want detailed information about what is available for this platform, I recommend an enormously read in the official documents of PySymbian that can be downloaded at the project site listed on the first part of this tutorial (available in PDF format). To illustrate the development an implementation of PySymbian will use a simple example of an application that takes a picture and send via MMS to a phone number listed. All applications PySymbian can use the skeleton below to be developed (for those who do not yet know Python I recommend reading the tutorial available in the language and): import e32 import appuifw class MinhaApp(object): # define a class MinhaApp def __init__ (self): # Create an object "lock" will "hold" # Our application running self.lock = e32.Ao_lock() def run (self): # Here's our Application # ========================= # ========================= # Assign a so-called "callback" to # The "exit ()" when the user # To choose "Exit" in cell # Note: note that the "exit()" is # Does not have the brackets because the function # Is not implemented immediately appuifw.app.exit_key_handler = self.leaves() # Awaiting safe until the execution # "Hangs" receives a signal self.lock.wait() def leaves (self): # Sends the signal to "lock" self.lock.signal() if __name__ == '__main__': application = MinhaApp() application.execute() This application does nothing interesting yet it is presents the basic skeleton. The only thing it does is organize a class "MinhaApp" which implements the method. "Run()" where program the option of "Exit" the application using a "ActiveObject Lock". The "brake" is needed because the applications are developed in the universe Symbian to work in asynchronous model, i.e. the functions return immediately after being called even before they have completed their tasks. Many features of PySymbian are also implemented using the callback model, i.e. the developer combines the functions and events when these events occur the appropriate function is called. In our case the method "Exit()" runs whenever an event is triggered exit_key and this event is triggered when the right soft key is pressed. Connecting the camera One of the most interesting modules that accompanies the PySymbian is the "camera". PySymbian can easily trigger the camera from of the device, take pictures, manipulate the picture, record it on the memory card, send it to other phones and so on. To take a picture with the camera just run the commands: import camera photo = camera.take_photo() The function "Take_photo()" module of the "camera" will return an object of type "Image" containing the image to be captured/photographed. To record the image on the memory card simply call the method. "Save()" this object (note that the character "\" needs to be doubled in the path): photo.save ( "E:\\Images\\minha_foto.jpg") As you can see, it is very simple to capture an image in Python but it has an inconvenience: the photo is taken so that the function camera.take_photo () is called but what is being photographed does not appear on the screen of your cell phone, then, you do not see what is being photographed. To see what the camera will shoot you need to trigger the camera's view finder (and close it immediately before taking the picture). Let us return to our "skeleton" of application and add a little more code to it: : import appuifw import camera : class MinhaApp(object): def __init__(self): : # Let's create a Canvas object. # Canvas object allows the display # Of images. self.canvas = appuifw.Canvas() def desenha_tela(self, imagem): self.canvas.blit(imagem) def run(self): # Define the title of the application # The "u" before the string says # She is in Unicode format appuifw.app.title = u"PyFoto" # Let's define that the body of the application # Canvas is the object created above. appuifw.app.body = self.canvas # Started the "view finder" that will # The image captured by the finder in Canvas camera.start_finder(self.desenha_tela) : def leaves(self): # Off the view finder camera.stop_finder() : Running the script, we get the following screen: Now let's add an option "Take picture" to our menu options. This is extremely simple to do ... let's go back to our code and add the following sentence: : class MinhaApp(object): : def take_pic(self): # Turn off the view finder camera.stop_finder() # Take a picture and write in # E:\Images\foto.jpg foto = camera.take_photo() foto.save("E:\\Images\\foto.jpg") #start the view finder camera.start_finder(self.function) def execute(self): : #... after the call camera.start_finder () # Create a "Take picture" on the menu # Options of cellular calls that the method # self.take_pic() when triggered appuifw.app.menu = [(u "Take picture," self.take_pic)] : Now you can take a picture that will be recorded in the file E:\Images\foto.jpg (for future send it via MMS): Do not be alarmed if the application to get a white screen for a few seconds because it is the time required for the serious Python the picture just taken. : import messaging class MinhaApp(object): : def take_pic(self): : # ... Soon after photo.save (...) # The number of phone calls Phone_number = appuifw.query(u"number of phone", "text") # Check if the number was informed and sends message if Phone_number: messaging.mms_send(messaging.mms_send(Phone_number,u"Photo taken by PyFoto","E:\\Images\\foto.jpg") As soon as we run our application and take a picture we can select the recipient's phone number and see the message delivered after (careful to test the sending of MMS since this will incur charge): Obviously we can improve many aspects of our application for example: - Reducing the size of the image before sending it to save money - Search the phone number of our list of contacts - Rotate the screen to make better use of space for the view finder - Add other options for sending (Flickr, Bluetooth, ...) But it is as an exercise for the reader. See Also - Introdução ao Python para S60 - Portuguese version of this article - PySymbian Code Examples - PySymbian Any comments are welcome here :-) croozeus 04:03, 26 November 2008 (EET) 03 Sep 2009.
http://developer.nokia.com/community/wiki/Introduction_to_PySymbian
CC-MAIN-2014-15
refinedweb
2,814
51.07
CodeGuru Forums > Visual C++ & C++ Programming > C++ (Non Visual C++ Issues) > assignment operator for an static array inside a class PDA Click to See Complete Forum and Search --> : assignment operator for an static array inside a class acosgaya July 27th, 2008, 10:54 AM Hi I have the following code (shown below) which is a class brt_node with 3 members, one of them being an static array called "buffer", the elements of this buffer are pairs (int, CDataType), the CDataType is also shown. I have created my own copy constructors and assignment operators, so that when I do something like the in following lines, I don't have to copy all the buffer, but only the part I am interested in, and given by the function get_buffer_size() brt_node x; //... do something with x brt_node n = x; // copy constructor brt_node y; y = n; // assignment operator I know that executing the lines above will work (without my own copy constructor and assigment operator), c++ takes care of it, but is very slow (I don't need to have the whole buffer copied); The copy constructor and assigment operator I have defined, do not seem to work properly (segmentation fault sometimes); Btw, the array has to be static, don't want a dynamic array in this specific case. I would appreciate some help fixing it. Thanks in advance. class CDataType{ public: // constructors: CDataType(): vertex(0), number(0){} CDataType(const unsigned int &_v, const cases &_status = unexplored, const unsigned int &_number = 0): vertex(_v), number(_number){} const CDataType &operator=(const CDataType &e) { if ( &e != this){ this->vertex = e.vertex; this->number = e.number; return (*this); } } // -- attributes unsigned int vertex; unsigned int number; }; // -- type of each record stored in the brt_node's buffer typedef std::pair<unsigned int, CDataType> value_type; class brt_node { public: // constructors brt_node(): left(0), two_children(false) { buffer[0] = value_type(0, CDataType(0) ); }; brt_node(const value_type &_key_pair): left(0), two_children(false) { buffer[0] = _key_pair; } brt_node(const unsigned &_key): left(0), two_children(false) { buffer[0] = value_type(_key, CDataType(0) ); } // copy constructor brt_node(const brt_node &_n): left(_n.get_leftChildPos()), two_children(_n.has_2_children()) { std::copy(_n.buffer, _n.buffer+_n.get_buffer_size()+1,buffer); } // functions KeyType get_key() const { return buffer[0].first; } void set_key(const KeyType &_key) { buffer[0] = value_type(_key, CDataType(0)); } KeyType get_buffer_size() const { return buffer[0].second.vertex; } void set_buffer_size(const unsigned int &size) { buffer[0].second.vertex = size; } bool has_2_children() const { return two_children; } void set_has_2_children(const bool &_two_children) { two_children = _two_children; } unsigned int get_leftChildPos() const { return left; } void set_leftChildPos(const unsigned &_index) { left = _index; } // -- object assignment operator const brt_node &operator=(const brt_node &n) { if ( &n != this){ left = n.get_leftChildPos(); two_children = n.has_2_children(); std::copy(n.buffer, n.buffer+n.get_buffer_size()+1, buffer); return (*this); } } value_type buffer[BUFFER_SIZE]; private: unsigned int left; bool two_children; }; Paul McKenzie July 27th, 2008, 11:04 AM Hi I have the following code (shown below) which is a class brt_node with 3 members, one of them being an static array called "buffer", the elements of this buffer are pairs (int, CDataType), the CDataType is also shown.Your CDataType does not need a user-defined copy constructor or assignment operator. Both members are unsigned int's, and they are copyable using the compiler default version of these functions. Do not introduce copy and assignment operators for no reason. What ends up happening many times is that you now have to maintain any new member variable that's added to the CDataType class, making sure that you copy them and assign them. By using the compiler default, you let the compiler handle these things, not user code. The only times when you need to define a user-defined copy and assignment are one or more of the following: 1) Your class contains members that are pointers to dynamically allocated memory. 2) Your class contains members that are references. 3) Your class is derived from another class that has turned off copying and assignment. 4) Your class contains members that represent resources that shouldn't be blindly copied (i.e. file handles, printer handles, etc.). 5) Your class is implementing a reference-counting scheme to track copies (similar to various copy-on-write string classes). Otherwise, the compiler default is perfectly fine and should be used. Edit: Added fifth item: Regards, Paul McKenzie Paul McKenzie July 27th, 2008, 11:11 AM In addition, I don't see a reason for your brtnode class for having a user-defined copy constructor and assignment operator. None of what you've shown needs any of that code you've written. I have created my own copy constructors and assignment operators, so that when I do something like the in following lines, I don't have to copy all the buffer,Why? When a copy is made, it's supposed to represent an exact copy, not a mutation of that copy. Writing code to produce "fake" copies will lead to hard to find bugs and a whole host of maintenance to make it work right. The only exception is if you're creating a reference counting scheme (That should have been the fifth item in my last post, which I forgot to mention). Otherwise, you're just asking for trouble. If you removed all of that code to copy and assignment, does your program work? It should, as all you have are int's, bools, and maps (I see no pointers). Regards, Paul McKenzie acosgaya July 27th, 2008, 11:24 AM thanks for the reply, yeah it works without the constructor and operator, the problem comes when I defined my own. In this specific case when letting the compiler takes care of it is very slow (copies the whole buffer, even if I don't need all). If I declare a variable, say brt_node x, n; //... do something with x n = x; // I don't need all the buffer copied, just some elements if I do something like std::copy(x, x+x.get_buffer_size(), n); // x.get_buffer_size() might be less than the original buffer_size is faster than the direct assignment n = x (of course I also have to copy the other two variables) I want that behavior in order to speed it up, because I will be doing this assignment a lot; thanks Paul McKenzie July 27th, 2008, 11:41 AM thanks for the reply, yeah it works without the constructor and operator,OK. So let's stay with this. the problem comes when I defined my own. In this specific case when letting the compiler takes care of it is very slow (copies the whole buffer, even if I don't need all).That is very hard to believe that copying an array is so slow. Arrays being copied are usually just a memset() internally. I would not be surprised if your code is even slower than what a compiler would do. Add to that, why did you code a user-defined copy ctor and assignment operator for CDataType? There was absolutely no reason to do so in that case, as all it has are two int members. You need to show proof of this slowness, as others will more than likely disprove your claims. Also, you need to run profiling tests to make sure you are not wasting your time optimizing something that makes no difference. You also need to specify which compiler, version, etc. and whether you are testing an optimized version, or a non-optimized (i.e. "debug" ) version. You never time debug versions, which is why you need to provide more information. Bottom line is that there is no need for all of this code, unless you have evidence of what you're doing. In the industry, your code would be rejected without evidence of having to write it, especially if your code works without all of this extra baggage and maintenance. Regards, Paul McKenzie Paul McKenzie July 27th, 2008, 11:56 AM I don't need all the buffer copied, just some elements Then IMO, this is an abuse as to what a copy is supposed to be. If you're not copying all of the elements, or at the very least, effectively making a copy, then it isn't a copy. In other words, after your copy, this relationship must be true: SomeObject a; SomeObiect b = a; SomeObject c; c = a; //... if ( a == b ) { if ( b == c ) { if ( a == c ) { // copy is a true copy } } } The if()'s are theoretical in nature. If the objects are not equivalent to each other, then they are not copies. For the rest of the program, whether I specify using an "a", "b", or "c" object should make no difference. If the program behaves any differently if I specify an a, b, or c, then an a is not b is not c, and your copies are not copies. If anything, another function should be provided, and not use the assignment operators and copy constructor for this.. Regards, Paul McKenzie acosgaya July 27th, 2008, 12:02 PM you are right, it isn't really an exact copy, ... I should wrap the desired behavior in function that does copy only the part I want. I guess I wanted a shortcut, but it isn't gonna work that way. thanks codeguru.com
http://forums.codeguru.com/archive/index.php/t-458089.html
crawl-003
refinedweb
1,536
59.13
Using TAO and OpenDDS with .NET, Part 1 by Charles Calkins, Senior Software Engineer January 2009 Introduction A major advantage of TAO and OpenDDS, open-source implementations of the Object Management Group's CORBA and the Data Distribution Service, is the wide variety of platforms to which they have been ported. While retaining platform neutrality is a worthy goal, the dominance of Microsoft Windows in the PC marketplace, over 90% [1] market share as of the writing of this article, encourages the use of Windows-specific features when developing for that platform. Since the release of Visual Studio.NET in 2002, Microsoft's direction for development has been that of the .NET Framework [2]. In a manner similar to Java bytecode, high-level languages are compiled into an assembly-like intermediate language, standardized as the Common Language Infrastructure by Ecma International in ECMA-335 [3], which is then ultimately compiled and run on the target machine. Although special languages such as C# have been created for .NET development, C++ has the ability to use the .NET Framework as well. How well-integrated C++ code is with the .NET Framework, though, is dependent upon how many code changes are made to conform to the new C++/CLI syntax. As TAO and OpenDDS are written in standard C++, this article series will show how they can be adapted to be used in a .NET application. Application Overview. Having a single process interact with the database on behalf of clients, instead of allowing each client direct access to the database, ensures that no database change can be made without the system, as a whole, becoming aware of it. Additionally, abstracting the details of the database access from the clients allows the database process be moved to other hosts, or even be implemented on a different platform, without requiring more than just a reference to the new location of the database process to be changed in the configuration of the clients — no client code changes would be necessary.. The existing legacy application interacts with a database via ADO.NET [4], a series of classes provided by the .NET Framework, which provide a uniform means of accessing various data source types. The code that uses ADO.NET is in a library, written in C#. The main application that uses this library is written in C++. In order to solve the problem outlined above, the following architecture was designed. In this diagram, components written in C# shown with box hatching and components written in C++ shown with angled hatching. The separate application to manage the database, called the DataServer, was written. This application, in C++, uses the same C# library as before. It now, however, acts as a CORBA server, processing requests from clients to perform database operations. As operations are performed, the DataServer publishes a DDS data sample to clients to notify them of the results of the operation. DDS is used instead of the CORBA Notification Service for notifications as DDS samples are strongly typed (rather than being the CORBA Any type), plus DDS provides quality-of-service policies that the Notification Service does not. This article describes the core elements of the DataServer, as well as a client application, written in C#, that makes use of it. The client performs CORBA operation invocations, and subscribes to the DDS data samples. This article will also illustrate the use of MPC for project maintenance. DataLib The core functionality of the Data Server is provided by DataLib, a library written in C# which interacts with the database. For this example, we'll use System.Data.SQLite, a public domain SQLite ADO.NET provider. DataLib consists of a single file, DataLib.cs, containing a single class named Database, and referencing several .NET libraries as well as System.Data.SQLite. The structure of the Database class is below. Methods are provided to open and close the database, where, for simplicity, a single database connection is used. Additional methods are provided to create, read, update and delete records in an item table, where an item has both an autogenerated numeric ID and a description. For the implementation of these methods, please see the code archive that accompanies this article. - namespace DataLib - { - using System; - using System.Data; - using System.Data.SQLite; - - public class Database - { - // open and close the database connection - public bool Open() - public void Close() - - // create a new item, and return the autogenerated ID - public bool CreateItem(string description, out Int64 id) - - // read the description from a specific item, given the item ID - public bool ReadItem(Int64 id, out string description) - - // update the description of an item given its ID - public bool UpdateItem(Int64 id, string description) - - // delete an item, given its ID - public bool DeleteItem(Int64 id) - } - } DataLib Project Creation Although the DataLib project can be created from within Visual Studio, using MPC (the Makefile, Project, and Workspace Creator) provides a number of benefits: - Different versions of Visual Studio can be supported with one set of project description files. Conversion of solution and project files between versions of Visual Studio is not necessary. - MPC project description ( .mpc) files can inherit from base project ( .mpb) files, allowing settings such as output directory specification or the setting of a warning level to be made in one place and applied across all projects. If these settings were changed within Visual Studio, changes would have to be made over and over again, once for each project in the solution. - Comments are supported in the project description files, allowing the rationale behind the various settings to be documented. - Often, the default settings for projects can be used without needing to change them, making project descriptions simple. Documentation for MPC can be found here, though we will describe features of MPC that are useful for this application. As this system will consist of several projects, we create a base project to allow settings that all projects should inherit. We also set an environment variable, DATASERVER_ROOT, to represent the top-level directory of the project. This allows us to move the entire source tree while correctly maintaining any full paths used in the project files. The base of all projects in the workspace is named DataServerBase.mpb, and has the following contents: - // DataServerBase.mpb - project { - specific { - Release::install = $(DATASERVER_ROOT)/Output/Release - Debug::install = $(DATASERVER_ROOT)/Output/Debug - - warning_level = 4 - } - } When generating projects for Visual Studio, it is important to remember that the variables set in the MPC or MPB file reflect ones set in the Visual Studio IDE. Generally, settings which correspond to strings are set directly in the MPC or MPB file, but those that represent dropdowns are set by the numeric index of the choice of interest in the dropdown. In this case, output directories are specified by name, but the warning level is set numerically to 4, which represents the choice of /W4 in the IDE. As this project will contain different types of projects, written in different languages, it is useful to define base projects which apply to subsets of projects in the workspace. The contents of the file CSBase follows, the base for all C# projects. - // CSBase.mpb - project : DataServerBase { - specific { - // to avoid "Load of property 'ReferencePath' failed. Cannot - // add '.' as a reference path as it is relative. Please specify - // an absolute path." on C# project load into the IDE - libpaths -= . - } - } By default, MPC adds the current directory to the list of directories where libraries are found, though Visual Studio will generate a warning if the directory is not an absolute path. The entry above removes the current directory from the library paths. This project inherits from DataServerBase, so settings that are made in DataServerBase are applied in addition to what is in this file. Finally, an MPC file is needed for the project itself. DataLib.mpc is as follows: - // DataLib.mpc - project : CSBase { - // To remove the warning "Load of property 'ReferencePath' failed. - // Cannot add '..\lib' as a reference path as it is relative. Please - // specify an absolute path." - expand(DATASERVER_ROOT) { - $DATASERVER_ROOT - } - - lit_libs += System System.Data System.Xml - lit_libs += System.Data.SQLite - libpaths += $(DATASERVER_ROOT)\lib - } The expand option causes the environment variable to be treated as an absolute path — by default, MPC converts environment variables to relative paths. As with the previous issue with libpaths, this also prevents a warning in Visual Studio from being generated when the lib subdirectory is added. As this is a .NET application, references to various .NET assemblies must be provided, in addition to the System.Data.SQLite assembly, which provides the database connectivity. For this example, System.Data.SQLite.dll is located in the lib subdirectory off of the main project directory, and the libpaths entry adds that directory to the library path. This project inherits from CSBase, so has all of the settings supplied by CSBase.mpb and DataServerBase.mpb. It is interesting to note what does not need to be specified. As this is an MPC file for a C# project, you do not need to provide specific names of .cs files — all .cs files in the same directory as the MPC file are automatically included. Also, you do not need to specify a file name for the output — in this instance, MPC will use the base name of the MPC file, which is what we want. With the project file created, the last step is to create a workspace ( .mwc) file, which corresponds to the contents of the Visual Studio solution ( .sln) file. DataServer.mwc, located in the project root, looks like this: - // DataServer.mwc - workspace { - specific { - cmdline += -language csharp - DataLib - } - } For this project, DataLib.cs and DataLib.mpc are in a subdirectory named DataLib, off of the root. The workspace file specifies that the DataLib subdirectory is to be searched for MPC files, and that any MPC files found there should be treated as describing C# projects. Running MPC on the MWC file generates the solution file. The solution file can then be opened in Visual Studio, the DataLib project compiled, and the DataLib assembly built. As this code was developed using Visual Studio 2005 (VC8), we can generate the solution file by executing: - %ACE_ROOT%\bin\mwc.pl -type vc8 DataServer.mwc from a console prompt set to the project's root directory. Interface Definition Language (IDL) Now that the library for data access has been developed, we can write a CORBA server which uses that library. We wish to expose the functionality of the library as a CORBA object, so an interface, described in IDL, must be created. In a subdirectory named IDL off of the root, we create a file, Database.idl, which contains that interface. - // Database.idl - interface Database - { - boolean CreateItem(in wstring description, out long long id); - boolean ReadItem(in long long id, out wstring description); - boolean UpdateItem(in long long id, in wstring description); - boolean DeleteItem(in long long id); - }; The operations of the interface correspond to the client-accessible methods of DataLib::Database, the class defined in DataLib. The IDL types that are used in the interface correspond to the types used in C#. In particular, strings in .NET are in Unicode, so wstring is used to pass them, and as database IDs are 64-bit, long long is needed. In the IDL subdirectory, create the file IDL.mpc to allow the file to be compiled by the TAO IDL compiler. - // IDL.mpc - project : taoidldefaults { - IDL_Files { - Database.idl - } - custom_only = 1 - } Inheriting from the taoidldefaults base project, a base project included in the TAO distribution, provides the needed infrastructure. We only need to list the IDL file in the IDL_Files section, and MPC generates the tao_idl compilation commands. We do need to indicate that the project has no executable output via the custom_only flag, however. For this project to be added to the solution file, the workspace file, DataServer.mwc, must be modified to include the IDL directory. After the addition, DataServer.mwc looks like this: - // DataServer.mwc - workspace { - specific { - cmdline += -language csharp - DataLib - } - IDL - } The IDL project is not in C#, so the IDL directory is listed outside of the specific section. The compilation of this project produces the client stub and server skeleton files, DatabaseC.[cpp,h,inl] and DatabaseS.[cpp,h,inl], respectively. Database Implementation With the database interface defined, we can create a C++ class that which implements the interface. We create a subdirectory off of the root named DataServer, and two files in that subdirectory, Database_i.h and Database_i.cpp. The files as presented here were based off of generated implementation files via the -GI option to tao_idl and modified accordingly. Amendments to the generated code are noted here — please see the code archive associated with this article for the full file listings. These files define class Database_i, an implementation of the Database CORBA interface. An instance of this implementation is called a servant. As we would like the instance of the DataLib::Database class to be maintained by the server itself, we must be able to pass a reference to it to the servant. As DataLib::Database is a .NET class and Database_i is not (as it is a standard, unmanaged C++ class), a reference to the DataLib::Database object must be stored using gcroot<>, a templated helper class provided by the vcclr.h header file. We must add #include to the top of Database_i.h, and add a class member variable to class Database_i to store the .NET reference (indicated by the caret) to DataLib::Database. - // Database_i.h - class Database_i - : public virtual POA_Database - { - gcroot<DataLib::Database^> database_; - ... This variable is initialized by the Database_i constructor. - // Database_i.h - Database_i(gcroot<DataLib::Database^> database); - // Database_i.cpp - Database_i::Database_i(gcroot<DataLib::Database^> database) : - database_(database) - { - } In the methods of Database_i, we use the database_ member variable to reference the DataLib::Database object, such as in the implementation of CreateItem(). - // Database_i.cpp - ::CORBA::Boolean Database_i::CreateItem( - const ::CORBA::WChar * description, - ::CORBA::LongLong_out id) - { - System::String^ netDescription = gcnew System::String(description); - ::CORBA::Boolean result = database_->CreateItem(netDescription, id); - delete netDescription; - return result; - } Implementation of the CORBA Database interface is essentially a translation between CORBA and .NET. In this method, a string provided by CORBA is converted to a .NET String before being passed to DataLib::Database::CreateItem(). The code above also illustrates a benefit of C++/CLI. The variable netDescription is allocated on the garbage-collected heap via gcnew. It can still be determininstically freed, however, by a call to delete, as if it was an allocation made by new on the unmanaged heap. However, if an exception is thrown by the invocation of CreateItem() and delete is not called, netDescription will still be freed by the garbage collector when it executes at some point in the future. The implementation of ReadItem() also involves string translation, but this time from .NET to CORBA. - // Database_i.cpp - ::CORBA::Boolean Database_i::ReadItem ( - ::CORBA::LongLong id, - ::CORBA::WString_out description) - { - System::String^ netDescription; - ::CORBA::Boolean result = database_->ReadItem(id, netDescription); - if (result) { - pin_ptr<const wchar_t> s = PtrToStringChars(netDescription); - description = s; - } - return result; - } The pin_ptr<> template and PtrToStringChars() function are two more Visual Studio-provided helpers to assist in dealing with .NET types in standard C++. PtrToStringChars() provides a means to directly address .NET String contents, and, as .NET strings are in Unicode, the contents are represented as an array of wchar_t. As the .NET String is on the garbage-collected heap, pin_ptr<> is used to keep the string contents from being relocated until access to it is complete. It must remain accessible until the skeleton marshals it into the GIOP reply. The implementation of UpdateItem() and DeleteItem() are analagous to the above. DataServer With the completion of the servant, we can now implement the DataServer itself. In the file DataServer.cpp, the main() function of DataServer begins as most simple CORBA servers do. - // DataServer.cpp - int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { - try { - // initialize the ORB - CORBA::ORB_var orb = CORBA::ORB_init(argc, argv); - - // get a reference to the RootPOA - CORBA::Object_var obj = - orb->resolve_initial_references("RootPOA"); - PortableServer::POA_var poa = - PortableServer::POA::_narrow(obj.in()); - - // activate the POAManager - PortableServer::POAManager_var mgr = poa->the_POAManager(); - mgr->activate(); To create the servant, we first create an object of type DataLib::Database, open the database connection, and pass a reference to the object to the servant's constructor. In this instance, the percent sign in .NET acts somewhat like an ampersand does in standard C++ — it provides a reference to an object. - // open the database - DataLib::Database database; - if (!database.Open()) - throw std::exception("Cannot open the database"); - - // create the Database servant - Database_i servant(%database); - PortableServer::ObjectId_var oid = - poa->activate_object(&servant); - CORBA::Object_var database_obj = poa->id_to_reference(oid.in()); There are a number of ways to provide the IOR of an object to callers, such as via a file or via the Naming Service. For this application, we use the IORTable, a TAO-specific feature which allows a client to find a server via a corbaloc URL. - CORBA::String_var ior_str = - orb->object_to_string(database_obj.in()); - CORBA::Object_var tobj = - orb->resolve_initial_references("IORTable"); - IORTable::Table_var table = IORTable::Table::_narrow(tobj.in()); - table->bind("DataServer", ior_str.in()); - std::cout << "DataServer bound to IORTable" << std::endl; main() ends by calling run() on the ORB instance, and by providing cleanup and error reporting. - // accept requests from clients - orb->run(); - orb->destroy(); - } - catch (CORBA::Exception& ex) { - std::cerr << "CORBA exception: " << ex << std::endl; - } - catch (std::exception& ex) { - std::cerr << "Exception: " << ex.what() << std::endl; - } - - return 0; - } We next create an MPC file for the DataServer. It is slightly more complicated than previous MPC files. - // DataServer.mpc - project : taoserver, CPPBase, iortable { - after += IDL - after += DataLib - - includes += ../IDL - Source_Files { - Database_i.cpp - DataServer.cpp - ../IDL/DatabaseC.cpp - ../IDL/DatabaseS.cpp - } - - managed = 1 - } In the same way that the IDL project inherits from the taoidldefaults base project to derive behavior, TAO provides other base projects which allow features of TAO to be easily referenced by an application — these base projects set include paths, library linkages, preprocessor symbols and other configuration options so the user of TAO does not have to. As DataServer is an application that uses server components of TAO, it inherits from taoserver. It uses the IORTable, so it inherits from iortable as well — if it had used Naming Service functionality, it would have inherited from naming. We desire it to have the same attributes as other C++ applications in the solution, so it also inherits from CPPBase. The after statements ensure that the IDL and DataLib projects are built prior to this one. As source code files are not all located in the same directory as the MPC file, we must specify them explicitly via the includes statement and the Source_Files section. Finally, the /clr compiler option must be set to allow .NET functionality to be directly used in C++ code, so managed = 1 is specified. This project must also be added to the workspace, leading to a DataServer.mwc that looks like this: - // DataServer.mwc - workspace { - specific { - cmdline += -language csharp - DataLib - } - IDL - DataServer - } We then regenerate the solution file using MPC, rebuild, and now have a working server. SIDEBAR As discussed in references [5] and [6], incomplete types will generate linker warning LNK4248 when compiled with /clr, and is seen with many types in TAO. For example: warning LNK4248: unresolved typeref token (01000016) for 'TAO_ORB_Core'; image may not run The actual type that will be used is defined in TAO itself, which is not compiled with /clr. In practice, this warning is harmless, though defining the symbol with an empty body in the module that generates the warning will suppress the message. Please see the file LNK4248.h in the code archive for an approach to this issue. DataServerConnectorLib With the server side complete, we can begin development of the client. The DataServerConnectorLib library acts as a client of the DataServer. More specifically, the class DataServerConnector in this library makes the client-side CORBA calls to invoke methods on the server. Although this class is implemented in C++ to make use of TAO, this class is a fully-fledged .NET type, so it can be used by the Client application which is written in C#. For future convenience, the method Run() of this class is executed in a .NET thread to allow an ORB to continue execution independent of the code that uses DataServerConnector, and the Start() and Shutdown() methods manage this thread. The other public methods of this class mirror the CORBA Database interface, in appropriate .NET syntax. We start by creating the file DataServerConnectorLib.h in the DataServerConnectorLib subdirectory off of the root, and add the following class definitions: - using namespace System; - using namespace System::Threading; - - class DataServerConnectorState { - CORBA::ORB_var orb_; - Database_var database_; - public: - DataServerConnectorState(CORBA::ORB_ptr orb, Database_ptr database); - Database_ptr DatabasePtr() { return database_; } - CORBA::ORB_ptr OrbPtr() { return orb_; } - }; - - public ref class DataServerConnector { - DataServerConnectorState *state_; - Thread^ thread_; - AutoResetEvent startupEvent_; - void Run(); - static void ThreadStart(Object^ param); - public: - DataServerConnector(); - ~DataServerConnector(); - void Start(); - void Shutdown(); - bool CreateItem(String ^description, Int64 %id); - bool ReadItem(Int64 id, String^% description); - bool UpdateItem(Int64 id, String^ description); - bool DeleteItem(Int64 id); - }; The using statements allow us to use types from various .NET assemblies without needing to specify the fully qualified names, such as Thread instead of System::Threading::Thread. The DataServerConnector class is declared as a public ref class. The public keyword indicates that the class is visible outside of the assembly; __declspec(dllexport) is not used with .NET types, as it would be with standard Windows dynamic link libraries to export symbols. The ref keyword indicates that the class is a garbage-collected .NET type, and not an unmanaged, standard C++ class. DataServerConnectorState is, however, an unmanaged, standard C++ class. Unmanaged types (such as CORBA::ORB_var) cannot be member variables of a .NET class, but pointers to unmanaged types can be. DataServerConnectorState acts as a container for the unmanaged state of DataServerConnector. The implementation of DataServerConnectorState is straightforward — it stores ORB and servant pointers for later use. It resides, with the implementation of DataServerConnector, in the file DataServerConnectorLib.cpp. - // DataServerConnectorLib.cpp - DataServerConnectorState::DataServerConnectorState(CORBA::ORB_ptr orb, - Database_ptr database) { - orb_ = CORBA::ORB::_duplicate(orb); - database_ = Database::_duplicate(database); - } The Run() method contains the CORBA client implementation. Because ORB_init() requires C-style argc and argv, they must be constructed from the .NET command-line argument array, so we begin by performing that conversion, and then initialize the ORB. - // DataServerConnectorLib.cpp - void DataServerConnector::Run() { - int argc = 0; - wchar_t **argv = NULL; - - try { - // convert .NET arguments to standard argc/argv - array<String^>^ arguments = Environment::GetCommandLineArgs(); - argc = arguments->Length; - argv = new wchar_t *[argc]; - for (int i=0; i<argc; i++) { - pin_ptr<const wchar_t> arg = PtrToStringChars(arguments[i]); - argv[i] = _wcsdup(arg); - } - - CORBA::ORB_var orb = CORBA::ORB_init(argc, argv); We now obtain an object reference to the Database object. Because the server registered the object in the IORTable, the client can locate it by passing -ORBInitRef DataServer= corbaloc:iiop:server_hostname:server_port/DataServer on its command line, and calling resolve_initial_references(). - // obtain the reference - CORBA::Object_var database_obj = - orb->resolve_initial_references("DataServer"); - if (CORBA::is_nil(database_obj.in())) - throw std::exception("Could not get the Database IOR"); - - // narrow the IOR to a Database object reference. - Database_var database = Database::_narrow(database_obj.in()); - if (CORBA::is_nil(database.in())) - throw - std::exception("IOR was not a Database object reference"); We now store references to the ORB and Database object for later use, run the ORB to process any requests, and perform cleanup on error. DataConnectorException, a subclass of the .NET Exception class, is defined to wrap and re-throw any exceptions that are generated. This allows native exceptions, such as CORBA::Exception to be propagated to the .NET world. - // save the references via a pointer to an unmanaged class - state_ = new DataServerConnectorState(orb, database); - - // good to go - tell the outside world - startupEvent_.Set(); - - // run the ORB - orb->run(); - orb->destroy(); - } - catch (CORBA::Exception& ex) { - std::stringstream ss; - ss << "Exception: " << ex; - throw - gcnew DataConnectorException(gcnew String(ss.str().c_str())); - } - catch (std::exception& ex) { - std::stringstream ss; - ss << "Exception: " << ex.what(); - throw - gcnew DataConnectorException(gcnew String(ss.str().c_str())); - } - } We must also implement methods that wrap the CORBA method invocations. As translation was performed in the DataServer, we do the same, but in reverse — from .NET to CORBA. For example, CreateItem() is defined below. The .NET string is converted to a CORBA::WString via the PtrToStringChars()/pin_ptr<> combination we have used before. The CORBA::LongLong used to store the out parameter from the CreateItem() CORBA interface method is converted to a .NET Int64 to be returned to the caller. Note that the percent sign in the argument list, in this usage, acts as an out parameter. As with Run(), exceptions are propagated as the DataConnectorException type. The other wrapper methods are analagous. - // DataServerConnectorLib.cpp - bool DataServerConnector::CreateItem(String ^description, Int64 %id) { - try { - pin_ptr<const wchar_t> cppDescription = - PtrToStringChars(description); - CORBA::WString_var desc = CORBA::wstring_dup(cppDescription); - CORBA::LongLong cid; - CORBA::Boolean result = - state_->DatabasePtr()->CreateItem(desc, cid); - id = cid; - return result; - } catch (CORBA::Exception& ex) { - std::stringstream ss; - ss << "Exception: " << ex; - throw - gcnew DataConnectorException(gcnew String(ss.str().c_str())); - } - } After the .NET thread management methods are added, development of the DataServerConnectorLib is complete. We now create an MPC file for it. The options specified are similar to those used in DataServer.mpc. - // DataServerConnectorLib.mpc - project : taoexe, CPPBase { - after += IDL - includes += ../IDL - - Source_Files { - DataServerConnectorLib.cpp - ../IDL/DatabaseC.cpp - } - - managed = 1 - } We also add it to DataServer.mwc. - // DataServer.mwc - workspace { - specific { - cmdline += -language csharp - DataLib - } - IDL - DataServer - DataServerConnectorLib - } Regenerating the solution with MPC and recompiling yields a working DataServerConnectorLib. Client The last module we will create is a GUI in C# to demonstrate the system. The GUI consists of a ListView to display messages, and a series of Buttons and TextBoxes to exercise the database methods. Please refer to the code archive for details of the GUI itself. The implementation of the button click methods invoke the corresponding database functions — the methods exposed by the DataServerConnector class. User input into the TextBoxes associated with each button is used, as appropriate. For instance, the click handler for the Create button is as follows: - private void bCreate_Click(object sender, EventArgs e) - { - try - { - // if input is blank, do nothing, else create the item - if (String.IsNullOrEmpty(tCreateDesc.Text)) - return; - - // invoke the method - long id = 0; - if (dataConnector_.CreateItem(tCreateDesc.Text, ref id)) - Log("Item '" + tCreateDesc.Text + "' created with id " + id); - else - Log("Item '" + tCreateDesc.Text + "' could not be created"); - } - catch (DataConnectorException ex) - { - Log(ex.Message); - } - - // after completion (or failure) clear the input - tCreateDesc.Text = ""; - } In this method, tCreateDesc is the TextBox associated with the Create button. If the user has entered text, it will be used as the item description of the item to be created. The call to DataServerConnector::CreateItem() invokes the CORBA method, the ID of the created item is returned (the ref in C# corresponds to the % in C++ in the argument list of DataServerConnector::CreateItem()), and displayed to the user in the ListView via the call to Log(). The other methods are implemented similarly. With the code complete, we create an MPC file for the Client project, as follows: - // Client.mpc - project : CSBase { - exename = Client - - after += DataServerConnectorLib - - specific { - winapp = true - } - - Source_Files { - *.cs - *.Designer.cs - } - - Source_Files { - subtype = Form - Client.cs - } - - Resx_Files { - generates_source = 1 - subtype = Designer - Properties/Resources.resx - } - - lit_libs += System System.Data System.Xml - lit_libs += System.Drawing System.Windows.Forms - } This MPC file is more complex than we have seen so far, due to the nature of a graphical .NET application. In this project, the file Program.cs contains the C# Main() function, so unless otherwise specified, the output will be named Program.exe. We use the exename keyword to change the name of the output to Client.exe. We must specify winapp = true as, by default, MPC will create a console-based C# application, and Client is a GUI-based one. Two Source_Files sections are necessary, as the file Client.cs contains a subclass of System.Windows.Forms.Form to act as the main window of the application. Form code requires additional infrastructure (e.g., support for one or more associated resource files) that normal code files do not. The resource file Resources.resx is similar in that it has an associated autogenerated C# file that provides access to the resources it contains. With the MPC file complete, we now add it to the workspace, yielding: - // DataServer.mwc - workspace { - specific { - cmdline += -language csharp - DataLib - Client - } - IDL - DataServer - DataServerConnectorLib - } Conclusion The following screen shots demonstrate the system. We start two Clients, as well as the DataServer (not shown). For this run, the server was run on the machine oci1373 and started with the following command (on a single line): DataServer -ORBDottedDecimalAddresses 0 -ORBListenEndpoints iiop://:12346 Each of the Client instances were started with this command (on a single line): Client -ORBDottedDecimalAddresses 0 -ORBInitRef DataServer=corbaloc:iiop:oci1373:12346/DataServer We enter "My First Item" into the TextBox associated with the Create button on the first Client. Pressing the Create button creates the database item, and the generated ID of 1 is reflected in the ListView. On the second Client, we enter the ID of 1 into the TextBox associated with the Read button. Pressing the Read button displays "My First Item" as the item description, demonstrating that the second Client has referenced the same database as the first Client. This article has described how to use TAO in a .NET application to implement both a CORBA client and server. The next article in this series will show how to incorporate OpenDDS to provide database notifications. References [1] Top Operating System Share Trend [2] Framework Overview [3] Standard ECMA-335 Common Language Infrastructure (CLI) [4] ADO.NET [5] warning LNK4248: unresolved typeref token (01000017) for '_TREEITEM'; image may not run [6] Linker Tools Warning LNK4248
https://objectcomputing.com/resources/publications/mnb/using-tao-and-opendds-with-net-part-1
CC-MAIN-2019-13
refinedweb
4,937
55.95
All, What’s the current line of thinking wrt patterns/best practices for remote calls and subsequent page updates? For instance, let’s say I have a simple link_to_remote call that simple creates a new comment for a given blog post. On success, I’d like to indicate that all was well, on failure, I’d like to give some indication as to why. Obviously, Rails has some nice (and by nice I mean ‘programmer friendly’) abstractions for handling this type of functionality but the myriad of options has left me in a state of paralysis. That said, I’m seeking to understand the preferred/recommended way to pull something like this off: class CommentController < ApplicationController def create_comment @comment = Comment.new(params[:comment]) if @comment.save # Should I use RJS here to update the page? # Should I return some HTML (sans RJS) and use the prototype helper to # update a DIV? else # Would obviously look to stay consistent here. # Do I use RJS to update the page? # Shall I send back a non 2XX status code and use prototype helper end end end What be the prevailing pattern? Arggh. TIA! Cory
https://www.ruby-forum.com/t/link-to-remote-patterns-idiom/126883
CC-MAIN-2021-43
refinedweb
191
63.29
Docs | Forums | Lists | Bugs | Planet | Store | GMN | Get Gentoo! Not eligible to see or edit group visibility for this bug. View Bug Activity | Format For Printing | XML | Clone This Bug Due to a missing include, scribus 1.1.2 compilation fails if python 2.3 is installed and configured as the default python. The following thread : proposes a fix to the issue, thru the simple patch: --- scribus-1.1.2.orig/scribus/plugins/scriptplugin/cmdvar.h 2003-07-06 10:09:18.000000000 +0100 +++ scribus-1.1.2/scribus/plugins/scriptplugin/cmdvar.h 2003-11-01 09:10:46.000000000 +0000 @@ -1,6 +1,7 @@ #ifndef CMDVAR_H #define CMDVAR_H +#include <Python.h> #include "scribus.h" /* Static global Variables */ I applied the patch in portage's working dir and finished the compilation successfully. Scribus's maintainer will probably incorporate this patch in the next scribus release, until then, it may be better to patch it before starting compilation. thanks. Changed patch to a sed-command and applied.
http://bugs.gentoo.org/32775
crawl-002
refinedweb
166
62.14
ONTAP Discussions We have a strong desire to run Oracle VM on cDOT 8.2 in a Flexpod environment which we already have in place. All of the documentation I have found is for 7-mode filers. I am wondering if there are any caveats or limitations to using NFS repositories or FCoE boot luns. Also, should the OSTYPE for LUNs and igroups be Linux or XEN? Any advise is greatly appreciated. Thanks Solved! See The Solution Hello RonaldMajor, NetApp and Oracle has written the joint vendor OVM Best practice technical report(TR-3712), which will be released to puplic in couple of days in. The OSTYPE for LUNs and igroups should be linux. Regards, Karthikeyan.N View solution in original post Thank you for the quick reply. I currently have TR-3712 which is for 7-mode. I assume the new one will be an update for cDOT? Yes RonaldMajor, The TR specifically updated for cDOT. nkarthik@netapp.com Cell: 919-376-6422 We have been unable to get OVM Manager to work with the showmount plug-in for cDOT and thus register the NFS volumes. I believe we are missing something and TR-3712 does not give specific instructions on how to configure OVM Manager to use NFS volumes on cDOT. I can install the plug-in and it runs correctly from the command line. Since the plug-in communicates with a management port on the filer and the volume is accessed from a data port, we are not sure how to configure the Generic NFS plug-in in OVM Manager. Obviously it must work since the authors of TR-3712 did it. Any ideas? I found the answer. The showmount plug-in should be installed on ALL OVM servers. The LIFs used to access (mount) the NFS repository volumes should have the mgmt firewall policy so the showmount plug-in can access with ONTAPI. The volume for the repository must be exported and mountable on ALL OVM servers. Make sure / is exported and is readonly! (Servers cannot mount anything if / is not exported.) With these requirements met, normal procedures for filesystem management in OVM Manager can be followed. Great Ronald to find the solution and share with others. Ronald, Still having problems with the showmount plugin. We've done the four steps you list here but are still getting "Authorization Failed" from the plugin. I found this comment in NaServer.py: def set_admin_user(self, user, password): """Set the admin username and password. At present 'user' must always be 'root'. """ def set_admin_user(self, user, password): """Set the admin username and password. At present 'user' must always be 'root'. """ Are you using root as the username? Thanks, Bill Bill, You need to create an account on the StorageVM for the showmount tool to use. This is the SVM that contains the OVM repository. Give the account vsadmin-readonly role and put the username and password for this account in the new showmount file as stated in the documentation. I hope this helps. Ah, the vsadmin-readonly role was the missling link. Thanks! Another question here if I may. My storage admin has asked me to mount the volumes using specific LIFs. However, because the LIFs and volumes are members of the same vserver all of the volumes are visible behind all of the LIFs. OVM Manager doesn't seem to allow you to specify the IP for the mount if the storage is visible behind more than one and instead picks the last IP that was used to refresh the storage.? Thanks, ? I am curious about this as well. I've been using iSCSI but would like to compare NFS for repositories, and also have the separate LIFS for management and data so the default file server access fails. Does anyone have feedback on this? Anyone done any extending of the plugin or showmount fix to accomodate the separate lifs? Live Chat, Watch Parties, and More! Engage digitally throughout the sales process, from product discovery to configuration, and handle all your post-purchase needs.
https://community.netapp.com/t5/ONTAP-Discussions/Is-anyone-running-Oracle-VM-on-cDOT-8-2/td-p/25721
CC-MAIN-2021-39
refinedweb
675
66.23
This document is intended to provide a guide regarding the use of Dispatch. Source code may be found on github. The Dispatch library consists of two primary components, the dispatch source and header and the framing source and header. Dispatch acts as the intermediary between your application and the remote application. Your application publishes data to the subscribers using Dispatch and your subscribers consume data from Dispatch. Your application will never have to interact directly with the hardware or the framing libraries. Dispatch is an event-driven framework which will execute your designated functions on receipt of certain messages. Framing happens, but - fortunately - you don't need to worry about it. Framing has been completely abstracted! A publish occurs when your application calls publish("topic", data). The data is then passed to Dispatch, through framing, and finally through the hardware drivers. The hardware drivers then pass the data through the communications channel where it is received by the hardware on the receiving end, de-framed, and then interpreted by the Dispatch library. Once the remote dispatch has received the message, it calls any subscribers to that data and allows them to execute. Subscribing is straightforward. Write your subscribing function and, then Dispatch will execute your function every time that message is received. Note that more than one function may be subscribed to a particular topic! Data retrieval must occur inside the subscribing function. If the data is not retrieved within the function, then the data will be lost forever! Data retrieval is done within the subscribing function using the DIS_getElements() function. In the off-chance that a driver exists in /src/drivers/, then you are in luck! In the likely scenario that it is not, then you will have to find or write the hardware driver yourself. There are four functions that need to be implemented: readable, writeable, read, and write. The function names do not matter since they will be assigned during initialization. Examples can be found in the /src/drivers/ directory. The drivers should have some sort of internal memory buffer that functions as a circular buffer. These buffers are the ones accessed by the below functions. In this document, TX_BUF_LENGTH and RX_BUF_LENGTH are the defines that will be utilized to control the sizes of this buffer at compile time. You can call them what you wish. The readable() function simply returns an unsigned 16-bit integer that indicates the amount of data than can currently be read from the RX circular buffer of the hardware interface. uint16_t UART_readable(void); The read() function takes length amount of unsigned 8-bit data from the driver buffers and copies them to the given buffer. void UART_read(void* data, uint16_t length); The writeable() function returns the unsigned 16-bit integer than indicates the amount of data that can safely be written to the circular buffer of the hardware interface. uint16_t UART_writeable(void); The write() function will write length amount of unsigned 8-bit data from the given buffer to the driver buffer, which will be sent through the hardware interface. void UART_write(void* data, uint16_t length) I considered not including defines for buffer sizing, but I quickly realized that some applications would be sending very modest amounts of data infrequenly and some could be sending significant amounts of data. As a result, you are required to set up the defines. There are default values that should get you started, but you should tune for your application. It is recommended that you write your UART TX driver to buffer at least 8 bytes. This gives enough room to send modest messages without stalling the processor to wait for the UART to send data. This is NOT a requirement! You can write your buffer to accept 1 byte at a time, but your processor will simply stall on a transmission waiting for bytes to move out of the TX queue. Due to the issue of having to calculate the checksum and verifying before accepting the entire message, received messages MUST be buffered. There are three buffer levels that must be accounted for: The dispatch message buffer is determined by: Use the provided buffer calculator to determine your memory footprint required for Dispatch to send and receive your data. The simplest way to determine the framing RX buffer is to simply double the size of the Dispatch message buffer. This will give a worst-case estimate that will ALWAYS be adequate under all circumstances. The reason for this is that the framing process adds escape characters when certain numbers are encountered. If the message consists of nearly all escape characters, then the message simply doubles in size. This is an unlikey event in some applications, but entirely plausible in others. For instance, it is not uncommon for sensor data to dwell on a particular number for some time. Ultimately, you must make the decision regarding this. The UART RX Buffer is where the hardware interfaces with the software. In some cases, there will be hardware buffers on-die that will be adequate. On many microcontrollers, this will not be the case and software buffers will need to be implemented. The size of this buffer is determined by two factors: baud rate and the frequency that DIS_process() is called. In the examples there is a file called 'dispatch_config.h' which contains some defines. Here, we will boil the above entries into those defines just to go the extra mile to make your experience a bit easier. In our case, we are including our hardware source file, uart.h, along with the dispatch header file, dispatch.h: #include "uart.h" #include "dispatch.h It is usually necessary to initialize the hardware independently of Dispatch. For a serial module, this configures the registers to communicate on the desired channel at a particular baud rate. We have called our pin hardware initializer DIO_init() and the channel initializer UART_init(). DIO_init(); UART_init(); There are two items that need to be tended to, initializing Dispatch itself and assigning the function that Dispatch will utilize for communication. /* Assign the four necessary channel functions to Dispatch. */ DIS_assignChannelReadable(&UART_readable); DIS_assignChannelWriteable(&UART_writeable); DIS_assignChannelRead(&UART_read); DIS_assignChannelWrite(&UART_write); /* Initialize Dispatch */ DIS_init(); As you can see, our communication hardware functions were very similary named to the Dispatch functions so as to make the assignments easier to identify. After initialization, DIS_process() must be called periodically in order to process incoming data and subscriptions. Generally, this is placed into the infinite while(1) loop, but it can be assigned to a task or other periodic function. while(1){ DIS_process(); /* ... other continually executing functions ... */ } It is not recommended to place DIS_process() within a timer interrupt as it may block all of your other interrupts, depending on architecture and configuration of your device. As described in the initial post, publishing to Dispatch is easy. We have renamed some of the functions to keep them from potentially colliding with other functions, but the functionality has not changed. A quick summary: /* send "my string" to subscribers of "foo" */ DIS_publish("foo", "my string"); /* send first element of bar[] to subscribers of "foo" */ DIS_publish("foo,u8", bar); /* send 10 elements of bar[] to subscribers of "foo" */ DIS_publish("foo:10,u8", bar); /* send 10 elements of bar[] and baz[] to subscribers of "foo" */ DIS_publish("foo:10,s16,s32", bar, baz); // ^ ^ data sources // ^ ^ format specifiers // ^ number of elements to send // ^ topic When not sending a string, the format specifiers must be in place for each array of data to be sent. Use the format specifiers shown here: In order to reduce the program memory footprint, we have introduced less dynamic publishing functions which perform the same function as DIS_publish(), but simply use less memory by making the function less generic. For instance, the two publish functions will result in sending the same data: uint8_t data[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; DIS_publish("foo:10,u8", data); DIS_publish_u8("foo:10", data); We have reduce the amount of processing and program memory footprint necessary to send a transmission. This approach is only recommended for situations in which the program memory is limited. Subscribing usually happens before the infinite while(1), but can happen at any time, even in response to other events. First, we must write the subscribing function. Our subscribing function is going to increment a local counter and then publish that counter back to topic "i": void mySubscriberFunction(void){ static uint16_t i = 0; i++; /* publish i back to the sender to 'close the loop' */ DIS_publish("i,u16", &i); } At some point, we must actually subscribe the function to the topic to create the association within Dispatch: DIS_subscribe("foo", &mySubscriberFunction); Now, every time that the topic "foo" is received, Dispatch calls mySubscriberFunction() which increments i and publishes it to topic "i". There is usually some payload sent with the topic. This can be string data or numeric, of 8, 16, or 32 bits. It may be a single data point or consist of an array or multiple arrays of data. How do we get the approprate data? In this, we will use the DIS_getElements() function. Topical data should always have the same format. It is possible to send different data formats to the same topic, but there is no way to distinguish one format from another. Best to stick with one format per topic. The DIS_getElements(uint16_t element, void* destArray) function takes two arguments, element and destArray. The element is the element number that is expected. In single dimensional data - such as strings, single numbers, and singe arrays - this number will be 0. In multidimensional data, this may be a different number in order to retrieve different values. A few examples should clear it up. For instance, if the topic is known to receive a string, then allocate string storage within the subscribing function and use DIS_getElements to retrieve it: void mySubscriberFunction(void){ char str[32] = {0}; // allocate your string array DIS_getElements(0, str); // copy the received data into str /* now use the data here */ } To retrieve a single number, we use a similar notation. When mySubscriberFunction is expecting a single unsigned integer: void mySubscriberFunction(void){ uint16_t v; // allocate memory DIS_getElements(0, &v); // copy the received data into local variable /* now use the data here */ } To transmit more than one variable, multiple calls to DIS_getElements() will be necessary. Note that the different calls will specify different element numbers. In the below function, we are mixing different integer widths and signs and still receiving them appropriately, so long as the correct element is retrieved: void mySubscriberFunction(void){ uint16_t a; // allocate memory int16_t b; int32_t c; DIS_getElements(0, &a); // copy the received data into local variable DIS_getElements(1, &b); DIS_getElements(2, &c); /* now use the data here */ } It is also possible to retrieve arrays of data, so long as the array length is pre-determined. In fact, transmitting data within an array is much more bandwidth-efficient and has a very similar syntactical complexity: void mySubscriberFunction(void){ uint16_t v[10]; // allocate memory DIS_getElements(0, v); // copy the received data into local array /* now use the data here */ } One may even retrieve a multi-dimensional array with similar effort, even with different data widths: void mySubscriberFunction(void){ uint16_t x[10]; // allocate memory int8_t y[10]; DIS_getElements(0, x); // copy the received data into local array DIS_getElements(1, y); /* now use the data here */ } And, just like that, 10 elements of x and y are received. This document is intended to list all of the available functions of Dispatch. Move over to the Dispatch How-To for a comprehensive guide for using Dispatch. Source code may be found on github. This table contains the basic functions which make up the Dispatch library. Most application will use all of these functions in one form or another. These functions should only be called at the beginning of program execution. /* Assigns the function which is used to determine how many bytes are currently readable from the UART RX buffer. */ void DIS_assignChannelReadable(uint16_t (*functPtr)()); /* Assigns the function which is used to determine how many bytes may be written to the UART TX buffer. */ void DIS_assignChannelWriteable(uint16_t (*functPtr)()); /* Assigns the function which is used to read from the UART RX buffer. */ void DIS_assignChannelRead(void (*functPtr)(uint8_t* data, uint16_t length)); /* Assigns the function which is used to write to the UART TX buffer. */ void DIS_assignChannelWrite(void (*functPtr)(uint8_t* data, uint16_t length)); /* Initializes Dispatch. Must be called after the `DIS_assignChannel` functions. */ void DIS_init(void); Subscribing to a topic will likely only occur once during initialization, but it is possible to dynamically subscribe and unsubscribe to topics. The DIS_getElements function is utilized to retrieve data within the subscriber. /* Subscribes to a topic. Normally called one time at initialization, but may be called at any time during program execution */ void DIS_subscribe(const char* topic, void (*functPtr)()); /* Removes a subscriber from the subscription list. If the subscriber is not active, then there is no action. */ void DIS_unsubscribe(void (*functPtr)()); Retrieving data is - hopefully - as simple as sending it. Note that it must be completed within the subscribing function. /* Retrieve data received on the RX. */ uint16_t DIS_getElements(uint16_t element, void* destArray); The element is the element number which is to be retrieved. Generally, if it warrants a new variable, then it will have its own element number within a particular topic. The destArray is the address of a variable to which the data is to be stored. /* Publishes data to a topic. This is the most generic publish function and has the most flexibility. */ void DIS_publish(const char* topic, ...); /* Processes incoming messages and calls the appropriate subscribers. Must be called periodically. If this is called infrequently, then any subscriber functions are also called infrequently and may be missed. */ void DIS_process(void); These functions are intended to replace the DIS_publish() function above with a specific variant in order to reduce the program memory footprint of Dispatch in some applications. It is not necessary to utilize any of these functions. All of these could be replaced by an appropriate call to DIS_publish(). These functions are available in releases of Dispatch that are greater than v1.0. /* Publishes a string to a topic without having to use `stdarg.h`. If the user only needs to send a string using Dispatch, then this will be smaller and faster than `DIS_publish()` */ void DIS_publish_str(const char* topic, char* str); /* Publishes a single unsigned 8-bit array to the topic without using `stdarg.h`. If this user only needs to send an 8-bit array using Dispatch, then this will be smaller and faster than `DIS_publish()`. */ void DIS_publish_u8(const char* topic, uint8_t* data); /* Publishes a single signed 8-bit array to the topic without using `stdarg.h`. If this user only needs to send an 8-bit array using Dispatch, then this will be smaller and faster than `DIS_publish()`. */ void DIS_publish_s8(const char* topic, int8_t* data); /* Publishes two unsigned 8-bit array to the topic without using `stdarg.h`. If this user only needs to send an 8-bit array using Dispatch, then this will be smaller and faster than `DIS_publish()`. */ void DIS_publish_2u8(const char* topic, uint8_t* data0, uint8_t* data1); /* Publishes two signed 8-bit array to the topic without using `stdarg.h`. If this user only needs to send an 8-bit array using Dispatch, then this will be smaller and faster than `DIS_publish()`. */ void DIS_publish_2s8(const char* topic, int8_t* data0, int8_t* data1); /* Publishes a single unsigned 16-bit array to the topic without using `stdarg.h`. If this user only needs to send an 8-bit array using Dispatch, then this will be smaller and faster than `DIS_publish()`. */ void DIS_publish_u16(const char* topic, uint16_t* data); /* Publishes a single signed 16-bit array to the topic without using `stdarg.h`. If this user only needs to send an 8-bit array using Dispatch, then this will be smaller and faster than `DIS_publish()`. */ void DIS_publish_s16(const char* topic, int16_t* data); /* Publishes a single unsigned 32-bit array to the topic without using `stdarg.h`. If this user only needs to send an 8-bit array using Dispatch, then this will be smaller and faster than `DIS_publish()`. */ void DIS_publish_u32(const char* topic, uint32_t* data); /* Publishes a single signed 32-bit array to the topic without using `stdarg.h`. If this user only needs to send an 8-bit array using Dispatch, then this will be smaller and faster than `DIS_publish()`. */ void DIS_publish_s32(const char* topic, int32_t* data);
http://forembed.com/dispatch-how-to.html
CC-MAIN-2018-39
refinedweb
2,730
53.41
JSONObject example in Java JSONObject example in Java In the previous section of JSON tutorials you .... Now in this part you will study how to use JSON in Java. To have functionality JSON Tutorials ; JSONObject example in Java...; JSONArray example in Java In this part of JSON tutorial you... In the previous section of JSON-Java example you have learned how to create a java What is JSON? transfer from one place to another easy. Though JSON is based on Java Script... file. JSON notation contains: Objects beginning and ending with curly... Engineer" } Read more tutorials about JSON. Which programming language supports JSON ("Parsing JSON Message Example "); alert(arrayObject.toJSONString().parseJSON..., visit the following link:... it using JSON The given code parse the message in JSON in JavaScript missing package-info.java file missing package-info.java file How to find and add the packages in Java if it's missing from the list JSON-JSP example this example follow this step by step procedure: create a JSON-JSPExample.jsp file... JSON-JSP example In the previous section of JSON-Servlet example you have json Tutorials JSON Tutorials... data is transferred and how it is encoded. While JSON is a tool used for describing values and objects by encode the content in a very specific manner. 2)JSON missing some import class(may be) - Java Beginners shape.java", what i missed? Hi, You have to change the java file name to "shape.java". In java file name and class name should the the same. For example you have to create a class "shape" then create new file in netbeans json json how to develop iphone web service application using json. Please help me by giving any link where I could find an example or any help will be anticipated converting Json data into rows of DTO in java converting Json data into rows of DTO in java I am using jqxgrid, and I am able to access the json data in JAVA controller. But now my requirement... have downloaded & used the following JAR file 'java-json.jar'. Thanks ; C Tutorials | Java Tutorials | PHP Tutorials | Linux... Tutorials | Dojo Tutorials | Java Script Tutorial | CVS Tutorial... | C String Copy | C Dynamic Array | C file delete example | C file...) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl. java:57 and Servlet example JSON and Servlet example In the previous section of JSON-Java example you have learned how to create a java class by using JSON classes. Now in this example C++Tutorials benefit to download the source code for the example programs, then compile and execute each program as it is studied. The diligent student will modify the example... other tutorials, such as C++: Annotations by Frank Brokken and Karel Kubat JEE7 JSON: How to use JEE 7 JSON API? languages. Here we are talking about the the Java API for JSON Processing which... in the pom.xml file. Here is the Java code (JsonArrayBuilderExample.java... compile To run the example you should use the following command: mvn exec:java Tutorial, Java Tutorials Tutorials Here we are providing many tutorials on Java related... Java Testing JSON Tutorial... NIO Java NIO Tutorials retrieve JSON array objects in javascript the following links: BASIC Java - Java Tutorials letter and lover case. For example, case and Case are different words in java...Basic Java Syntax This tutorial guide you about the basic syntax of the java... of the java which is applicable to all java program : Case Sensitive Java Java xcode warning missing file xcode warning missing file on deleting a folder from desktop earlier that has the link to application.. now, stoping the application to run. The xcode is giving warning like file does not exist or xcode warning missing file Spring MVC Tutorials Spring MVC Tutorials and example code In this section I will provide you... if user input is missing or not correct. This is very good example... Part 3. Spring MVC File Upload Example - This tutorial JSON with Java JSON with Java How to request Json From URI and to parse and to store the values in Java array jfree missing import file jfree missing import file hi....... i have checked the jar file of jfree that import file of RECTANGLEINSETS is not there then what to do now? how.... This jar contains the required class file Spring 3.0 Tutorials with example code Spring 3.0 - Tutorials and example code of Spring 3.0 framework... of example code. The Spring 3.0 tutorial explains you different modules... download the example code in the zip format. Then run the code in Eclipse java tutorials java tutorials Hi, Much appreciated response. i am looking for the links of java tutorials which describes both core and advanced java concepts... topics in detail..but not systematically.For example ..They are discussing about Siverlight JSON Siverlight JSON how to use JSON in silverlight, i need to populate dynamic data by using JSON CAN ANY HELP ME Hi Friend, Please go through the following link: Thanks JSON in JavaScript this JavaScript and JSON example you have to just run this ".htm" file on your... JSON in JavaScript JSON stands for JavaScript Object Notation that  Ajax json Ajax json Hi, How consume json file in ajax program? Thanks JSP Tutorials - Page2 file Java Beans are reusable components. It is used to separate Business... in JSP file. This example performs transformation from an XML file to XSLT... page In this example, we will see how to embed a flash file in jsp page A better Java JSON library? A better Java JSON library? A better Java JSON library "JSONArray" example in Java "JSONArray" example in Java  ... in your java program you must have JSON-lib. JSON-lib also requires following "....jar JSON-lib is a java library for that transforms beans, collections, maps Java FTP file upload example Programming in Java tutorials with example code. Thanks...Java FTP file upload example Where I can find Java FTP file upload...; Hi, We have many examples of Java FTP file upload. We are using Apache Parsing a message in JavaScript with JSON ; To run this example we need to have json2.js file included with our ParseMessageJSON.htm file. File "json2.js" is as same as in our previous example... Parsing a message in JavaScript with JSON RDF Tutorials ; Generate RDF file in Java In this example we are going to generate our first RDF( Resource Description File). This example generates a RDF file with the use of "Jena". Jena is a java API Java example for Reading file into byte array Java example for Reading file into byte array. You can then process the byte...: Java file to byte array Java file to byte array - Example 2... ByteBuffer to byte array in java. Read more at Java File - Example Java error missing return statement Java error missing return statement Java error missing return... Java error missing return object. For this we have taken a non void method Good tutorials for beginners in Java in details about good tutorials for beginners in Java with example? Thanks.  ...Good tutorials for beginners in Java Hi, I am beginners in Java... the various beginners tutorials related to Java Java Example Codes and Tutorials Java Tutorials - Java Example Codes and Tutorials Java is great programming... Java conversion tutorials with example.  ... Java String tutorials with example.   AWT Tutorials AWT Tutorials How can i create multiple labels using AWT???? Java Applet Example multiple labels 1)AppletExample.java: import javax.swing.*; import java.applet.*; import java.awt.*; import JSON-RPC JSON-RPC JSON-RPC-Java is a dynamic JSON-RPC implementation in Java. It allows you to transparently call server-side Java code from JavaScript with an included lightweight JSON-RPC XML Tutorials This Example shows you how to Query Xml File via XPath expression. JAXP (Java API for XML... This Example shows you how to get the next Tag from the XML File. JAXP (Java API for XML... programming. In these tutorials we have developed example programs using struts - application missing something? and they are taken to correct location. What am I missing? The JSP, Java Class...struts - application missing something? Hello I added a parameter... to working in the presentation layer no deeper than struts-config. I know Java C Tutorials . C file write example Here we are using... in the given example that we want to replace the name of the text file MYFILE.txt with HELLO.txt. C file read example This section...) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl. java:57 Java - JDK Tutorials Java - JDK Tutorials This is the list of JDK tutorials which... should learn the Java beginners tutorial before learning these tutorials. View the Java video tutorials, which will help you in learning Java quickly. We XPath Tutorials XPath Tutorials Java - XPath Tutorial In this example we have created an XML file "person.xml" first, which is necessary Java HashMap - Java Tutorials provides a collection-view of the values in the map. Example : import... : C:\Program Files\Java\jdk1.6.0_18\bin>java MapDemo. AXIS ATTACHMENT MISSING - WebSevices AXIS ATTACHMENT MISSING Hi, i have a method which takes a filename as input. It reads the file and returns the content using MessageContext(Axis1.4... { String ret = "GET FILE CALLED"; try Creating Message in JSON with JavaScript a message with JSON in JavaScript. In this example of creating message in JSON... this example you need to include the JavaScript file "json2.js" so.../blog/2006/09/26/for-in-intrigue/ This file creates a global JSON object DBUnit Tutorials with proper example. The DbUnit is an extension of JUnit which is used data-driven Java applications. With the help of DbUnit you can repopulate your database with sample data and perform unit testing of the Java application. This helps JSF - Java Server Faces Tutorials JSF - Java Server Faces Tutorials Complete Java Server Faces (JSF) Tutorial - JSF Tutorials. JSF Tutorials at Rose India covers... zip format from our website. In our JSF tutorials we will describe you Thread Deadlocks - Java Tutorials Thread Deadlock Detection in Java Thread deadlock relates to the multitasking... lock that holds by first thread, this situation is known as Deadlock. Example In the given below example, we have created two classes X & Y. They have Appending Strings - Java Tutorials .style1 { text-align: center; } Appending Strings In java, the two... will compare the performance of these two ways by taking example. We will take... of accurate size and after that we append. Given below the example: public Creating Array Objects in JavaScript with JSON in JavaScript-JSON. In our example file we have created an object "students"... Creating Array Objects in JavaScript with JSON... of JavaScript-JSON tutorial you have known that how to create an object and now Submit Tutorials - Submitting Tutorials at RoseIndia.net and related pictures (if any). Then create zip file of the tutorials fine and then email... Submit Tutorials Submitting Tutorials at RoseIndia.net is very easy. We welcome all members JSON array objects retrieval in javascript JSON array objects retrieval in javascript I am fetching some data... box is not populating any value, perhaps i am doing something wrong in json... in while loop JSONObject jsonObj= new JSONObject(); List<String> myList Tutorials on Java examples Java FTP Library Advanced Java Tutorials Java Example Codes... Tutorials on Java Tutorials on Java topics help programmers to learn... on Java like wrapper class, break example, get example, Biginteger json json how connect ajax with json XML,XML Tutorials,Online XML Tutorial,XML Help Tutorials XML Tutorials Transforming XML with SAX Filters This Example shows you the way to Transform XML with SAXFilters. JAXP (Java API for XML Processing) is an interface which provides json json how to get data in json object from database How can I initialize the JSONArray and JSON object with data? How can I initialize the JSONArray and JSON object with data? How can I initialize the JSONArray and JSONObject with data Java : Servlet Tutorials - Page 2 Java : Servlet Tutorials  ... data from this .java file.. Export data... an example which explains you clearly. In the example, We have created the session Java File Management Example of file. Read the example Read file in Java for more information on reading...Java File Management Example Hi, Is there any ready made API in Java for creating and updating data into text file? How a programmer can write code JRuby Tutorials table on the console output. File Reader example... with the JRuby. Here in our example we are reading a text file and printing its content... tutorials we have learned about how to use Java classes in JRuby program now here is one RMI Tutorials java files. RMI-Example-3 In this example you will see function... RMI Tutorials In this section there are many tutorials on RMI, these tutorials FTP Programming in Java tutorials with example code continuing with the FTP Programming in Java. With the help of these tutorials... API's in your Java program. Here are the tutorials and examples of FTP Programming in Java: What is FTP (File Transfer Protocol)? What is Anonymous FTP Difference between jsonstring and json object Difference between jsonstring and json object Is There any difference between JsonString and jsonobjectA? if there is any differece could any one explain with example. Thanks venkatesh ANT Tutorials to generate build.xml file This example shows how to generate... This is a simple example that illustrates how to find the basedir name, file name... This build.xml file is used to compile and run the java file and print the value Hibernate Tutorials the java class and add necessary code in the contact.hbm.xml file.  ... Hibernate Tutorials Deepak Kumar Deepak... conception to implementation. He has a good experience into Java and J2EE java binary file io example java binary file io example java binary file io example JSP Tutorials the Java code in your HTML page. Basically JSP is simply a text file which...; JSP Tutorials - Introducing Java Server Pages Technology... JSP Tutorials   Reading file into bytearrayoutputstream is:" + e.getMessage()); } } } Read more at Java File - Example and Tutorials... input stream and byte output stream. This is and good example of reading file... the file into byte array and then write byte array data into a file. In this example Roseindia Java Tutorials Example Java Break Example Master Java Tutorials (TOC) Java...Roseindia Java Tutorials are intended to provide in-depth knowledge of Java... with roseindia Java Tutorials is quite simple and easy, which will teach you Java Field Initialisation - Java Tutorials Java Field Initialization The fields/variable initialization in any.... It is performed to provide some default value. The java programmer can... the initialization code is copied into all the constructor. For Example public Java Comments - Java Tutorials .style1 { text-decoration: underline; } Comments in Java holds the description or hint about the code or explanations... ignore these comments and do not compile it. Types of comment Java supports Java write to file Java write to file How to write to a file in Java? Is there any good example code here? Thanks Hi, Java is one of the best... to a text file. Here is the examples: Example program to write to file. File jQuery - jQuery Tutorials and examples jQuery - jQuery Tutorials and examples  ... and jQuery Tutorials on the web. Learn and master jQuery from scratch. jQuery is nice... to develop highly interactive web applications. In this jQuery tutorials series we Flex Tutorials ComboBox control inside your flex file. In the example you will learn to build two... In the example below an action script file with .as extension has been... and Sqrt.as, and the third example, i.e. Figure.mxml is our main flex file inside Java file byte reader Java file byte reader I am looking for an example program in Java for reading the bytes. More specifically I need java file byte reader example code. Thanks For complete details read the following tutorials: Java JSP Tutorials Resource - Useful Jsp Tutorials Links and Resources tutorials and the Java documentation . DMXzone.... Java Applets Tutorials: JSP or Java...JSP Tutorials   Chart & Graphs Tutorials in Java Chart & Graphs Tutorials in Java Best collection of Graphs and Charts Tutorials in Java. Our Chart and Graphs tutorials will help learn everything you need Java Training and Tutorials, Core Java Training Java Training and Tutorials, Core Java Training Introduction to online Java tutorials for new java programmers. Java is a powerful object... applications and applets with graphics and user interfaces because Java has built Struts Tutorials Struts Tutorials Struts Tutorials - Jakarta Struts... is provided with the example code. Many advance topics like Tiles, Struts Validation Framework, Java Script validations are covered in this tutorial. Using JSON-RPC-Java JSON-RPC-Java JSON-RPC-Java is an AJAX RPC middleware that allows JavaScript DHTML web applications to call remote methods in a J2EE Application Server and Transparently maps Java Tutorials Java read binary file Java read binary file I want Java read binary file example code... at Reading binary file into byte array in Java. Thanks Hi, There is many more examples at Java File - Learn how to handle files in Java with Examples Java Multi Dimensions Array - Java Tutorials .style1 { text-align: center; } Multidimensional Arrays in Java In java, the grouping of same type of elements for storing under the same name... below the example to provide you an idea-how array works? Declaring Ajax Tutorials Ajax Tutorials  ... is that they don't have to type as much and they don't have to wait as long. For example, having... Remoting DWR allows JavaScript in a browser to interact with Java on a server In this section of sitemap we have listed all the important sections of java tutorials. Select the topics you want..., Spring, SQL, JSF and XML Tutorials. These All Java Tutorials links XML, XML Tutorial, XML Tutorial Online, XML Examples, XML Tutorial Example XML XML Tutorials and examples In this section we will learn XML with the help of tutorials and example code. If you are a beginner in XML then learn... tutorials mentioned below. We are giving XML tutorials and example codes for free File Handling in Java was trying to find some tutorials about handling file in Java on net. I have also seen...File Handling in Java Hi, While opening a file in Java developers... are the use of these classes? Is there example code for explaining the File Handling Java Swing Tutorials Java Swing Tutorials Java Swing tutorials - Here you will find many Java Swing... and you can use it in your program. Java Swing tutorials first gives you brief
http://www.roseindia.net/tutorialhelp/comment/85990
CC-MAIN-2014-41
refinedweb
3,111
50.12
Write a function called numeric() that takes a c-string made up of numeric characters such as 0's and 1's, and assigns the numeric value of the string to an integer type reference parameter and returns true if the numeric value was computed successfully and false otherwise. For example, if the c-string contains 00100011, it must assign the value of 35 to its integer parameter and return true. Another parameter passed to the function tells what number system the c-string contains. For the example just given, that parameter would be 2 indicating base 2 for the value (binary number). If that parameter is 10, then the string would have to contain a decimal value (0...9). The function first checks to see if the elements of the string meet the number system criterion in which case, it computes the value, assigns it to its reference parameter and returns true. If not, it assign -1 to the reference parameter and return false. To calculate the numeric value of the string, the function must take the numeric value of each of the characters of the string, multiply each by the weight of the digit and add all the resulting products. For example, if the number is 6903, 6 has a weight of 1000, 9 has 100, 0 is at 10 and 3 has a weight of 1. Remember that the numeric value of a digit is different from its ASCII value. For example, the ASCII value of 0 is not 0; it's 48 and the ASCII value of 1 is 49, etc. Also, write a function called shift_left() which takes a c-string and shifts all its digits to left by one. So, for example, 01101001 becomes 11010010. For this to work the leftmost digit must be 0; otherwise, the result will be wrong. That means the input number must not be so large as to make the leftmost digit a non-zero. Also, notice that the rightmost digit takes on a 0 after the shift. After performing the shift, the function copies the input c-string to another (output) c-string parameter which the caller (main) can take as the output. An integer parameter again tells the function the number system of the input c-string, 10 for decimal, 2 for binary, etc. Now, write the main program to test both functions - once with a binary number and once with a decimal value: declare two c-strings of a size large enough to hold at least 17 characters (large enough for 16 bits plus the null character) called input and output. Read a binary number containing no more than 16 bits from the keyboard and store in input c-string, and using the numeric() function, calculate and print in main its numeric value. Then, pass the string read from the user as well as the output c-string to the shift_left() function which will assign the shifted string to the output c-string. Then, have main pass the output c-string to numeric() function to compute its value. Again, print the resulting value in main. Also, read a decimal value from the user into the input c-string, pass it to the numeric() function, and print the resulting value in main, and then pass both the input and output c-strings to the shift_left() function and print the result again in main. You will see that when the string digits are shifted to the left, it's the same as multiplying its value by the base: 2 for binary, 10 for decimal, etc. Code:#include <iostream> #include <cmath> #include <conio.h> using namespace std; bool numeric(char[], int, int&); void shift_left(char[], char[], int); int main() { char input[17], shifted[17]; int number, base; cout << "Enter a numeric string of maximum 16 characters long: "; cin.getline(input, 17, '\n'); cout << "\nEnter the base; e.g.: 2 for binary, 10 for decimal: "; cin >> base; if(numeric(input, base, number)) { cout << "\nNumeric value of " << input << " = " << number << endl; shift_left(input, shifted, base); cout << endl << input << " shifted left by a digit = " << shifted; if(numeric(shifted, base, number)) cout << "\nNumeic value of " << shifted << " = " << number << endl; } else cout << "\nInvalid string entered!\n"; cout << "\nPress any key to continue."; _getch(); return 0; } bool numeric(char in[], int base, int& num) { int len = strlen(in), exp = 0; num = 0; for(int i = len - 1; i >= 0; i--) { if(in[i] >= base) { num = -1; return false; } else num += (in[i] - '0') * pow((double)base, exp++); } return true; } void shift_left(char in[], char sh[], int base) { strcpy(sh, in + 1); strcat(sh, "0"); sh[strlen(sh)] = '\0'; } I didn't write this program ,but I need an explanation on why is num += (in[i] - '0') need to has " - '0' " in it. Thank you
http://cboard.cprogramming.com/cplusplus-programming/141954-need-help-explaining.html
CC-MAIN-2015-40
refinedweb
797
63.93
Frederic Raphael (Page 2) When I was 6 years old, my father was transferred from New York to London. As we crossed the Atlantic, in the M.V. Britannic, he comforted me by saying, “Now you can be an English gentleman instead of an American Jew.” Whether or not I achieved this transformation is not for me to say, nor do I greatly care: Hybridization can be a happy condition: for a novelist at least, it is more a privilege than an inconvenience to entertain contradictory elements. How much of a Jew have I remained, despite my Anglicized accent? In terms of faith, I am (like many) lost to orthodoxy: I eat shellfish, do not read Hebrew, scarcely notice whether I am in Jewish company or not. I do not believe in the literal veracity of the Torah nor do I have any desire to live in a Jewish community, here, there or anywhere. In certain company, such a near-Jew can be accused of betraying his people or—a charge typically unsheathed by some militant brethren—of “self-hatred.” The topic has been copiously covered, but I doubt the accuracy of the charge and even, except in extreme cases such as Otto Weininger, the terminology. It is not entirely disreputable (though it may be comic) for a man to resent the label others tie on him, or the expectations they then have of his character and duties. The comedy arises from the tenacity of what Shlomo Sand argues are as often “national” as Jewish characteristics. Jewish humor, for instance, is essentially Eastern European. There are not many jokes in the Bible. Jesus wept; but is not reported to have laughed. Spinoza was a great (Sephardic) philosopher, but no marked humorist. There is an old Jewish story, which it would be politically incorrect to tell in full, that has the punch line (from a rabbi’s lips) “Look who wants to be nobody!” The revised version is less funny, but more ludicrous: In today’s Israel, if Sand is to be believed, it is not a matter of conscience or even, in some cases, of lineage whether or not a man is a Jew, but of authoritarian decision. Somewhere behind all this is the ghost of the 19th century Viennese anti-Semitic Mayor Lueger, who boasted that he decided who was or was not a Jew. It is no great scandal, still less a surprise, to find that the routines of his and other anti-Semitic discourse, rough or smooth, have generated reciprocal responses, not least of more or less aggressive nationalism and self-enchantment, in Jewish apologists. In the same way, Bismarckian nationalism, to which no one at the time took great exception, encouraged (to put it mildly) men such as Heinrich Graetz to propound a history of “the Jews” which would entitle his people to belong to the nascent, and expanding, new Germany. By Shlomo Sand Verso, 332 pages By the same token, turned abruptly on its head, it is unlikely that Zionism would ever have achieved its measure of paramountcy if it had not been for Nazi racism (and what Lucy Davidowicz called “the Abandonment of the Jews” by the Allies). In that sense, there is some truth in the malevolent assertion, which George Steiner put in the mouth of his fictitious Hitler, in “The Portage of A.H. to San Cristobal,” that without Adolf there would have been no Jewish state. Zionism was as unpopular among emancipated Western Jewry (only some 2 percent endorsed it) in the 1930s as Nazism itself had been in Germany until the disaster of the Depression. It does not follow that the state of Israel should not, for that reason, be allowed to exist, still less that its founders endorsed or conspired with the Nazis. Konrad Adenauer’s payment of reparations to Israel, rather than (as later happened, in some cases at least) to individual sufferers, was probably well intentioned. Symbolically, however, it can be read as standing for Germany’s (and the West’s?) paying off of all its debts to “the Jews.” Europe’s conclusive goodbye was wrapped in cash. Israel, it has further been argued (not entirely implausibly), was established so that Europe’s evicted Jews should have somewhere to go which was not either the United States or Britain. The victors did not want the despoiled. The British, unsurprisingly, used the Jews to enable them to divide and rule Palestine and then, in accordance with Foreign Office tradition, left them to face the angry Arabs in a war which, if the British had rightly calculated (and fixed) the odds, would lead to their elimination. Pontius Pilate has never lacked emulation in London. None of this, however keenly asserted, validates the existence of Israel, nor yet does its devious creation, as a kind of noble dump for unwanted persons, invalidate it. It happened as it did, not because “the Jews” were or were not a single people, but in consequence of events over which no Jews, of any political persuasion, had effective control. Israel is, in that sense at least, a reactionary state. So what? It is a common phenomenon, as Zionists have proved, for the defeated to adopt, in whatever modified or supposedly sublime form, the tactics of those who humiliated them. Ben-Gurion, for eminent instance, admired European culture, but wanted the Jews to become, once more, a “fighting people” (in truth, the Philistines had more often defeated the Jews than modernized myth found convenient to admit). The baggage Ben-Gurion wanted left behind, in old Europe, were the weapons of inferiority: He now wished the sword to be mightier than the pen. George Steiner has also observed that “Jewishness, in the twentieth century, is a club from which there can be no resignations.” In the 21st, however, it is a club to which entry is vigilantly scrutinized in the state which, at the same time, is said to incorporate the eternal aspiration of all Jews. The vexedness of the question of Jewish identity has been modernized by the existence of Israel and by its leaders’ claim that it is the (exclusive) nation-state of the Jewish people rather than of those who live within its borders and are subject to its laws. For this reason, Sand tells us, at least one of its leading judges, Shimon Agranat, has maintained that “there is a Jewish nation, but not an Israeli 20, 2010 at 11:15 am Link to this comment Now Charterbus in your own words and without the sales link at the bottom. You will be reported, no free sales on the boards! Anti-Judaism is just another way of saying they are lesser than you. It is both egotistical on a national level and a show of defiance against that which you think is better than you and you can’t stand it. The same happens on a personal level. I see it here and elsewhere following the same pattern, same psychological roots. No live and let live, but one-up-ones-ship over another but with far more dire and dangerous consequences. [Like pograms and death camps and ostracism from society etc. Jews aren’t the only ones but theirs is one of the most prominent and still living examples. Only now some of them do the same to others now that they have power, such as the Palestinians. By Night-Gaunt, March 14, 2010 at 9:20 pm Link to this comment Ah which came first in this the prophecy before it happened or written in after? When the prophecy is well known all it takes is what the writers wish to interpret to mean. Was Simon a precursor to Jesus? Hard to say if they can just find that one missing word. Was it a call by that angel to resurrection or something more mundane? By Inherit The Wind, February 27, 2010 at 12:53 pm Link to this comment Dave: You can’t get around it: You keep saying that you don’t have to obey God’s Laws given to Moses. That FUNDAMENTALLY means one of three things: 1) you are violating God’s Law. 2) God is not infallible, therefore not omniscient and omnipotent, and therefore NOT got. 3) It’s not God’s Law and the OT is nothing but a fairy tale made up by men. You can squeeze your eyes shut as tight as you can and pray as hard as you like but you cannot get around that basic contradiction. Now THIS got me laughing: Everything that was to happen in the NT was prophesied in the OT. Damn straight! No doubt about THAT! You better believe that if I was charged with writing the NT I’d be as careful as a high-priced lawyer to make sure EVERYTHING I wrote mapped EXACTLY to the OT! Programmers call this a “Requirements Matrix” to ensure their software addresses EVERY specification agreed to by the client. “Remember: He has to be descended from the House of David…be sure to write that in!” What? You mean to say ITW thinks the guys who wrote the SELECTED scriptures picked to be included in the NT might have “cooked” them to fit the prophesies??? Amazing! (like I said: Too funny!) By Night-Gaunt, February 27, 2010 at 11:24 am Link to this comment True. Once the wall is set nothing can breech it from without only from within. By ardee, February 27, 2010 at 9:02 am Link to this comment Inherit The Wind, February 25 at 7:24 pm I think that one cannot expect to win an argument with a religious fanatic ( anyone who believes in a supernatural and all powerful god). Thus you are really speaking only to yourself…..why bother? By DaveZx3, February 26, 2010 at 1:09 pm Link to this comment By Inherit The Wind, February 25 at 7:24 pm # Dave:….” There is no contradiction. In the OT man was found guilty and sentenced. But they were told by God that a way of forgiveness would be provided. If they would follow the law, they would be forgiven. But they were totally incapable of following the law, and instead made their silly religion out of it, practicing the letter of the law, but ignoring the spirit of the law. The OT also prophesied of a messiah, (saviour) who would come to save them. The religious Jews interpreted that to mean an earthly king who would conquer their enemies, but in fact it was a spiritual saviour who would forgive their sins so they could enter heaven. The image playout of this story was Moses, playing the saviour, and leading the Israelites (the people) out of Egypt (the sinful world) The Israelites needed to sacrifice a lamb and paint their doorjambs with its blood. This was symbolic of the “Lamb of God” having to shed blood for the sins of the people. This act fulfilled the law and the prophets and the people were ready to be saved out of Egypt. Everything that was to happen in the NT was prophesied in the OT. But the Israelites, with their ego, thought they were fullfilling the law themselves, and only saw the messiah as an earthly king. Now the Messiah shows up 2000+ years ago to make a personal appearance to fulfill the prophesy of the “blood of the Lamb of God” dying for the sins of the people. Where each individual had been sentenced to death by the law, the sacrifice of a perfectly sinless one in their place would also satisfy the law, and it was done. At this point, the veil was torn, and the priesthood was essentially ended. Now each man could approach God himself. The purpose was for each one to claim the forgiveness of the sacrifice directly to God, and to pray for others to be saved as well. Where the OT provided salvation through the individual works of following the law exactly, the NT made it possible to be saved by simply acknowledging the grace and forgiveness of God and thanking the Messiah for his sacrifice. So there is no contradiction. The NT is a natural extension of the OT. The OT taught man the harshness of the world which had been become an example of being in bondage or slavery to everything around you. A very hard living. Like the Israelites in Egypt, when they finally pleaded to be taken out, triggering the Exodus. The NT reminded man that there was a God who would not let them live and die in such a hell-hole, and would save them out of “Egypt” by sending a leader such as “Moses” (Christ) The whole exercise is a very natural one as well as spiritual, (the natural only being an image of the spiritual) the idea being you need to know how bad prison and bondage are before you, as a collective mankind, will plead to be taken to a place of freedom. (promised land) You can try to work your way out,(OT) but in the end when you have failed multiple times, you call on God to get you out, and he does it. (NT) And because you realize and remember how bad bondage was, you appreciate your freedom and your God. It is nothing that thousands of parents have not done with their own children, punish them by giving them some thing very harsh (grounding) but before it is over when the child sincerely repents, you offer forgiveness and take them out. It is all part of one reproducing oneself. I know this is a poorly constructed post, rambling on, but I think the points I am trying to make are in there somewhere. The story is not as complicated as most try to make it, and there is not a flaw in it. By Inherit The Wind, February 25, 2010 at 3:24 pm Link to this comment…. Instead you could teach that Jesus was, like Talmudic scholars before and after him, bringing an INTERPRETATION of The Law and its meaning. But, of course, that would mean he was just another part of the long history of Judaism—not good for those that want to establish a new and separate religion and power base. By bonito, February 25, 2010 at 11:27 am Link to this comment Nothing can excuse the way that the Jews have treated the Arabs in Palestine. They have stolen their property, forced them off their land, taken the water rights and the good land that benefits the Jewish state. And then relegates them into a second class existence. The Jews continue to declare that they are a peaceful people and wish peace with their neighbors, while at the same time are annexing and forcing the people of Palestine off of their own property. I guess that the peace the Jews want is on their terms and their terms only, I bet the American Indian would sure as hell like a deal like that. You would think that the US taxpayer would get tired of being assessed billions of dollars a year to pay for the Jews war against the Arabs just so they can have A homeland for their Religion. Why cannot the Jews of the world pay for this Crusade. Just as the Catholics support the Vatican. and did so on the other crusades to the so called holy land. But then I assume the Jews are very good at getting others to pay for what they want, if not then they are certainly good at playing the Jew card, and if that fails, the holocaust card. By Night-Gaunt, February 25, 2010 at 10:38 am Link to this comment .”DaveZx3 Where do you get this “pure” reading from Jesus the Christ? If not in the Bible then where? From your theoi that talks to you and gives you the “real” version of things? In Leviticus he also says “Love one another” but in the full context there aren’t many left to do that. “Only the atheist has to be terribly concerned with this image life and its death, because in his natural mind, it is all that he has.” Yes of course as you should be. Even if reincarnation exists you still want to do good to get off that wheel of incarnation to reach the center or nirvana. Since we seem to have one go we should do right. As for death. You are forbidden to see if there is anything after. (Necromancy) Those pesky shades of the dead and all. However by you discarding the Bible and the accompanying religion of it makes it hard to discuss this with you. (Except when you use it.) You can fly off to whatever place, with no checks, as you feel like it. But then since your personal revelation it too is sullied by your own fleshy human brain hasn’t it? That Fall from Grace and all from Eden. But if you choose atheism, then never expect to understand the principles of the spiritual truth of God. These are antithesis to your natural mind. It has been written of you, that you are “forever studying, but never able to come to the truth.” Maybe so but I didn’t “choose” that is how I am. None of that religious stuff can sway me by their promises alone. Yes a Natural mind born without the active DNA necessary to believe. It just doesn’t happen. I have studied it for some time, many such religions but no conversion experience. A natural variation. Most people are born ready to have a religion implanted. Some change what it is and a few switch between not having one and having one. But then that is science, that is Natural, which you & your ilk find as anathema. But even if you deny God, do not deny the teaching of Christ, because these words can bring peace. If, even as Muslims, Jews and others believe, Christ was a great teacher, then pay attention to the teachings. How can I deny what isn’t there? As for teachings some of it is good others not so much. None of it beyond human understanding or capacity to create it. What about John of Patmos and his Revelations? His portrayal of Jesus was as warrior smiting all in his way with his sword-tongue is very different. Was he wrong too?. Well since most of it was caused when JHVH had his Chosen People and led them to slaughter those on the land that was chosen for them to live on. That is Canaan. Who to blame? the Judeans or JHVH for ordering it? Your not the first one to say that our biological existence isn’t the only or best part of our existence—-prove it. By DaveZx3, February 25, 2010 at 7:08 am Link to this comment By Night-Gaunt, February 23 at 11:31 pm # “The problem is that which Christianity in the Bible do you mean?” I do not mean the religion of Christianity, because it has been infiltrated by the natural mind of men and the evil minds of higher principalities. Religions are deceitful, as they take a legitimate spiritual truth and manipulate it for the sake of committing atrocities and injustices for their own interest. This is what religion is. It is anti-God. No where does Christ state that he is establishing a religion. Men did that.. Only the fool clings onto the old covenant in light of the new. The old is good for teaching and doctrine within a historical context, but no one should wish to go back to the rules of Leviticus when grace and forgiveness have been extended in their place. This is clear within the teaching of Christ, that grace has replaced works. This is not to say that we should commit evil acts, because evil acts are proof that grace and forgiveness have never actually manifested in the life of the perpetrator. Evil acts are proof that one is not a follower of the teaching of Jesus Christ, though he may call himself a christian. Evil acts are proof that the natural mind has not been renewed by the Spirit of God. The natural mind of man considers death as the termination of life, which is correct, but only for the natural or “image” of life. The reality of spiritual life is not terminated. This is the life which only God gives and God takes away. Thus, as King David states, in death, one is only asleep awaiting resurrection. There is no terror in dying for the man of God. Whether you die at age 20 or age 70, it is only a difference of milliseconds when put next to the concept of eternity. And there is no pain in death for the innocent. Only the atheist has to be terribly concerned with this image life and its death, because in his natural mind, it is all that he has. But for the man of God, there is the realization that all lessons learned on this island of insanity, called Earth, are only that, lessons. There is no reality here, only image. Like a “B” movie, everyone being slaughtered, but when the scene is done, they get up and go home to the family and have dinner. Learn your lessons, and when the time comes, be ready to make your choice, eternal life or eternal death. It really is your choice. But even if you deny God, do not deny the teaching of Christ, because these words can bring peace. If, even as Muslims, Jews and others believe, Christ was a great teacher, then pay attention to the teachings. By Inherit The Wind, February 25, 2010 at 5:12 am Link to this comment N-G’s point about the 613 commandments is actually quite true (direct translations are better than the KJB for making this argument). I have made that same argument with Orthodox Jews: If you suspect your wife is cheating, do you feed her dirt and see if her belly swells? (IE: see if she dies and rots) The rules for detecting leprosy, etc. are virtually indecipherable into modern actions. I no more advocate a society based on the 613 than I do on Sharia. And certainly nearly 2000 years of Europe ruled by Christian beliefs shows we don’t want to live under THOSE either! But Torah Orthodox OPPOSED the founding of Israel because Moshiach (the Messiah) is supposed to come and do it. They opposed it from the 1800’s through to and after 1948. Now, today, hypocritically, they justify the WORST excesses by using the same Bible, but now to say what the boundaries of Israel should be. I guess the lesson is NEVER trust a deeply religious person: They will always be an irrational and intolerant fanatical bigot, regardless of the religion. By Night-Gaunt, February 24, 2010 at 10:40 am Link to this comment To me it is always the people who have the ultimate blame for it and religion is the facilitator of it. I would say that the Ba’hi aren’t known for their violence either no matter who steps on them. If I am wrong here then someone please correct me. When you have bad people running things a secular gov’t is no better on that than a religious based one. The price for such power is violence and death. (Not to mention torture or as it is known now “enhanced interrogation.) Just as our original country only favored white men who owned property but we have gone far beyond that to take their words about “equality” to their logical conclusion. But with a great deal of fighting and marching in the streets for it. [Some are still fighting now for equality under the law.] However I would like to go back to the time where all drugs and gun ownership was legal. Now that is something we need to return to…for all! By ardee, February 24, 2010 at 5:51 am Link to this comment Sorry NG, I did not mean to correct anyone, only reinforce the truth, that Christian doctrine is totally anti-violent. ‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’‘’ While Night-Gaunt literally destroyed Dave’s rather absurd contention I would add that , aside from Bhuddism, I cannot think of any religion for which atrocities were not committed. Just so Dave understands that noone is picking on his choice. By Night-Gaunt, February 23, 2010 at 7:31 pm Link to this comment The problem is that which Christianity in the Bible do you mean? Depending on where you read you can find it supporting violence, for pure reasons, and being against it in other places. Almost like it was written by many people and then a committee put it together, but didn’t proof read it very well. Personally I think you just don’t want to see where so much of the sweetness and light sit on an ocean of blood and misery. With more to come. You think Shar’ia is bad? Where do you think it came from? Some examples:. Also— Kill Witches You should not let a sorceress live. (Exodus 22:17 NAB)<Some later translations say it really is “poisoner” not a witch unless they dealt in pharmacology.> Kill Homosexuals “If a man lies with a male as with a women, both of them shall be put to death for their abominable deed; they have forfeited their lives.” (Leviticus 20:13 NAB) <Bisexuals too.>) <How many people would die for this?>) It isn’t looking good for you DaveZx3 and there are some who want Leviticus to be the law of this land too. Do you agree? It is in the Bible and was never been rescinded. I haven’t looked at the Torah yet to see what kind of strictures they have against people. Well enjoy, there are some powerful, rich and connected people who want to force us to live by these laws right here. They are Biblical after all aren’t they? For all their faults our founders made sure we wouldn’t fall into theocracy. But then after 221 years (1789) they are much closer to it than ever before. By DaveZx3, February 23, 2010 at 1:39 pm Link to this comment By Night-Gaunt, February 22 at 5:14 pm # It was directed at anyone who might think otherwise, of which I do not think you are one. By ofersince72, February 23, 2010 at 11:31 am Link to this comment then somebody wants to revisit the crudades when the barbarians from europe went to the middle east to steal some culture because they still didn’t know how to count and thought the world was flat By ofersince72, February 23, 2010 at 11:02 am Link to this comment Western powers have been drawing lines in the desert changing borders, names of states, insterting governments and interfering every since oil exploration. if it weren’t for that nobody would care for a jew or arab By ofersince72, February 23, 2010 at 10:54 am Link to this comment revisit, revision history…. we don’t care about yesterday why 3000 yrs ago lets turn all lands back of to 3300 years at that Jeruselum isn’t anybodys to claim By Jacob, February 23, 2010 at 9:46 am Link to this comment ender, February 22 at 1:10 pm # In fact the overwhelming majority of Israeli Jews strongly support the Zionist ideology. When the Palestinian Jewish community under the leadership of the Zionist movement accepted the UN partition plan, it recognized the existence of the Palestinian Arab people and its right to political self-determination and statehood. Had the Arabs accepted the UN plan, their independent state would have been 62 y old, side by side with Israel. The lives of thousands, on both sides would have been spared and there would have been no refugees. And Golda Meir never said that there are no Palestinians. She said that there is no Palestinian people, based on a lifetime of debates she had with Arab nationalists who vehemently excluded a separatist Palestinian Arab nationalism from their formulations. Here are some examples:In 1956, the PLO’s first chairman, Achmed Shukeiri, declared at the U.N. that:“There is no such thing as Palestine, which is merely the southern part of greater Syria.” In 1974, Syria’s president, Hafez Assad stated:“We must remind the Israeli government that we view Palestine not only as inseparable from the Arab nation, but as part of Southern Syria. Israel is a full fledged member of the UN and recognized as the nation-state of the Jewish people by more than 150 countries. And 194 did not dictate the return of the refugees. It dictated the establishment of a reconciliation commission aimed at facilitating comprehensive peace between Israel and its Arab neighbors. Only one of its fifteen paragraphs alluded to refugees. Most importantly, far from recommending the return of the Palestinian refugees as the only viable solution, it put this particular option on a par with resettlement elsewhere. Those clauses of 194 made it anathema to the Arabs, who vehemently opposed it and voted unanimously against it. The Arab states kept the refugees in camps using them as political pawns instead of absorbing them. The Israeli “revisionist” historian Benny Morris has clearly stated that there was no premeditated plan to expel Palestinians. He wrote that the creation of the Palestinian refugee problem in 1948 occurred as the result of a war-a war that for the Jews was a matter of survival, and which those same Palestinians and their Arab brothers had launched. A war whose aim, which they have never denied, was to destroy the nascent state of Israel, and quite probably its inhabitants as well. But they lost the war, to Ender’s great sorrow. The.On the other hand, not a single Jew was allowed to remain in the areas taken by the Arab armies, an ethnic cleansing par excellence… The Palestinian refugees will be able to settle in the future Palestinian state or third countries, with appropriate compensation (which should be given also to the Jewish refugees from Arab countries). the will not return to Israel proper. On that, both the Israeli hawks and doves agree. And Jerusalem, under the name of Salem, is more than 5,000 y old. There were no Canaanite Arabs then… It has been the capital of only one people, both 3,000 ago and in the last 62 years. By ender, February 23, 2010 at 8:31 am Link to this comment continued. By ender, February 23, 2010 at 8:30 am Link to this comment.’ Have you ever tried the party game where one person tells a story and it’s passed from person to person around a room and at the end the conversation is nothing like the original. Can you imagine what happens after 60-300 and thousands of people participating? The Emperor Constantine who never became a Christian, had his scribes compiled, edited and rewrite what was mostly oral tradition with a few poorly scripted letters. A few hundred years after that, a learned merchant that lives a life of leisure due to marrying a much older but wealthy widow, studies the Jewish religion, and realizes its real problem is its exclusivity. So exclusive they won’t let him join.. By ofersince72, February 23, 2010 at 8:05 am Link to this comment I wish the media would spend as much space worrying about what it means to be a Native American or a young black man stuck in the getto By ofersince72, February 23, 2010 at 7:17 am Link to this comment being a Jewish lawmaker on Capitol Hill means your a whore for the Military Industrial Complex. and that you don’t know of any other way to create jobs unless it is supporting this By ofersince72, February 23, 2010 at 7:13 am Link to this comment To be a Jewish lawmakeron Capitol Hill means you supported the complete destruction of Iraq, helped displace who knows how millions of its citizens, supported the sloughter(sp) of how many of its citizens supported making their places of worship where generals plot murder supported the lies from our media about WMDs even though you were chairman of all armed services committees and intellegence committees. By ofersince72, February 23, 2010 at 6:41 am Link to this comment it means you have the power to campaign for one president and two days later be named chairman of a prestigous sub-committee by the opposing party By ofersince72, February 23, 2010 at 6:37 am Link to this comment To be a Jewish lawmaker on Capitol Hill means to control all armed service committees to keep the outdated NATO ALLIENCE and waste as money in it as posible It means to torpedo all Middle East peace talks. it means you really don’t care about genocide unless its you…............ By ofersince72, February 23, 2010 at 6:26 am Link to this comment I do know what it means to be a JEWISH lawmaker on Capitol Hill…. It means to spend as much money posible perpetuating nonsense and lies as to keep a foot hold in the Middle East to steal oil. It means defending the lies about 1948. or 1967. It means recycling public money into AIPAC. It means….................. everything bad with american foriegn policy By ofersince72, February 23, 2010 at 6:14 am Link to this comment Regardless of what it means to be Jewish President Barrack Obama, owes it to us and to the world to keep just one of his campaign promises.. Quit this silly deadly nonsense and talk himself with the president of Iran and keep these talks going until the Middle East problem is settled, The Iranian president is right in making a mockery of the Atomic Weapon issue and bringing the hypocracy of Western Powers to light in front of the world. Western media distorts and intentionally mis translates almost everything that comes out of his mouth. It is still very embarrassing to me the reception Columbia university gave him. I sure am not afraid of the anti-Semite label that is thrown upon everyone that that speaks rationally about bringing lasting peace to that region. Worry about what it means to be Jewish some other time By PatrickHenry, February 23, 2010 at 4:41 am Link to this comment Irrationality is having a centuries old heritage in a European country, Poland, claiming United States citizenship and claiming alligence to Israel. The Jeruselem - Israel - jews connection is about religion, nothing agnostics and the non-religious should care about. Kind of reminds me of all the posers with 2% indian heritage who show up to claim casino and reservation privilages as a representative of the tribe. By Inherit The Wind, February 22, 2010 at 8:51 pm Link to this comment PH: You are simply irrational. Poland exists. Lithuania exists. Americans whose families hailed from there, especially Poland, made a HUGE stink and CHEERED when Solidarity created, ultimately, REAL independence for Poland, their own, real state. And so did MOST (not all) Americans, proudly! By PatrickHenry, February 22, 2010 at 5:00 pm Link to this comment By Inherit The Wind, February 22 at 10:05 pm # ?” Each of these -Americans hail from a nation where they have or had established family. Most Ashkenazi eastern European jews were established in Poland and Lithiuania for over a thousand years before migrating. Polish-Americans. Now imagine Polish American expats demanding that Israel exist for Polish American expats everywhere because they are hated and everyone is out to get them. (Polish jokes) They will allow some Lithiuania-Americans and of course the inhabitant jews and indigents who live there, for now. By M Henri Day, February 22, 2010 at 2:12 pm Link to this comment As comments of the type «[t]he arrogance of the ostentatiously anti-Israel Diasporites, Jacqueline Rose and Noam Chomsky en tete, suggests that the delusion of the Good Jew, who makes no waves, still has its eager tenants» demonstrate, it is unlikely that an objective discussion of the «Jews» - and in particular, Israel - is possible with Mr Raphael. I therefore limit myself here to suggesting that he consult the entry n?scor in his «large Latin dictionary», to see if n?scere is not noted as the infinitive (both active and passive).... Henri By Inherit The Wind, February 22, 2010 at 2:05 pm Link to this comment Ender: Please explain how 800,000 Palestinians “driven off” their lands has turned into “Jewish terrorist gangs such as Haganah, Palmach, Shtern and Argun used extreme violence to ethnically cleanse millions of Palestinians” Huh? Since when is 800,000 “millions”? And I’m not even going to raise the question of how many were ACTUALLY driven out (“millions” is clearly impossible) of what is now Israel. Let me put it to you this way: Find me ONE anti-Zionist here who doesn’t advocate the total destruction of Israel, either by allowing MILLIONS of Palestinians in who weren’t born there who will then take over and slaughter Jews sooner or later, or by total annihilation, and I’ll acknowledge THAT person is not a racist. There’s not ONE anti-Zionist that has a plan that will prevent the 5 million Jews in Israel from either being slaughtered or made stateless. Criticism of settlement policies in the West Bank? I agree with them—I want Israel to pull the settlements out or warn the residents that they will come under Palestinian Law if they choose to remain, unprotected by the IDF. Criticism of SOME actions taken in Gaza? I’m willing to listen. Blanket condemnation of Israel to reacting to rocket attacks? Sorry, wrong number! Likud and Netanyahu? Bastards, to my mind. Just as dangerous to Israel as Hezbollah, if not more so.? I only know of a few who put Israel over America—and they are in jail where they belong. By Night-Gaunt, February 22, 2010 at 1:14 pm Link to this comment I noticed you corrected me but not John Ellis, why is that? Anyway I was speaking of those who invoke the “eye for an eye” incorrectly to give reason for violence against those who disagree with them. By DaveZx3, February 22, 2010 at 1:04 pm Link to this comment Christianity does not proclaim “an eye for an eye”. That statement was only used to contrast man’s judgements with the teaching of Christ. The exact quote is in Matthew 5:38 and 5:39. Mat 5:38 ¶. By Night-Gaunt, February 22, 2010 at 12:50 pm Link to this comment John Ellis, February 22 at 12:03 pm # Night-Gaunt says: “John Ellis, the Nazis positioned themselves within the mantle of Christianity not Secular Humanism.” “But there is really no difference between Secular Humanism and Christian Humanism, for in practice then accomplish the same thing.” That is correct but then you ignore what you just wrote. Christianity: “Do not use force to overcome evil. If they strike you on the right cheek, turn to them the other.” That is your mistake that ruins your analogy. It is in error. Constantine made sure of that. Humanism is when people treat each other the way they wish to be treated. It can be in any philosophy or theology or none at all. However the Inquisition/Crusades had none as did the 20th century version with the Nazis who had the same kind of mentality. What the USA projects today. Very little humanism except among some soldiers is a few areas of domination. Secular Humanism: “Eye for an eye, tooth for a tooth…life for a life.” How many ways wrong? The “Eye for an eye..” comes from the old Testament doesn’t it? So that is part of Christianity then not Humanism of any kind then isn’t it? A misrepresentation then. Who do you listen to to get this tripe? You will find many Humanists, of all types, being against Capital Punishment (Death Penalty) including me. However I find many Christians who are for the Death Penalty. So how does that fit your twisted world? Until the Jews of Israel consider all non-Jews to be equal to them as people, the same for those too in looking at Jews, no peace will ever come. Until everyone has an equal say and equal standing it will only continue in misery and death for the Palestinians. Job one. Convince the Radical Zionists that they can’t simply take others land because they think the Talmud mandates it. Everyone must respect each others rights or no real, equal and lasting peace will be obtained. Very simple to understand but very hard to accomplish. By ender, February 22, 2010 at 9:10 am Link to this comment ITW attempts to paint any opposition to Zionism as anti-semitic. Rather in fact, Zionism is anti-semitic. A large percentage of Israeli Jews are opposed to Zionism. Zionism is an ugly black stain on the history of an otherwise valiant and humane people. Wolfowitz, Daniel Pipes, Richard Pearl and their ilk are part and parcel of the mammoth AIPAC. Daniel Pipes tried to stifle American academic freedom on US universities’ campuses with his “Campus Watch” to spy on Americans and prevent any debate or discussion of Israel’s racist policies and its grip on US foreign policy. Here is a brief on Israel’s history and policies: “Israel” never ever recognized the existence of the indigenous owners of Palestine: the Palestinian people.Golda Meir once said “What Palestinians?”. Jewish terrorist gangs such as Haganah, Palmach, Shtern and Argun used extreme violence to ethnically cleanse millions. No land or resources are left whatsoever for a Palestinian state: Israel occupied 78%of??? Even the resent Israeli defense minister Yahoud Barrack once said: “If I were a Palestinian I would be a terrorist.” Israel’s economic successes have been possible only because they have confiscated most of the fresh water in the region, then used $billions in American aid to prop up their apartheid theocracy. We have given more than $100 billion in aid, besides billions in weapons, and more than a billion a year is moved from our economy into theirs by private American support groups. More than half of Israeli citizens believe they should return all confiscated lands and make retribution to those 800,000 persons, Christian and Moslem alike, whom were driven off of their ancestral lands in ‘legal’ Israel. We can’t have that discussion here because of the power wielded by AIPAC and Zionist controlled media outlets. A majority of Israelis recognize that the Zionist insistance on ignoring the UN designated borders of Israel and creating a nation with the mythical borders of the Talmud are counter to Israeli survival and morally reprehensible. Any US citizen that promotes the interest of Israel above the interest of this nation should immediately renounce that citizenship and head for the newest kibbutz being constructed on stolen Palestinian soil. By Eso, February 22, 2010 at 9:02 am Link to this comment (Unregistered commenter) Most letter writers here take myth for reality. You think you are climbing a tree, but in fact are bending a birch. Truth is that Judaism and neo-Christianity are a split off arch-Christianity. Neo-Christianity destroyed arch-Christianity with crusades, Zionism—an offshoot of arch-Christian Jews—is about to destroy this civilization by starting a war. By balkas, February 22, 2010 at 8:44 am Link to this comment john ellis, i thought that humanism does not stand for revenge, death penalty, and many other iniquities that the ruling classes perp on us. In add’n, “secular humanism” label tacitly posits a notion that there is also a “religious humanism”. Actually i find all relgions to be against all other religions and against laics. For don’t priests, rabbis and mullahs-ulema say: be with them but not of them. And hadn’t jesus said [or s’mone put words in his mouth]: ye shall always have poor amongst u. Don’t rich peole rejoice over that utterance? And why wld a god create poverty? Or divide us into two groups of people? Jesus had also said: i came to uphold the law and prophets. Which means he approbated genocide of the canaanites [if they ever happened]and approves of what socalled prophets stood for. tnx By ron_woodward, February 22, 2010 at 8:22 am Link to this comment Obama, Progressives and Jews Lumped Together as Nazis CPAC has enlarged the GOP rhetoric to smash mouth proportions. Breitbart to “progressives”: “[W]e are going to come after you so hard you will have no idea what you have awoken in this country” Emboldened by the Muslim victories against the USA, the Muslim immigrants in Sweden have embarked on a hate campaign to rid that nation of Jews. The leftist popular style in Germany is to consider Jews as Nazis. Rush Limbaugh’s great wish is that Obama and the Progressives pilot the American Ship of State underwater sunk by debt and abysmal leadership. He wants to vindicate the Bush Administration. He is banking on fear. There are too many US Progressives who have enlisted in the army of hatred and fear. They are self-destructive. Where is your humanity, Gentlemen? By RdV, February 22, 2010 at 8:18 am Link to this comment Any genetic claim-legitimate or otherwise, smacks of proofs of Aryan pedigree in determining who qualifies for the master race. By balkas, February 22, 2010 at 8:15 am Link to this comment Perhaps i cld clarify ab a human being antihuman by nature and anti an ethnicity. I don’t think, or hope not, nature or god had endowned us or most of us with capabilites to kill humans just because they are humans. So, most humans are not anti other humans. They can be only against what other people say-think-do; justifying the opposition most of the time on rationalization and not necessarily on facts of factual knowledge. However, as i said before, the hellish people [possibly just 1% of the pop]: collumnists, priests, cia-fbi-army echelons, actors, singers, pols, WH, judiciary, ‘educators’ do convince other americans that what they are saying is true. And it is human to defend self.It cld have happened to me. tnx By balkas, February 22, 2010 at 7:46 am Link to this comment Inherit the wind, People kill or expel people mainly because they want their land, basing the theft and murder on rationalization and not any causative factors for such behavior. One cannot be an anti-human to the degree that one cld kill members of another set of people and remain sane-peaceful-happy. Or a denial kicks in. Such as: I cldn’t possibly be this bad; it must be because the other people are pure evil an dtheir land is my land, etc.,and continues on the same rant forever! God or mother nature had ensured that human race survives. Over millennia, peoples everywhere have been conditioned just like pavlov’s dog to react to rationalization [lies] by ‘nobility’ and priestly class of life to identify mere rationalization as factual knowledge. Evocation of great peril by the ruling class seems always to work. US, not being an exception nor a novelty, had to date always succeeded in convincing vast number of their citizens that there was a great peril coming to US shores from countries they may have not even ever heard of. But i am still not anti-humaness of these people; i am solely against what they do. This analyses pertains to all peoples. However,there are two classes of people: ruling and nonruling class. The ruling class i call hell-on- earth people. These people [priests-shamans-nobles] have divided people into less- amd more valued. Once that had been done all ills that befell us over the last 10k yrs on interpersonal and int’l levels are due to this one initial iniquity. ‘Jews’ are no exception. They are being misled; used and abused by own leadership. People who are duped or conditioned like pavlov’s dog are, to me, innocent. Is this a lie, too. tnx By jay1953, February 22, 2010 at 7:44 am Link to this comment John Ellis, February 21 at 10:48 am …” So why not a one-state solution instead of a purely Zionist solution? That is the future. Israel will disappear pure through demographics. Why not now? There is no peace without justice. Give all Palestinians the same rights that Jews have including the right of return. If South Africa could do it, so could Israel. By NYCartist, February 22, 2010 at 5:28 am Link to this comment (ardee, thanks for the compliment re “keen eye"in re Johannes comment…artists are good observers) Johannes comment, the first paragraph of his of Feb. 21, is a perfect example of James Carroll’s nonfiction “Constantine’s Sword”. Carroll puts the history of the Church in a straight line from Constantine to Auschwitz. He starts the book with the controversy of nuns putting a crucifix in view of Auschwitz concentration camp not long ago. (Carroll was a Catholic priest. He is the famous writer, nonfiction and fiction. Son of a US General= his growing up sitting near dad’s desk at and the book on history of Pentagon.) Carroll lays out the history of why Europeans have hated the Jews (and obviously, viz Johannes’ comments, “lapses” as ardee points out re this naked/raw one of his). The basis is that Jews would not convert to Christianity. I boil it down. All the anti-Jew comments, the twisted myths and stereotypes go back to that long history. A close friend is latching on to the new “blame some Muslim from WWII” to get the Church “off the hook” - but Carroll’s analysis proves his point:look at the history of the Church in relation to Jews for about 2 thousand years. My best friend, Marie S., switched from public school to parochial school in 3rd grade, in our working class Italian Catholic and Jewish neighborhood, as some did in the late 1940s. She came home from school one day, (we lived opposite each other) and yelled to me, playing outside, in front of my apartment windows, first floor, “Simi, the nuns said today that you killed Christ.”. I yelled in to my mother, who was in the window in the kitchen, facing the street, “Ma, did we kill Christ?”. “No”, she said. Christianity is angry that Jews refuse Christ as Messiah. All else is embroidery. By PatrickHenry, February 22, 2010 at 4:56 am Link to this comment Jim Crow theocracy for arabs and Palestinians in Israel.;=&size=1&l=e By Jacob, February 22, 2010 at 4:17 am Link to this comment… omop, February 21 at 12:23 pm # Of course Omop’s friend (who happens to be of the faith…) forgot to tell him that the Talmud was written more than 1500 y ago. That it is a collection of discussions on various topics of Jewish law, but not all of the material in every discussion: 1) represents the majority view; 2) applies today. As the translator of the Soncino translation of the Talmud notes:“Not a few of these harsh utterances were the natural result of Jewish persecution by the Romans, and must be understood in that light. In actual practice these dicta were certainly never acted upon”. But they will be used by haters of the Jewish people as if they represent mainstream Jewish thought or behavior. And that is why they repeatedly appear in many anti-Semitic websites and now in this one. By PatrickHenry, February 22, 2010 at 4:17 am Link to this comment By Inherit The Wind, February 22 at 1:29 am # “If you can de-legitimize the group you are attacking right from the start you have won the game right from the beginning.” Yeah typical zionist whining and attempts at censorship to stifle opinions other than your own. You have won nothing. By ofersince72, February 21, 2010 at 9:49 pm Link to this comment You mean there really wasn’t talking burning bush? I always liked that story. You blew it for me By ofersince72, February 21, 2010 at 9:36 pm Link to this comment How does he do that?? Clear English one day,,, broken the next By Inherit The Wind, February 21, 2010 at 9:29 pm Link to this comment Johannes: Next you’ll be saying Jews have horns and signed Satan’s book. I don’t need friends like you. Balkas: The wholesale genocide of a people, ANY people, Jew, Cambodian, Hutu, Tutsi, Darfurian, Kurd, Native American all prove your contention that one cannot be an “anti-semite” to be a lie. One can EASILY tar a whole people with imagined offenses and then try to wipe them out. PH: You live in your fantasy land of conspiracies and hatred. You cannot even CONCEIVE of the idiocy of the idea of Jews being behind 9/11 because you are so twisted with hatred you can’t see straight or think straight. To me, you are no different than Sarah Palin. You just have a different flavor of fantasies you put out. Sadly, I think you actually believe your bullshit. By yours truly, February 21, 2010 at 9:27 pm Link to this comment (Unregistered commenter) So the descendents of the mass conversions to Judaism that took place thirteen centuries ago in Russia and North Africa have the right to return, while the actual descendents of the ancient Hebrews, the Palestinians, are denied the same right? And the justification for this so-called return (so-called because how can one be returning to a land which neither one’s forebears nor oneself ever lived in?) is nothing but a biblical fairy tale? But never mind such facts because European Christianity owes the Jewish people a save haven somewhere outside Europe, so why not Palestine? Except Palestine wasn’t Europe’s to give away. And never mind that this giveaway/takeaway of Palestine has increased, not decreased anti-Semitism, since, what the heck, just from knowing that there’s a Jewish state, Jews can stand up with pride? Except right now the Jew who does stand up has to watch out for haters, so what good this new found pride? As for the one about Israel being a safe haven for Jews, a state under siege by its neighbors cannot be a safe haven, which is one reason why so few Jews outside Israel are interested in immigrating there, another reason being that these same Jews are, for the most part, very happy, thank you, right where they are. As for ridding the world of anti-Semitism, nothing will do more to bring this about than a just and peaceful settlement of the Mideast conflict. Which means that for the Jew, supporting justice for the Palestinians not only is the right thing to do, it’s in his or her best interest. By ofersince72, February 21, 2010 at 9:26 pm Link to this comment He practiced NON-OBSERVANTCY.. By ofersince72, February 21, 2010 at 9:19 pm Link to this comment that durn jew still holdin out on that beer, and my sister married a jew (my youngest) now i have a 25 yr old nephew with a real identity crisis. By balkas, February 21, 2010 at 5:00 pm Link to this comment One cannot be antisemitic- one can be only against what socalled semites do and say. In add’n, euro-asians of the cult comprise dozens of ethnicities. Thus, one caling-deeming self a jew, this can only denote one’s religion;i.e., cult and not one’s humaness. Nature has ensured that we cannot ever be antihuman. That doesn’t mean that if a human steals land expels/murders people that we shld not point this out. I am not afraid being called jew-hater or an anti-semite. In fact, any human who resorts to any name call has by that alone admitted to one’s guilt. Euro ‘jews’ by now have no connection to palestine, hebrews, yehudim, zion and do not have a legal or moral right to palestina. I also think that the s[h]emites of the three cults are being used by world plutos. Proof is found in the fact that ‘zionists’ do not yet have a state for ‘jews’ only nor even an israel. World plutos need badly unrest and ‘terrorism’ everywhere so that they can manufacture ever ‘better’ weapons in order to obtain the planet or as much of it as they can. Tiny, impoverished palestine that god ‘gave’ hebrews as punishment,has no strategic value for nato! tnx By ameriki1, February 21, 2010 at 4:43 pm Link to this comment Israel and the Jewish people will continue to exist inspite of enemies from within and without. From before Josephus there have been self hating and self serving Jews. This is the stock from which kapos are found. Recent genetic evidence has disproved Sand’s Khazar premise. The author of this review should have displayed some self respect and refuted this book that is a compilation of historical distortions and lies. By ardee, February 21, 2010 at 4:28 pm Link to this comment NYCartist, February 21 at 8:17 pm You have a good eye indeed. Ive noted the lapses before but , in the end, this bigot isn’t worth the effort. He has stated his desire to see all Muslims confined to “their own countries” and undoubtedly feels the same way about Jews. ITW Same comment to you , this one is too easy a target after all. By NYCartist, February 21, 2010 at 4:17 pm Link to this comment Oh, Johannes, Your first paragraph of Feb. 21, comment is very clear English. James Carroll’s “Constantine’s Sword” is explains where you beliefs come from. By David Ehrenstein, February 21, 2010 at 2:42 pm Link to this comment (Unregistered commenter) Looks like we’ve got a REAL Anti-semite in here folks—armed with the latest thing in slander. We are to believe that 9/11 is all the fault of the Jews! Perhaps this is best passed over in silence. Unless the owners of this site wish to take action—which may well be advised. By Night-Gaunt, February 21, 2010 at 2:28 pm Link to this comment John Ellis the Nazis positioned themselves within the mantle of Christianity not Secular Humanism. At will show you how close they mingled church and state. That is Lutheran (Protestant), Catholic & the Deutsche Christen group (DC) became the voice of Nazi ideology within the Evangelical Church (the religious right of their day) & approved by Hitler. The main problem I see with Jews is that they are labeled as if their racial stock and religion are synonymous. That is a fallacy. Just look at the Jews of Ethiopia and Russia. And what of the Palestinians who are Semitic but are Christians or Muslims? These were not looked at in this well written but ultimately wrong article. Anti-Judaism is closer to correctness. Since both Palestinians and Israelis are Semitic then are they anti-Semitic to each other? And as for the Khazars as Jews and therefor “false” ones is spoken of in this article as if that was correct. [Certain people use this as a reason to say that Israel is “illegitimate” and therefor can be destroyed.] With the knowledge that Adolf Hitler had one or more Jews in his background, and made sure to eradicate them from his official geneology I would say he would trump Heydrich in Frederic Raphael‘s analogy in the infamy department. We need to stop using identification as if they are barriers between people and as sign posts to whether they are “superior” or “inferior” to some base line. We are equal under the law and as in situ people regardless of our station or success in life. Once we can reach that point then we can start putting this other garbage behind us. Not before. By Inherit The Wind, February 21, 2010 at 12:54 pm Link to this comment PatrickHenry, February 21 at 1:10 pm # Your Yiddish, fine, too bad your loyalties don’t lie with the country of your birth. ********************* You have no idea. You are clueless. You claim to love America but hate everything about it, just like the religious far right fanatics. ********************** You certainly must have your head up your ass not to recognize the mounting evidence that American and Israeli jews were involved in 9/11, but I know where your loyalties really lie. Ethnicity over truth. ************************** The only “mounting evidence” is that you will buy ANY bullshit that disses Jews. Only irrational conspiracy crackpots like you and the neo-nazis could even IMAGINE that Jews, both American and Israeli, would risk alienating THEIR MOST CRUCIAL SUPPORTER if such an asinine plot were discovered. Motive? Plan? Evidence? ALL these things exist abundantly for the Arab extremists who executed it. But for Jews and Israelis? Only a truly demented mind could buy into that. And I don’t need a link to a biased, lying crackpot website! ****************************************. ***************************************** What I FANCY is that your relatives are spinning in their graves because some racist descendant of theirs (you) advocate the views of the guy they died fighting! By PatrickHenry, February 21, 2010 at 12:15 pm Link to this comment By David Ehrenstein, February 21 at 7:52 pm # Your opinion and your entitled to it. By David Ehrenstein, February 21, 2010 at 11:52 am Link to this comment Anyone who thinks Reiner and Brooks are “talentless hacks” is well beneath the level of ACTUAL talentless hackdom. By PatrickHenry, February 21, 2010 at 11:24 am Link to this comment By David Ehrenstein, February 21 at 3:01 pm # No, I don’t remember. I think Reiner and Brooks are talentless hacks and rarely if ever watch their work. They run with the likes of Larry David, whom I bet you think is amusing in his anti-gentile work. Collaberative jews were more responsible for turning in their bretheren than those non jews who tried to help at the threat of their own life. By jay1953, February 21, 2010 at 11:23 am Link to this comment To establish a nation based on the biblical myth and legend of a religious text that is insane. The preposterous notion that an invisible being in the sky was actually talking to a group of Iron Age mystics who catered to the superstitions and ignorance of their followers is stupid. If we put events into chronological historical context, omitting all the religious crap, the modern argument for a theocratic state named Israel is blown full of holes because it lacks the historical continuity to justify the genocidal experiment called Israel today. Most of the pro-Zionist justifications are based on legend, myth and a lot of superstition. Religion is a pathology and in the case of the Israeli experiment, a socio-pathological enterprise. When did Judaism actually become a religion? Biblical mythology contends that Jews are the descendants of Judah. One of of Jacobs 12 sons. The so called Kingdom of Judah was not a nation since the modern concept of nation was unknown at the time 3000 years ago. There was tribalism and city states of which KoJ was a tribe. So how can you apply essentially what was a tribe more than 3000 years ago the status of nation in the modern context? It defies logic and reason. Judah wasn’t a Jew, he was a Hebrew which was one of the many nomadic groups that wandered those lands. So Judah was the first Jew as much as Christ was the first Christian. The fact is that neither were either. Judah wasn’t a Jew but a Hebrew and Christ wasn’t a Christian but he was a Jew. And people kill each other based on this biblical line of BS mythology and superstition? Its all BS. By David Ehrenstein, February 21, 2010 at 11:01 am Link to this comment PactrickHenry: “Relatives of mine died in WWII fighting nazis and helping escaping Jews flee Germany.” Remember the interview with German director “Adolph harlter” on “Carl Reiner and Mel Brooks at the Cannes Film Festival”? “Why in my own home we hid a Jewish family. Sure—we hid ‘em for awhile, and then we turned ‘em over to the Gestapo.” By bozh, February 21, 2010 at 9:41 am Link to this comment (Unregistered commenter) It does seem that if there is antisemitism, there must be also prosemitism. Now let’s see what an antisemite like me says-does and what a prosemite says-does. I protest wars and land theft. I’m calling for the right to be informed, to obtain an enlightening education, health care. A prosemite and nearly all semites hate nearly all shemites, et al. They approbate land theft with intent to murder and expulsion of people from their homes. So,let us be proud when called antis[h]emitic. In any cas, one cannot biologicly be antihuman, one can be only against what a human does or says. Even a cultist like koresh, jones, moshe,jesus, mohammed cannot be antihuman [and live sanely]- they can be only aggainst what we do or don’t do. But all cultists are by far more unsane than almost all noncultists. I do not call cultists “insane” because that wld be an insult to people who are brain-damaged or otherwise incapacitated and cannot deal with daily life;unlike unsane people who can,but can do so much evil! tnx By PatrickHenry, February 21, 2010 at 9:10 am Link to this comment By Inherit The Wind, February 21 at 7:26 am # “And a Jew-hating anti-semite like PatrickHenry always returns to the stereotypes of trecherous, disloyal, cowardly, Jews:” I don’t hate anyone, I leave hate up to people like you who seem to have enough to go around for everyone with your obnoxious prattle. There are some Jews I respect (mainly observant ones) and dog shit posers like you I could scrape off the bottom of my shoe. Your Yiddish, fine, too bad your loyalties don’t lie with the country of your birth. What does it tell you that many observant jews disregard you being jewish at all? just a pretender. I notice the first thing non-observant jewish posters such as yourself do (some on this thread) is broadcast that they are a non-observant or agnostic jews. They are perhaps the only ethnicity that does this (besides christian96) and then take the position of determining all things jewish and falsely label those who they “hate”. Yes, jews are great haters and much commentary has been written about that. You certainly must have your head up your ass not to recognize the mounting evidence that American and Israeli jews were involved in 9/11, but I know where your loyalties really lie. Ethnicity over truth.. By omop, February 21, 2010 at 8:23 am Link to this comment Inherit The Wind, February 21 at 11:15 am # Said: If the Jew did not exist, the anti-Semite would invent him. ANTIS HAVE BEEN AROUND SINCE THE BEGINNING. A few excerpts according to a friend who happens to be of the faith and his readings of parts of the Talmud ” Hitting a Jew is the same as hitting God”. By Inherit The Wind, February 21, 2010 at 7:15 am Link to this comment Wikipedia on Jean-Paul Sartre’s “Anti-Semite and Jew”: Sartre tells of a classmate of his who complained that he had failed the agrégation exam while a Jew, the son of eastern immigrants, had passed. There was – said Sartre’s classmate – no way that that Jew could understand French poetry as well as a true Frenchman. But Sartre’s classmate admitted that he disdained the agrégation and had not studied for it. ‘Thus to explain his failure, he made use of two systems of interpretation… His thoughts moved on two planes without his being in the least bit embarrassed by it.’ (Ibid. p.12.) Sartre’s classmate had adopted in advance a view of Jews and of their role in society. ‘Far from experience producing his idea of the Jew, it was the latter that explained his experience. If the Jew did not exist, the anti-Semite would invent him.’ (Ibid.) Anti-Semitism is a view that arises not from experience or historical fact, but from itself. It lends new perspective to experience and historical fact. The anti-Semite convinces himself of beliefs that he knows to be spurious at best. By Inherit The Wind, February 21, 2010 at 7:08 am Link to this comment John Ellis, February 20 at 11:38 am # A HEBREW — OF THE BLOOD OF ABRAHAM Inherit The Wind says: “I am a Jew… I am an agnostic… the CHRISTIAN myth of Jews shouting for Christ’s death at Golgotha… When the world kills Jews again… they will kill me just for coming from Jews… Palestinians… have convinced the idiot-progressive Left to join neo-Nazis… The ONE place on Earth I am welcome is: Israel. The ONLY place I know I am welcome to flee.” FACTS (1) Tens of thousands of Jews converted to Christianity during the lifetime of the Hebrew authors of the New Testament. *********** So THEY (the authors with an agenda) claimed! Is there corroborating evidence? If recruitment was SO great why was St. Paul willing to compromise on circumcision in order to boost recruitment among the Greeks, who refused conversion if they had to have their foreskins removed? *********** (2) All of the authors of the Bible, both the Old and New Testament, were Hebrews. A Hebrew being one of the blood of Abraham, Isaac and Israel. *********** Again, how do we know this? Because THEY tell us. Nor do we know this about ALL the authors of the NT, because the “books” that make it up were selected long after, in part at the Council of Nicea. ***********(3) All of the authors of the New Testament testified that only because of the Jews threatening to riot did the governor Pilate order the execution of Christ. *********** Again, self-serving interest of the SELECTED authors, with NO corroborating evidence. There is very little evidence that Yeshua Bar Joseph, who became known by the Greek name of Jesus, actually existed (though there undoubtedly were numerous men with such a common name as Yeshua Bar Joseph). *********** (4) Over 95% of Jews are Hebrews, having the blood of Abraham and the extremely high intelligence of Abraham who was the most wealthy man on earth in his day. I am a Jew but I have NO knowledge if I have the Blood of Abraham (whatever that means since we have no DNA remnants of Abraham). I don’t even know if my DNA maps (as it does for many) to the earlier Jews of Palestine at the Diaspora. Further, the statement that Jews are GENETICALLY smarter than other humans is just as racist as PH’s assertions that we are treacherous traitors. Jews APPEAR smarter because of a 3000 year tradition of scholarship. In fact, in the schools here in NJ, a similar stereotype is being created about Asian kids, because THEY are consistently at the top of their classes. Why? DNA? No! A tradition of scholarship and a DEMAND that they do well. A girl my son liked was struggling a bit with the sciences. So her parents sent her to summer school SOLELY to ensure she caught up and got a solid grounding. *********** (5). *********** Yet another disgusting stereotype. The poor shtetl Jews of Fiddler on the Roof were actually THE typical Jew in Europe. Simple people, but still worshipful of scholars. *********** (6) The Jews in Israel again have immense wealth and the highest standard of living on earth, while Palestine, the land they occupy, has about the most enslaved and impoverished people on earth. So if I were a Jew, Israel is the last place on earth I would flee to seeking anything that resembled safety. ************ And where did you get THIS phony statistic? Actually, according to the IMF, Israel is 31st in per capita wealth. 26th according to the World Bank and 36th by the CIA World Factbook. Gaza ranks just above India and the West Bank just below. (India is 134 is the CIAWF). So you are shown to spew the usual racist BULLSHIT stereotypes. By Jacob, February 21, 2010 at 6:22 am Link to this comment Ellis “forgot” that he wrote: “But because of their immense intelligence and wealth, only because of this came the Holocaust.” As I said before that is a typical racist statement. Classical anti-Semitism. And he should go to the nearest library and he will learn that Babylon conquered Judah in 586 and not in 450 as he claims. And he will learn that the Jews came back in 538 (following the declaration of Cyrus) and rebuilt the temple in 516 BCE. During the period of the Second Temple the Jewish people in Judea were ruled by several different empires and underwent many religious and political changes. From the beginning of the era until Judea was conquered by Alexander the Great in 332 BCE, the Persian Empire ruled the region, enabling religious freedom. Although Judea, led by the High Priest, still enjoyed a relative religious autonomy until Antiochus IV’s decrees. Subsequent to Alexander’s death, Judea was under various Hellenistic rules: (Egyptian) Ptolemaic and later Seleucid. As a result of the Seleucid king Antiochus IV’s (Epiphanes) decrees against the Jewish religion, a rebellion led by the priestly Hasmonean family erupted in 167 BCE. Judea, led by the Hasmoneans, who also assumed the High Priesthood, gained full independence at around 140 BCE, which lasted until 63 BCE when Judea was conquered by the Roman general, Pompey. Under Roman rule, Judea remained somewhat independent, as a vassal state, and finally became a Roman province in 4 CE. In 66 CE, the Great Revolt against the Romans broke out, which resulted in the destruction of Jerusalem and the Temple in 70 CE. Still, the Judeans remained the majority in Palestine at least until their next failed attempt at gaining independence in the Bar Kochbah Revolt (132-135 CE). Which means that Ellis, in his ignorance struck out more than 700 y of Jewish history. If there were no Jews there who did the Romans fight in 70 and in 135 CE? Why did the Romans built the Arch of Titus in Rome and what is depicted on it? By David Ehrenstein, February 21, 2010 at 6:11 am Link to this comment My “gut response”? The “gut” is not the brian. My response is Franco Fortini’s essay “The Dogs of Sinai”—filmed by Straub and Hulllet as “Fortini/Cani.” It was the only Straub-Hullet film not invited to the New York Film Festival under Richard Roud’s tenure. By johannes, February 21, 2010 at 3:07 am Link to this comment On this site I geth the same cold shivery feeling as wath I have had when I was a young boy, if you was the only not Jew in an company of Jews, they ignored you as if you where cold air, they same feelings is to be found here. To make my feeling bether understood, I could not play football with two mates of me, In Amsterdam, while the club was only for jews, when my father protested this, and told them that he had saved several Jews in the war, they alloud me in, but than my father forbid me to play in this club,for a principal reasen. Thats the shivery feeling I mean! By Inherit The Wind, February 20, 2010 at 11:26 pm Link to this comment A dog always returns to his vomit. And a Jew-hating anti-semite like PatrickHenry always returns to the stereotypes of trecherous, disloyal, cowardly, Jews: I wouldn’t worry ITW, if we were in power I assure you would be safe, however, Israel would cease recieving military and financial AID, The media and especially Hollywood would be subject to anti-trust legislation especially concerning areas of discrimmination in hiring... It is also good to know where your fleeting loyalties and patriotism lay. Pollard, Nozette, Kadish no doubt thought the same way as alot of the perps of 9/11…. Yes it is paranoid, if every 50 years or so a band of jews commits an act like 9/11 and through other jews in media and banking cover it up with the collusion of governmental non jewish zionists and military opportunists just to blame another religion, country or race just to persue political objectives then I could see your paranoia as justified, but then something like that could never happen now could it. He has hammered the old stereotypes and now the new one: Despite the fact that EVERY shred of evidence put nothing but Arabs on those planes of 9/11, this anti-semite has picked up on the self-serving lie perpetrated throughout the Arab world that it was Jews who did this, to discredit Arabs. As if the US was going to stop supporting Israel? As if George W. Bush and Company weren’t already planning the Patriot Act and war with Iraq? And so the dog returns to his vomitus. Oh, and while you are mentioning traitors of MY ethnic group, PH, you may want to think about those of YOUR ethnic group, especially one SO noted for his treason that his name IN LOWER CASE is synonymous with treason: Vidkun Quisling. During WWII, traitors weren’t called “Quisling"s, they were called “quislings”. BTW, Quisling, like you, took on nazi anti-Semitism. Meanwhile, an admirer of yours, quotes Ayn Rand in support of your anti-Semitism, not realizing, of course, that Rand (Alice Rosenbaum) was, like me, a Jew of Eastern European descent. By Steven Podvoll, February 20, 2010 at 9:40 pm Link to this comment (Unregistered commenter) Please bear in mind, folks, that I’m *not* making any case for or against zionism, for or against anything political, for that matter. I’m merely refuting a major claim in the book about Jewish heritage. We *are* genetically distinct and we can trace our roots to pre-diaspora Palestine. Let’s not conflate politics with biology. Shlomo Sand’s basic premise is *wrong*, regardless of the politics. By Liquor Store Larry, February 20, 2010 at 9:34 pm Link to this comment I meant Sand is full of beans! He HAS gone to great lengths in his pandering in order to sell books though .... hey, wait a minute, there is a *** joke in there somewhere! By Liquor Store Larry, February 20, 2010 at 9:32 pm Link to this comment This whole premise is bigoted on the face and this is basically a phony attempt to lend an academic and intellectual air to the same old anti-Semitic clap trap that has dogged the Jews for several thousand years. Raphael is simply full of beans. By Liquor Store Larry, February 20, 2010 at 7:58 pm Link to this comment Speaking as a non-observant Jew one thing I know for sure. You can not even mention the Jews without bringing the neo nazis out from under their rocks. While I don’t like the idea of any nation predicated on an ethnicity, first tell me of one nation where Jews had not been persecuted and abused and they I will tell you how they ended up in Israel! By PatrickHenry, February 20, 2010 at 5:54 pm Link to this comment The true torah jews argue that agnostic jews are not jews at all. visitorcomments/comment_details.cfm?ItemNo=1276 By Arabian Sinbad, February 20, 2010 at 5:38 pm Link to this comment When one reflects on the fact that Israel is the hybrid child of a Nazi racism mother and an imperialist Anglo-Saxon father one is left with no doubt about why such child is so ugly, immoral and spoiled beyond hope! By David Ehrenstein, February 20, 2010 at 5:24 pm Link to this comment I’m against the Blockade of Gaza and the Israeli settlements on the West Bank. By Basoflakes, February 20, 2010 at 4:16 pm Link to this comment Okay Shlomo, are you for or against the Blockade of Gaza and the Israeli settlements on the West Bank? I don’t care if you are Jewish or Martian, those are the issues that Middle East peace revolves around. By Arabian Sinbad, February 20, 2010 at 4:02 pm Link to this comment By “G"utless “W"itless Hitler, February 19 at 2:44 pm # “Ah yes, Israel: Where the Jews go to become Nazis.” ======================= Yes, I do like the truth of the statement above. However, there is another parallel statement to this, which is: America is where fanatic Christians exploit Christianity, and in their hatred for Islam they like to identify with racist Zionism and like to call themselves Christian-Zionists. By NYCartist, February 20, 2010 at 3:58 pm Link to this comment PurpleGirl, You seem to upset some people who call themselves religious. Good. By NYCartist, February 20, 2010 at 3:53 pm Link to this comment Johannes, I am sad that you do not understand English well enough to understand what I said. By PatrickHenry, February 20, 2010 at 3:18 pm Link to this comment A better timeline, notice Hebrews were around until the kingdoms established 900 - 500 BC, when the jews appeared. By Night-Gaunt, February 20, 2010 at 3:18 pm Link to this comment I wish Truth Dig would fix their number counter so it won’t pass 4,000 then freeze where I can’t do anything at all an lose all that I spent time on typing. Such a shitty thing and this really pisses me off because the mofo’s at TD didn’t fix it last time. It should stop at zero words and not freeze up or allow you to copy and take letters off. Instead you are dead and can’t save your hard work—-at least fix that crap please! By johannes, February 20, 2010 at 3:13 pm Link to this comment To Jacob, How can you write things as you do, you are writing and goming to the point if you are not human, and if other humans did not excist, if you read an peace as this you start to understand some very dark points in our human history bether. By Ira Eisenberg, February 20, 2010 at 2:47 pm Link to this comment (Unregistered commenter) Shlomo Sand’s “The Invention of the Jewish People” offers a wise, lucid and profoundly valuable insight not only into the errant nonsense we Jews have burdened ourselves with, but the tragic course down which Israelis seem so determinedly headed. I came across it by chance in a local book store, was unable to put it down, and eagerly recommend it to all who value historical truth, and especially those who fear the ultimate outcome of the on-going conflict between Israel and its neighbors. However, the choice of Frederic Raphael to review it is unfortunate, as he has precious little to say about Sand’s provocative work that is at all interesting, and his pompous, self-indulgent prolixity is enough to discourage most readers. By WriterOnTheStorm, February 20, 2010 at 2:28 pm Link to this comment Chapeau to PROLE for having the patience to walk us through Raphael’s calculated labyrinth. Sand’s book apparently puts the lie to the Zionist foundation myth, but this is of little consequence, or even interest to Raphael. On this point at least, Raphael would be right. It matters far less if what the Israelis believe about themselves is actually true than the fact that they believe it to be true and are willing to act upon it. There ain’t too many foundation myths that can stand up to scrutiny, but they too often suffice to justify some of the most regrettable tendencies of human nature. Not that it matters to the rest of us either, since, even if the Zionist version of history were true to the letter, it would not morally justify Israel’s current course of action. What irks is the implication that even in their colonial enterprise, the Israelis are somehow better or more justified than any run-of-the-mill technologically superior, wealthier, more powerful tribe that ever scrummed a border with somebody more vulnerable than they. Israelis may believe themselves to be the chosen ones, but word up, it’s not always preferable to be singled out. By PatrickHenry, February 20, 2010 at 2:12 pm Link to this comment Jacob, save the classic diatribes jews use against anyone who disagress with them, they are old and do not work anymore. Actually zionist jews set the early stage for the holocaust. zionism/jewishwar.cfm Abraham, Isaac and Jacob didn’t exist? where’s your proof. I read where the Rothschilds also were the richest jews in the world. Is that nonsense too? As to your timelines, I like to see source materials as well as who wrote them. By Jacob, February 20, 2010 at 1:44 pm Link to this comment Ellis writes:.” That is a typical racist statement. Classical anti-Semitism. Bias and ignorance. To blame the Jews for the Holocaust is despicable. The Jews became a people sometime around 3500 y ago in Canaan. The earliest extra-Biblical source mentioning the name Israel (as a people) is the Mernaptah stele, from around 1200 BCE. Abraham, Isaac and Jacob are mythical figures. There is no evidence that they ever existed. To claim that Abraham was the richest man in the world is nothing but nonsense. The Kingdom of Israel was conquered by the Assyrians in 722 BCE. The Kingdom of Judah was conquered by Babylon in 586 BCE. The Babylonian exile ended in 538 and the Second Temple was built in 516 BCE. The name Palestine was used by the Romans to replace the name of Judea,in the second century CE, following the suppression of the Bar Kokhba revolt. Jews lived there for 1500 y before that. And being Jewish means to be part of the Jewish people, not only to be part of the Jewish religion. There are millions of Jews who are not religious and are members of the Jewish people. I happen to be agnostic and a Jew and a Zionist and very proud of it. By ron_woodward, February 20, 2010 at 1:38 pm Link to this comment To me the striking factor of the book review and most of the responses to it was the common humanity revealed. The Truthdig community engaged in a meaningful discussion of the Jewish experience. For a decade I participated in morning prayers with Holocaust Survivors who became my friends and mentors. We were open to men and women with intellect of any age. We traded in wisdom not easy to come by or to explain. My immersion in the ancient stream of Jewish consciousness will remain. Every man can be a Rabbi if he is literate and wise in the ways of the Torah. Our Bible states succinctly, “Don’t worship idols.” The rest is commentary. Imagine Jews as a resource for mankind. We were common people with the abilities to read and write as witnesses to Cyrus the Great and Alexander. We are not unique, but we have had a unique set of circumstances. By jay1953, February 20, 2010 at 1:07 pm Link to this comment I stated: “The DNA argument in essence is flawed. Any unique rights which are claimed by a group on the basis of race is racist and immoral”. And I might add if its based on cherry-picked DNA evidence it is just as much as dishonest and a lie as the cherry-picked intelligence that was used to justify the invasion of Iraq. By jay1953, February 20, 2010 at 12:56 pm Link to this comment DNA evidence is grasping at straws. There is more evidence contradicting racial jewishness as there is supporting it. The genetic trace that Jews proclaim as proof of racial Jewishness can also be found among other groups that are non-Jews. Mahmoud Ahmadinejad may carry the same DNA being claimed as Jewish proving him to be just as much of a Jew as Ben Gurion. Would that entitle Ahmadinejad to Israeli citinzenship to a little piece of Palestine by displacing a Palestinian from his ancestral home? If we are going to determine Jewishness by DNA we’ll have a population of billions of people entitled to live in Jerusalem. So Judaism is a religion, period. Overstepping that interpretation will only bring violence and bloodshed as it already has done. The whole genetic argument is racist and no more moral and ethical than Nazi racial theories. The Ashkenazi Jews have more in common genetically with eastern Europeans than they do Sephardi Jews in Spain and vice-versa. Any genetic assimilation and wandering is limited at best and is the result of intermarriages between the two groups on religious grounds. There are many people that are white by all appearances but when DNA is analyzed they are found to have black-race or Amerindian traces. Would this make them black or Native Americans? Would that justify them claiming Native American roots and give them rights to open a Casino on an Indian reservation? The DNA argument in essence is flawed. Any unique rights which are claimed by a group on the basis of race is racist and immoral. By Steven Podvoll, February 20, 2010 at 11:53 am Link to this comment (Unregistered commenter) Folks, the DNA evidence is incontrovertible; Jews are indeed a fairly unique and generally isolated blood line. By jay1953, February 20, 2010 at 11:32 am Link to this comment In my view Judaism is neither a culture, a nationality, a race nor ethnicity. It is a religion. By omop, February 20, 2010 at 10:20 am Link to this comment To PatrickHenry’s, comment of February 20 at 1:40 pm #. Well stated PH. For those who sincerely and un-equivocably claim their religious beliefs supercede their loyalties to the principles and norms of the nation/society they spend their lifetimes in. Then they should be encouraged to migrate to the state/society that represents their beliefs. Ann Rynd quote. In this regards Truthdig stands above most of the msm in the US.
http://www.truthdig.com/arts_culture/page2/frederic_raphael_on_the_invention_of_the_jewish_people_20100219
CC-MAIN-2015-40
refinedweb
15,271
68.81
A polling plugin for the Wagtail CMS A plugin for Wagtail that provides polling functionality. Installing Install using pip: pip install wagtailpolls It works with Wagtail 1.3 and upwards. Using Add wagtailpolls to your INSTALLED_APPS. Ensure you add the line from wagtailpolls.views.vote import vote to your urls.py and include the URL url(r'^vote/(?P<poll_pk>.*)/$', vote, name='wagtailpolls_vote'). Define a foreign key referring to wagtailpolls.Poll and use the PollChooserPanel: from django.db import models from wagtailpolls.edit_handlers import PollChooserPanel from wagtail.wagtailadmin.edit_handlers import FieldPanel class Content(Page): body = models.TextField() poll = models.ForeignKey( 'wagtailpolls.Poll', null=True, blank=True, on_delete=models.SET_NULL ) content_panels = [ FieldPanel('body', classname="full"), PollChooserPanel('poll'), ] Then, in your editor, ensure that you have added some polls in the polls section in wagtail admin. You will be able to select a poll from there accessable in the template as you would expect. Templating & Display There are many ways in which you may want to display your poll. wagtailpolls comes with a template tag to assist with this, as well as certain attributes accessible via templating to render each question as a form. Here is an example using all of the tools provided: {% extends "layouts/page.html" %} {% load wagtailpolls_tags %} {% block content %} <h1>{{ self.title }}</h1> <br> {% if self.poll %} <form class='poll' method='POST' action='{% vote self.poll %}'> {% csrf_token %} {{self.poll.form}} <br><br> <input type="submit" value="Vote"> </form> {% else %} No polls added to this page yet! {% endif %} {% endblock %} As shown, the {% vote %} template tag will need to be passed a poll instance to function correctly. You will also need to {% load wagtailpolls_tags %} at the top of the file where this template tag is used. The poll can be rendered with all questions using .form at the end. .form_as_ul and all other form types will also work. If you do select a poll for a page, no fields will display on the form and, upon voting, a message stating that there is no poll to vote on will be displayed. Voting When a vote has been submitted, the server will return a JsonResponse something like: {"total_votes": 11, "total_questions": 3, "poll": "Test Poll", "votes": {"Nah": 10, "Yeah": 1, "Maybe": 0}} With javascript, this data can be used to create a frontend for your poll to your own liking. The voting form also performs some validation. If the voting form is unable to obtain your IP it will return something like: {"poll": "Test Poll", "total_questions": 3, "total_votes": 11, "votes": {"Yeah": 1, "Maybe": 0, "Nah": 10}, "form_error": {"__all__": ["Sorry, we were not able to obtain your ip address"]}} There is also a WAGTAILPOLLS_VOTE_COOLDOWN which is set in your settings. This will only allow users on the same IP to vote at an interval of your choosing. If this is caught, the error will be present in the JsonResponse much like the error above. Additionally, information will be added to the django session (basically cookies will be set) that will help make sure devices are not able to vote twice. When a vote is rejected due to this reason, the vote simply won’t register with no error being returned in the JsonResponse. Settings The following settings can to be set in your settings.py file. WAGTAILPOLLS_VOTE_COOLDOWN This is to be an integer representing minutes, the default is 10 minutes. WAGTAILPOLLS_VOTE_REQUIRE_PERMS A string or list of strings representing the permissions to vote, aka. 'wagtailadmin.access_admin' 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/wagtailpolls/
CC-MAIN-2017-39
refinedweb
592
66.64
Recently there have been a number of questions about drawing techniques. Almost all of these were using code far more complex than is required. This essay tells about how I do drawing in Windows. Being lazy, I wish to do it with as little effort as possible. I've developed some effective techniques over the years. One of the most frequent misconceptions I've seen is that you have to allocate a drawing object in order to use it. So I see code of the form CPen * myPen = new CPen; CPen->Create(...); CPen * OldPen = dc->SelectObject(myPen); ... delete myPen; This is unnecessarily complex code. At least part of the confusion is that the SelectObject method wants a CPen * (or in general, a " Tool *"), which leads programmers to believe that they must supply a CPen * variable. Nothing in the specification of the call requires that the object be allocated on the heap; only that a pointer to an object be provided. This can be done by doing CPen myPen(...); CPen * OldPen = dc->SelectObject(&myPen); ... dc->SelectObject(OldPen); This is much simpler code; it doesn't call the allocator. And the parameter &myPen satisfies the requirement of a CPen *. Since pens and other GDI tools are often created "on the fly" and discarded afterwards, there is no need to allocate them on the heap. When the destructor is called when you leave scope, the HPEN underlying the CPen is normally destroyed--but see below for when it is not! The only time you need to keep objects around is if you need to return them to a context outside your own. For example, the following will not work properly: HBRUSH MyWnd::OnCtlColor(...) { CBrush MyBackground(RGB(255, 0, 0)); return (HBRUSH)MyBackground; } This does not work because upon exiting the context in which the brush was created, the HBRUSH is destroyed, so the handle, when it is finally used by the caller, represents an invalid GDI object and is ignored by GDI. But the following is also erroneous: HBRUSH MyWnd::OnCtlColor(...) { CBrush * MyBackground = new CBrush(RGB(255, 0, 0)); return (HBRUSH)*MyBackground; // or return (HBRUSH)MyBackground->m_hObject; } This is erroneous because a brush is allocated each time the routine is called, and is never deleted. Not only do you clutter up your application space with a lot of unreclaimed CBrush objects, you clutter up the GDI space with a lot of unreclaimed HBRUSH objects. This will eventually crash Win9x, and on NT will eventually crash your application (it just takes longer on NT because you have more space to fill up). In cases like this, you must add a member variable to your class, the background brush, e.g., CBrush * MyBackground; initialize it in the constructor, and delete it in the destructor: MyWnd::MyWnd() { ... MyBackground = new CBrush(RGB(255,0,0)); } MyWnd::~MyWnd() { ... delete MyBackground; } he implicit deletion of objects in the destructor doesn't work if the object is selected into an active DC when it goes out of scope. The ::DeleteObject is called, but because the object is in a DC, this operation fails. Thus the following code leaks GDI objects, and eventually all of the GDI space will will up: void OnDraw(CDC * pDC) { CPen RedPen(PS_SOLID, 0, RGB(255, 0, 0)); ... pDC->SelectObject(&RedPen); ... } At the time we leave scope, the HPEN associated with RedPen is still selected into the DC. The destructor is called, but is ignored. The HPEN is not deleted. The correct solution to this is to be certain that none of your GDI objects are selected into the DC when the destructors are called. The usual way is to save the old object. This means you have to remember to save it, and remember to restore it, and you don't need to save any but the original, for example, { CPen RedPen(PS_SOLID, 0, RGB(255, 0, 0)); CPen GreenPen(PS_SOLID, 0, RGB(0, 255, 0)); CPen BluePen(PS_SOLID, 0, RGB(0, 0, 255)): CPen * OldPen = dc->SelectObject(&RedPen); ... dc->SelectObject(&GreenPen); ... dc->SelectObject(&BluePen); ... dc->SelectObject(OldPen); } Note that only the original pen needs to be restored. But what if there were a loop? You'd need to store the original pen the first time, or always restore it at the end of the loop so the next iteration was correct, etc. And what if you needed to change pen, brush, ROP, fill mode, etc., etc. Very tedious. And what if you decided to change pens earlier in the code? The hazards of compromising what I call "robustness under maintenance" are considerable. The simplest way to handle this is to use SaveDC/RestoreDC instead: { CPen RedPen(PS_SOLID, 0, RGB(255, 0, 0)); CPen GreenPen(PS_SOLID, 0, RGB(0, 255, 0)); CPen BluePen(PS_SOLID, 0, RGB(0, 0, 255)): int saved = dc->SaveDC(); dc->SelectObject(&RedPen); ... dc->SelectObject(&GreenPen); ... dc->SelectObject(&BluePen); ... dc->RestoreDC(saved); } Note that there is no reason to maintain a bunch of variables whose sole purpose is to restore the DC to what it was, and remember which ones, and how to manage them, and a lot of other needless complexity. Just do a RestoreDC. All of the DC state is restored to whatever it was when the SaveDC was done, which means that all GDI objects selected into the DC are deselected. Now when their destructors are called, the underlying GDI objects will be destroyed, because they are not in any active DC. SaveDC and RestoreDC will "nest", in that you can call a function that does some drawing and it can do its own save/restore, or you can just do it inline in your function, e.g., { CPen RedPen(PS_SOLID, 0, RGB(255, 0, 0)); CPen GreenPen(PS_SOLID, 0, RGB(0, 255, 0)); CPen BluePen(PS_SOLID, 0, RGB(0, 0, 255)): int saved = dc->SaveDC(); dc->SelectObject(&RedPen); ... dc->SelectObject(&GreenPen); int saved2 = dc->SaveDC(); for(int i = 0; i < something; i++) { dc->SelectObject(...); ... dc->SelectObject(...); } dc->RestoreDC(saved2); ... dc->SelectObject(&BluePen); ... dc->RestoreDC(saved); } The only requirement is that any GDI objects you create must be at the same or enclosing scope of the SaveDC and must not have their destructors called until after the RestoreDC. I usually solve this by requiring that the GDI objects and the variable for the save/restore be in the identical scope. For example, this will not work correctly: int saved2 = dc->SaveDC(); for(int i = 0; i < something; i++) { CBrush br(RGB(i, i, i)); dc->SelectObject(&br); ... dc->SelectObject(&GreenPen); } dc->RestoreDC(saved2); because when the destructor is called for br it is still selected into the DC. I can't move the creation of br outside the loop because it depends on the loop variable i. There are two solutions to this: the traditional one of saving the old brush and restoring it explicitly, or doing a SaveDC/RestoreDC inside the loop: int saved2 = dc->SaveDC(); for(int i = 0; i < something; i++) { CBrush br(RGB(i, i, i)); CBrush * oldBrush = dc->SelectObject(&br); ... dc->SelectObject(&GreenPen); dc->SelectObject(oldBrush); } dc->RestoreDC(saved2); int saved2 = dc->SaveDC(); for(int i = 0; i < something; i++) { int save = dc->SaveDC(); CBrush br(RGB(i, i, i)); dc->SelectObject(&br); ... dc->SelectObject(&GreenPen); dc->RestoreDC(save); } dc->RestoreDC(saved2); I have not done any performance measurement, so I don't know if SaveDC in a tight loop really matters; evidence suggests that for most drawing routines on most fast computers, this overhead is unnoticeable. but it could show up more seriously in a high-performance inner loop drawing routine. When the save of the old value and restore of the new value are separated by only a few lines, in an inner loop, I will revert to the older mechanism, but if the extent of the code goes beyond more than about six lines I'll use SaveDC/RestoreDC because it is easier to not get this wrong. There are some interesting pieces of code in the GUI for my Hook DLL; it draws a cute picture of a cat. You may find some interesting ideas reading this code as well. The views expressed in these essays are those of the author, and in no way represent, nor are they endorsed by, Microsoft. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/GDI/drawtechniques.aspx
crawl-002
refinedweb
1,379
51.68
A on your behalf. That’s a much more effective strategy for causing mayhem! In the case of a CSRF attack, the confused deputy is your browser. After logging into a typical website, the website will issue your browser an authentication token within a cookie. Each subsequent request to sends the cookie back to the site to let the site know that you are authorized to take whatever action you’re taking. Suppose you visit a malicious website soon after visiting your bank website. Your session on the previous site might still be valid (though most bank websites guard against this carefully). Thus, visiting a carefully crafted malicious website (perhaps you clicked on a spam link) could cause a form post to the previous website. Your browser would send the authentication cookie back to that site and appear to be making a request on your behalf, even though you did not intend to do so. Let’s take a look at a concrete example to make this clear. This example is the same one I demonstrated as part of my ASP.NET MVC Ninjas on Fire Black Belt Tips talk at Mix in Las Vegas. Feel free to download the source for this sample and follow along. Here’s a simple banking website I wrote. If your banking site looks like this one, I recommend running away. The site properly blocks anonymous users from taking any action. You can see that in the code for the controller: [Authorize] public class HomeController : Controller { //... } Notice that we use the AuthorizeAttribute on the controller (without specifying any roles) to specify that all actions of this controller require the user to be authentication. AuthorizeAttribute After logging in, we get a simple form that allows us to transfer money to another account in the bank. Note that for the sake of the demo, I’ve included an information disclosure vulnerability by allowing you to see the balance for other bank members. ;) To transfer money to my Bookie, for example, I can enter an amount of $1000, select the Bookie account, and then click Transfer. The following shows the HTTP POST that is sent to the website (slightly edited for brevity): POST /Home/Transfer HTTP/1.1 Referer: User-Agent: ... Content-Type: application/x-www-form-urlencoded Host: 127.0.0.1:54607 Content-Length: 34 Cookie: .ASPXAUTH=98A250...03BB37 Amount=1000&destinationAccountId=3 POST /Home/Transfer HTTP/1.1 Referer: User-Agent: ... Content-Type: application/x-www-form-urlencoded Host: 127.0.0.1:54607 Content-Length: 34 Cookie: .ASPXAUTH=98A250...03BB37 Amount=1000&destinationAccountId=3 There are three important things to notice here. We are posting to a well known URL, /Home/Transfer, we are sending a cookie, .ASPXAUTH, which lets the site know we are already logged in, and we are posting some data (Amount=1000&destinationAccountId=3), namely the amount we want to transfer and the account id we want to transfer to. Let’s briefly look at the code that executes the transfer. .ASPXAUTH Amount=1000&destinationAccountId=3 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Transfer(int destinationAccountId, double amount) { string username = User.Identity.Name; Account source = _context.Accounts.First(a => a.Username == username); Account destination = _context.Accounts.FirstOrDefault( a => a.Id == destinationAccountId); source.Balance -= amount; destination.Balance += amount; _context.SubmitChanges(); return RedirectToAction("Index"); } Disclaimer: Do not write code like this. This code is for demonstration purposes only. For example, I don’t ensure that amount non-negative, which means you can enter a negative value to transfer money from another account. Like I said, if you see a bank website like this, run! The code is straightforward. We simply transfer money from one account to another. At this point, everything looks fine. We’re making sure the user is logged in before we transfer money. And we are making sure that this method can only be called from a POST request and not a GET request (this last point is important. Never allow changes to data via a GET request).So what could go wrong? Well BadGuy, another bank user has an idea. He sets up a website that has a page with the following code: <html> <head> <title></title> </head> <body> <form name="badform" method="post" action=""> <input type="hidden" name="destinationAccountId" value="2" /> <input type="hidden" name="amount" value="1000" /> </form> <script type="text/javascript"> document.badform.submit(); </script> </body> </html> What he’s done here is create an HTML page that replicates the fields in bank transfer form as hidden inputs and then runs some JavaScript to submit the form. The form has its action set to post to the bank’s URL. action When you visit this page it makes a form post back to the bank site. If you want to try this out, I am hosting this HTML here. You have to make sure the website sample code is running on your machine before you click that link to see it working. Let’s look at the contents of that form post. POST /Home/Transfer HTTP/1.1 Referer: User-Agent: ... Content-Type: application/x-www-form-urlencoded Host: 127.0.0.1:54607 Content-Length: 34 Cookie: .ASPXAUTH=98A250...03BB37 Amount=1000&destinationAccountId=2 POST /Home/Transfer HTTP/1.1 Referer: User-Agent: ... Content-Type: application/x-www-form-urlencoded Host: 127.0.0.1:54607 Content-Length: 34 Cookie: .ASPXAUTH=98A250...03BB37 Amount=1000&destinationAccountId=2 It looks exactly the same as the one before, except the Referer is different. When the unsuspecting bank user visited the bad guy’s website, it recreated a form post to transfer funds, and the browser unwittingly sent the still active session cookie containing the user’s authentication information. Referer The end result is that I’m out of $1000 and BadGuy has his bank account increased by $1000. Drat! It might seem that you could rely on the checking the Referer to prevent this attack, but some proxy servers etc… will strip out the Referer field in order to maintain privacy. Also, there may be ways to spoof the Referer field. Another mitigation is to constantly change the URL used for performing sensitive operations like this. In general, the standard approach to mitigating CSRF attacks is to render a “canary” in the form (typically a hidden input) that the attacker couldn’t know or compute. When the form is submitted, the server validates that the submitted canary is correct. Now this assumes that the browser is trusted since the point of the attack is to get the general public to misuse their own browser’s authority. It turns out this is mostly a reasonable assumption since browsers do not allow using XmlHttp to make a cross-domain GET request. This makes it difficult for the attacker to obtain the canary using the current user’s credentials. However, a bug in an older browser, or in a browser plugin, might allow alternate means for the bad guy’s site to grab the current user’s canary. XmlHttp The mitigation in ASP.NET MVC is to use the AntiForgery helpers. Steve Sanderson has a great post detailing their usage. The first step is to add the ValidateAntiForgeryTokenAttribute to the action method. This will validate the “canary”. ValidateAntiForgeryTokenAttribute [ValidateAntiForgeryToken] public ActionResult Transfer(int destinationAccountId, double amount) { ///... code you've already seen ... } The next step is to add the canary to the form in your view via the Html.AntiForgeryToken() method. Html.AntiForgeryToken() The following shows the relevant section of the view. <% using (Html.BeginForm("Transfer", "Home")) { %> <p> <label for="Amount">Amount:</legend> <%= Html.TextBox("Amount")%> </p> <p> <label for="destinationAccountId"> Destination Account: </legend> <%= Html.DropDownList("destinationAccountId", "Select an Account") %> </p> <p> <%= Html.AntiForgeryToken() %> <input type="submit" value="transfer" /> </p> <% } %> When you view source, you’ll see the following hidden input. <input name="__RequestVerificationToken" type="hidden" value="WaE634+3jjeuJFgcVB7FMKNzOxKrPq/WwQmU7iqD7PxyTtf8H8M3hre+VUZY1Hxf" /> At the same time, we also issue a cookie with that value encrypted. When the form post is submitted, we compare the cookie value to the submitted verification token and ensure that they match. The point of this post is not to be alarmist, but to raise awareness. Most sites will never really have to worry about this attack in the first place. If your site is not well known or doesn’t manage valuable resources that can be transferred to others, then it’s not as likely to be targeted by a mass phishing attack by those looking to make a buck. Of course, financial gain is not the only motivation for a CSRF attack. Some people are just a-holes and like to grief large popular sites. For example, a bad guy might use this attack to try and post stories on a popular link aggregator site like Digg. One point I would like to stress is that it is very important to never allow any changes to data via GET requests. To understand why, check out this post as well as this story about the Google Web Accelerator. It turns out Web Forms are not immune to this attack by default. I have a follow-up post that talks about this and the mitigation. If you missed the link to the sample code before, you can download the source here (compiled against ASP.NET MVC...
http://haacked.com/archive/2009/04/02/anatomy-of-csrf-attack.aspx
CC-MAIN-2013-20
refinedweb
1,548
58.28
#include <MCF1_lp.hpp> Inheritance diagram for MCF1_lp: Definition at line 12 of file MCF1_lp.hpp. Definition at line 25 of file MCF1_lp.hpp. Definition at line 26 of file MCF1_lp.hpp. References branch_history, cg_lp, flows, gen_vars, and purge_ptr_vector(). Unpack the initial information sent to the LP process by the Tree Manager. This information was packed by the method BCP_tm_user::pack_module_data() invoked with BCP_ProcessType_LP as the third (target process type) argument. Default: empty method. Reimplemented from BCP_lp_user. Pack an algorithmic variable. Reimplemented from BCP_lp_user. Definition at line 34 of file MCF1_lp.hpp. References MCF1_pack_var(). Unpack an algorithmic variable. Reimplemented from BCP_lp_user. Definition at line 37 of file MCF1_lp.hpp. References MCF1_unpack_var(). Create LP solver environment. Create the LP solver class that will be used for solving the LP relaxations. The default implementation picks up which COIN_USE_XXX is defined and initializes an lp solver of that type. This is probably OK for most users. The only reason to override this method is to be able to choose at runtime which lp solver to instantiate (maybe even different solvers on different processors). In this case she should probably also override the pack_warmstart() and unpack_warmstart() methods in this class and in the BCP_tm_user class. Reimplemented from BCP_lp_user. Initializing a new search tree node. This method serves as hook for the user to do some preprocessing on a search tree node before the node is processed. Also, logical fixing results can be returned in the last four parameters. This might be very useful if the branching implies significant tightening. Default: empty method. Reimplemented from BCP_lp_user. Evaluate and return MIP feasibility of the current solution. If the solution is MIP feasible, return a solution object otherwise return a NULL pointer. The useris also welcome to heuristically generate a solution and return a pointer to that solution (although the user will have another chance (after cuts and variables are generated) to return/create heuristically generated solutions. (After all, it's quite possible that solutions are generated during cut/variable generation.) Default: test feasibility based on the FeeasibilityTest parameter in BCP_lp_par which defults to BCP_FullTest_Feasible. Reimplemented from BCP_lp_user. Compute a true lower bound for the subproblem. In case column generation is done the lower bound for the subproblem might not be the same as the objective value of the current LP relaxation. Here the user has an option to return a true lower bound. The default implementation returns the objective value of the current LP relaxation if no column generation is done, otherwise returns the current (somehow previously computed) true lower bound. Reimplemented from BCP_lp_user. Generate variables within the LP process. Sometimes too much information would need to be transmitted for variable generation or the variable generation is so fast that transmitting the info would take longer than generating the variables. In such cases it might be better to generate the variables locally. This routine provides the opportunity. Default: empty method. Reimplemented from BCP_lp_user. Convert a set of variables into corresponding columns for the current LP relaxation. Converting means to compute for each variable the coefficients corresponding to each cut and create BCP_col objects that can be added to the formulation. See the documentation of cuts_to_rows() above for the use of this method (just reverse the role of cuts and variables.) Reimplemented from BCP_lp_user. Decide whether to branch or not and select a set of branching candidates if branching is decided upon. The return value indicates what should be done: branching, continuing with the same node or abandoning the node completely. Default: Branch if both local pools are empty. If branching is done then several (based on the StrongBranch_CloseToHalfNum and StrongBranch_CloseToOneNum parameters in BCP_lp_par) variables are selected for strong branching. "Close-to-half" variables are those that should be integer and are at a fractional level. The measure of their fractionality is their distance from the closest integer. The most fractional variables will be selected, i.e., those that are close to half. If there are too many such variables then those with higher objective value have priority. "Close-to-on" is interpreted in a more literal sense. It should be used only if the integer variables are binary as it select those fractional variables which are away from 1 but are still close. If there are too many such variables then those with lower objective value have priority. Reimplemented from BCP_lp_user. Definition at line 14 of file MCF1_lp.hpp. Referenced by ~MCF1_lp(). Definition at line 15 of file MCF1_lp.hpp. Definition at line 16 of file MCF1_lp.hpp. Definition at line 17 of file MCF1_lp.hpp. Referenced by ~MCF1_lp(). Definition at line 19 of file MCF1_lp.hpp. Referenced by ~MCF1_lp(). Definition at line 21 of file MCF1_lp.hpp. Referenced by ~MCF1_lp(). Definition at line 22 of file MCF1_lp.hpp.
http://www.coin-or.org/Doxygen/CoinAll/class_m_c_f1__lp.html
crawl-003
refinedweb
792
52.15
In machine learning, it is a common practice to split your data into two different sets. These two sets are the training set and the testing set. As the name suggests, the training set is used for training the model and the testing set is used for testing the accuracy of the model. In this tutorial, we will: - first, learn the importance of splitting datasets - then see how to split data into two sets in Python Why do we need to split data into training and testing sets? While training a machine learning model we are trying to find a pattern that best represents all the data points with minimum error. While doing so, two common errors come up. These are overfitting and underfitting. Underfitting Underfitting is when the model is not even able to represent the data points in the training dataset. In the case of under-fitting, you will get a low accuracy even when testing on the training dataset. Underfitting usually means that your model is too simple to capture the complexities of the dataset. Overfitting Overfitting is the case when your model represents the training dataset a little too accurately. This means that your model fits too closely. In the case of overfitting, your model will not be able to perform well on new unseen data. Overfitting is usually a sign of model being too complex. Both over-fitting and under-fitting are undesirable. Should we test on training data? Ideally, you should not test on training data. Your model might be overfitting the training set and hence will fail on new data. Good accuracy in the training dataset can’t guarantee the success of your model on unseen data. This is why it is recommended to keep training data separate from the testing data. The basic idea is to use the testing set as unseen data. After training your data on the training set you should test your model on the testing set. If your model performs well on the testing set, you can be more confident about your model. How to split training and testing data sets in Python? The most common split ratio is 80:20. That is 80% of the dataset goes into the training set and 20% of the dataset goes into the testing set. Before splitting the data, make sure that the dataset is large enough. Train/Test split works well with large datasets. Let’s get our hands dirty with some code. 1. Import the entire dataset We are using the California Housing dataset for the entirety of the tutorial. Let’s start with importing the data into a data frame using Pandas. You can install pandas using the pip command: pip install pandas Import the dataset into a pandas Dataframe using : import pandas as pd housing = pd.read_csv("/sample_data/california_housing.csv") housing.head() Let’s treat the median_income column as the output (Y). y= housing.median_income Simultaneously we will have to drop the column from dataset to form the input vector. x=housing.drop('median_income',axis=1) You can use the .head() method in Pandas to see what the input and output look like. x.head() y.head() Now that we have our input and output vectors ready, we can split the data into training and testing sets. 2. Split the data using sklearn To split the data we will be using train_test_split from sklearn. train_test_split randomly distributes your data into training and testing set according to the ratio provided. Let’s see how it is done in python. x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2) Here we are using the split ratio of 80:20. The 20% testing data set is represented by the 0.2 at the end. To compare the shape of different testing and training sets, use the following piece of code: print("shape of original dataset :", housing.shape) print("shape of input - training set", x_train.shape) print("shape of output - training set", y_train.shape) print("shape of input - testing set", x_test.shape) print("shape of output - testing set", y_test.shape) This gives the following output. The Complete Code The complete code for this splitting training and testing data is as follows : import pandas as pd housing = pd.read_csv("/sample_data/california_housing.csv") print(housing.head()) #output y= housing.median_income #input x=housing.drop('median_income',axis=1) #splitting x_train,x_teinst,y_train,y_test=train_test_split(x,y,test_size=0.2) #printing shapes of testing and training sets : print("shape of original dataset :", housing.shape) print("shape of input - training set", x_train.shape) print("shape of output - training set", y_train.shape) print("shape of input - testing set", x_test.shape) print("shape of output - testing set", y_test.shape) Conclusion In this tutorial, we learned about the importance of splitting data into training and testing sets. Furthermore, we imported a dataset into a pandas Dataframe and then used sklearn to split the data into training and testing sets.
https://www.askpython.com/python/examples/split-data-training-and-testing-set
CC-MAIN-2021-31
refinedweb
821
67.35
RPi_mcp3008 is a library to listen to the MCP3008 A/D converter chip, as described in the datasheet. RPi_mcp3008 is a library to listen to the MCP3008 A/D converter chip with a RPi. This library implements the example communication protocol described in the datasheet. Communication is made through RPi SPI port using SpiDev Wiring Connect the SPI data cables in the tables bellow. Choose either CE0# or CE1# to connect to CS. RPi SPI GPIOs MCP3008 Pinout Please check the Adafruit guide on the MCP3008 for more information about wiring Usage RPi_mcp3008 uses the with statement to properly handle the SPI bus cleanup. import mcp3008 with mcp3008.MCP3008() as adc: print adc.read([mcp3008.CH0]) # prints raw data [CH0] It’s possible instantiate the object normally, but it’s necessary to call the close method before terminating the program. import mcp3008 adc = mcp3008.MCP3008() print adc.read([mcp3008.CH0]) # prints raw data [CH0] adc.close() The initialization arguments are MCP3008(bus=0, device=0) where: MCP3008(X, Y) will open /dev/spidev-X.Y, same as spidev.SpiDev.open(X, Y) Both arguments are optional and have a default value of 0 Methods Currently there are two implemented methods: def read(self, modes, norm=False): ''' Returns the raw value (0 ... 1024) of the reading. The modes argument is a list with the modes of operation to be read (e.g. [mcp3008.CH0,mcp3008.Df0]). norm is a normalization factor, usually Vref. ''' def read_all(self, norm=False): ''' Returns a list with the readings of all the modes Data Order: [DF0, DF1, DF2, DF3, DF4, DF5, DF6, DF7, CH0, CH1, CH2, CH3, CH4, CH5, CH6, CH7] norm is a normalization factor, usually Vref. ''' Fixed mode You can also declare the class with a fixed mode, which will make the instance callable and always return the value of the listed modes. Again you can normalize the data with the norm argument when calling the instance. import mcp3008 with mcp3008.MCP3008.fixed([mcp3008.CH0, mcp3008.DF0]) as adc: print adc() # prints raw data [CH0, DF0] print adc(5.2) # prints normalized data [CH0, DF0] MCP3008 Operation Modes MCP3008 has 16 different operation modes: It can listen to each of the channels individually Single Ended or in a pseudo-differential mode Differential Use the table above as the operation mode when calling MCP3008.read(modes) or setting the MCP3008.fixed(modes) mode. (e.g. MCP3008.read([mcp3008.CH0, mcp3008.DF1])) 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/mcp3008/
CC-MAIN-2018-05
refinedweb
427
65.73
Django 1.2 alpha 1 release notes¶ January 5, 2010 Welcome to Django 1.2 alpha 1! This is the first. Backwards-incompatible changes in 1.2¶ CSRF Protection¶ There have been large changes to the way that CSRF protection works, detailed in the CSRF documentation. The following are the major changes that developers must be aware of: CsrfResponseMiddleware and CsrfMiddleware have been deprecated, and will be removed completely in Django 1.4, in favor of a template tag that should be inserted into forms. All contrib apps use a csrf_protect decorator to protect the view. This requires the use of the csrf_token template tag in the template, so is included in MIDDLEWARE_CLASSES by default. This turns on CSRF protection by default, so that views that accept POST requests need to be written to work with the middleware. Instructions on how to do this are found in the CSRF docs. CSRF-related code has moved from contrib to core (with backwards compatible imports in the old locations, which are deprecated). if tag changes¶ Due to new features in the if template tag, it no longer accepts ‘and’, ‘or’ and ‘not’ as valid variable names. Previously that worked in some cases even though these strings were normally treated as keywords. Now, the keyword status is always enforced, and template code like {% if not %} or {% if and %} will throw a TemplateSyntaxError. LazyObject¶ are require support for Python < filter the _state attribute of out __dict__. get_db_prep_*() methods on Field¶ Prior to v1.2, a custom field had the option of defining several functions to support conversion of Python values into database-compatible values. A custom field might look something like: class CustomModelField(models.Field): # ... def get_db_prep_save(self, value): # ... def get_db_prep_value(self, value): # ... def get_db_prep_lookup(self, lookup_type, value): # ... In 1.2, these three methods have undergone a change in prototype, and two extra methods have been introduced: class CustomModelField(models.Field): # ...: get_db_prep_* can no longer make any assumptions regarding the database for which it is preparing. The connection argument now provides the preparation methods with the specific connection for which the value is being prepared. The two new methods exist to differentiate general data preparation requirements,. Conversion functions has been provided which will transparently convert functions adhering to the old prototype into functions compatible with the new prototype. However, this conversion function will be removed in Django 1.4, so you should upgrade your Field definitions to use the new prototype.. Features deprecated in 1.2¶ Email backend API. Old code that explicitly instantiated an instance EMAIL_BACKEND setting,) Specifying databases¶ Prior to Django 1. Old-style database settings will be automatically translated to the new-style format. In the old-style (pre 1.2) format, there were a number of DATABASE_ settings at the top level of your settings file. For example: DATABASE_NAME = 'test_db' DATABASE_ENGINE = 'postgresql_psycopg2' DATABASE_USER = 'myusername' DATABASE_PASSWORD = 's3krit' These settings are now contained inside a dictionary named DATABASES. Each item in the dictionary corresponds to a single database connection, with the name 'default' describing the default database connection. The setting names have also been shortened to reflect the fact that they are stored in a dictionary. The sample settings given previously would now be stored using:). User Messages API¶ The API for storing messages in the user Message model (via user.message_set.create) is now deprecated and will be removed in Django 1.4 according to the standard release process. To upgrade your code, you need to replace any instances. What’s new in Django 1.2 alpha 1¶ The following new features are present as of this alpha release; this release also marks the end of major feature development for the 1.2 release cycle. Some minor features will continue development until the 1.2 beta release, however. CSRF support). Support for multiple databases¶ Django 1.2 adds the ability to use more than one database in your Django project. Queries can be issued at a specific database with the using() method on querysets; individual objects can be saved to a specific database by providing a using argument when you save the instance. ‘Smart’ if tag¶ The if tag has been upgraded to be much more powerful. First, support for comparison operators has been added. No longer will you have to type: {% ifnotequal a b %} ... {% endifnotequal %} ...as you can now do: {% if a != b %} ... {% endif %} The operators supported are ==, !=, <, >, <=, >= use the cached. Natural keys in fixtures¶ Fixtures can refer to remote objects using Natural keys. This lookup scheme is an alternative to the normal primary-key based object references in a fixture, improving readability, and resolving problems referring to objects whose primary key value may not be predictable or known. BigIntegerField¶ Models can now use a 64 bit BigIntegerField type. Fast Failure for Tests¶ The test subcommand of django-admin.py, and the runtests.py script used to run Django’s own test suite, support a new - run before the interruption. Improved localization¶ Django’s internationalization framework has been expanded by locale aware formatting and form processing. That means, if enabled, dates and numbers on templates will be displayed using the format specified for the current locale. Django will also use localized formats when parsing data in forms. See Format localization for more details. Added readonly_fields to ModelAdmin¶ django.contrib.admin.ModelAdmin.readonly_fields has been added to enable non-editable fields in add/change pages for models and inlines. Field and calculated values can be displayed along side editable fields. Customizable syntax highlighting¶ You can now use the DJANGO_COLORS environment variable to modify or disable the colors used by django-admin.py to provide syntax highlighting. The Django 1.2 roadmap¶ Before the final Django 1.2 release, several other preview/development releases will be made available. The current schedule consists of at least the following: - Week of January 26, 2010: First Django 1.2 beta release. Final feature freeze for Django 1.2. - Week of March 2, 2010: First Django 1.2 release candidate. String freeze for translations. - Week of March 9, 2010: Django 1.2 final release. If necessary, additional alpha,.
https://docs.djangoproject.com/en/1.5/releases/1.2-alpha-1/
CC-MAIN-2014-15
refinedweb
1,012
59.9
In this blog I will tell you that how to create dll in c# by using notepad and visual studio command prompt. Here I will provide you a sample algorithm which is helpful for you while creating dll in c#. 1) Create a class for which you want to create a dll. Like following example will be demonstrate a sample class. /* This is a program which give you a demonstration that how to make a dll in c# using notepad and visual studio command prompt. */ using System; //A basic namespace which is required for c# program. public class Employee { public void disp() { Console.WriteLine("This is sample dll created by notepad and c# compiler."); } } 2) Save this class in a file by using valid filename. I had save this file by using Employee.cs for this demonstration. 3) Now compile this file by using following syntax. This will create a dll for Employee class. Here target:library will denotes that a dll should be created after compilation. 4) Now create another file in which create a TestEmployee named class which used this dll. Following example will demonstrate use of this class. /* This is a sample program which will execute Employee.dll */ using System; public class TestEmployee { public static void Main() { Console.WriteLine("Testing of Employee.dll begins...."); Employee emp=new Employee(); //Create an object of Employee class. emp.disp(); //Call disp() method of Employee class. Console.WriteLine("Testing of Employee.dll ends...."); } } 5) Save this file by using TestEmployee.cs . 6) Compile this file by using following syntax. Here reference word tells that Employee.dll is added in program before compiling. 7) Now execute program by writing TextEmployee.exe and see the output.
https://www.mindstick.com/blog/189/creating-dll-in-c-sharp
CC-MAIN-2016-50
refinedweb
283
70.29
Problem : To generate all r-Permutation with repetitions of a set of distinct elements Before we start discussing about the implementation we will go through the basic definitions of Permutations. Then we discuss the method to generate r-Permutations with repetitions with examples, and at last we implement a C Language Program of the problem. Continue reading. Definitions - Permutation: A Permutation of a set of distinct objects is an ordered arrangement of these objects. Let A = {1,2,3} , then {1,2,3}, {1,3,2} , {2,1,3}, {2,3,1}, {3,2,1}, {3,1,2} are the permutations of set A - r-Permutation: An r-Permutation of a set of distinct objects is an ordered arrangement of some of these objects. Let there be n distinct elements in a set, then a permutation of r elements selected from that set is an r-Permutation of the set. Let A = {1,2,3} then {1,2},{2,1}{1,3},{3,1},{2,3},{3,2} are the 2-permutations of set A - r-Permutation with repetitions: An r-Permutation with repetitions of a set of distinct objects is an ordered arrangement of some of these objects, each allowed to be appear more than one time. Let A = {1,2,3} then {1,1},{1,2},{1,3},{2,1},{2,2},{2,3},{3,1},{3,2},{3,3} are the 2-permutations of set A Let there be n elements in a set and we need to generate r all permutations of that set. Then by product rule we get there would be nr such r-Permutations. For example if n = 10 and r = 3, then the first object of the permutation could be any of the 10 objects of the set. For each object in the first position of the permutation, the second position can have any 10 objects of the set, and for each object in the second position there can be also 10 objects in the third position of the permutation. That makes 10 * 10 * 10 = 1000 = 103 permutations. The Method When we count the numbers in decimal number system, we actually generate r-permutation with repetitions with the ten decimal digits (0,1,2,3,4,5,6,7,8,9). Similarly when we count in binary we generate r-permutation with repetitions with the two bits (0 and 1) , and the same with octal and hexadecimal. In case of hexadecimal we use the first 6 alphabet as the last six symbols from the alphabet. Each position in a number runs from its minimum base value to its maximum base value. If there is a set with n symbols and we need to generate all r length permutations of that set, we will simply generate all the r length n base numbers and use the different symbols from the set to denote each different value. This technique is described elaborately with examples below. Description In a number the rightmost digit is called the LSB or the Least Significant Bit or Position and the leftmost digit is called the MSB or the Most Significant Bit or Position. (Here Bit, Digit and Symbols are used as the same thing). The left positions are of more significance and the right positions of a position is of more significance. Now note how a number is counted: Let there be a 4 digit decimal number, and it starts from 0000. First the LSB (0th position) of the number will increase while it does not attain its maximum value, 9 . Thus we count the numbers 0000 to 0009. Next when we attempts to increase 9, we see that it already at the maximum value that a decimal digit can have, so the LSB is reset to 0 and the Next significant digit at position 1 is incremented from 0 to 1 and the number 0009 becomes 0010. Again the LSB increases from 0 to 9, thus counting from 0010 to 0019. In the next count the LSB is again reset and the Next significant position (position 1) is increased making it 0020. Similarly the LSB keeps on counting 0 to 9 and then again 0. At each 9 to 0 reset the Next more significant bit, the 1st digit increments. Let us see some more examples to make the thing clearer. Let us consider the number is 0090 we will attempt to increment it. In this case the LSB will count from 0 to 9, and then reset to 0, then the next significant digit at position 1 attempts to increase, but it is already at 9 the maximum value, so position 1 resets to 0 , this triggers the 2nd position to increment from 0 to 1 thus making 0100. In case of incrementing a number say 0099999, the 0th position will reset to 0 making the 1st position to increment which also resets to zero triggering 2nd position to increment, but this will also resets to zero and the 3rd position increments which also resets making 4th position to increment which again resets and increments 5th position from 0 to 1 and making the number 0100000 . If there is a number 00969 the the LSB will be reset to 0 (it already is on it’s maximum value) and trigger the increment of 1st position making it 6 to 7 thus the number will become 00970. So a position will only increment if its next less significant position resets, and a position will reset when tried to increment it beyond the maximum value it can attain. For an Octal number where each digit’s minimum and maximum attainable values are 0 and 7 respectively. In hexadecimal each digit can attain a minimum of 0 and the maximum of 15. The values from 10 to 15 are labeled with some symbols from the alphabet which are A to F respectively. Similarly say a 26 base number system will run from 0 to 25 (or 1 to 26) and we can assign the lowercase alphabets to each value. The basic thing is a digit in a certain position will increase when the digit on its right side (the next less significant position) is reset, in other words when a digit resets from its maximum value to its minimum the next more significant digit will increase one count. Thus the reset of each digit triggers the increment of the next more significant position digit. Now just think that you are given 10 characters say “abcdefghij” and you are told to generate all 4-permutation with repetitions of this set, that is generate all possible permutations of length 4 with repetitions. There will be a total of 1010 permutations. Can you find the similarity of this problem with counting all four digit decimal numbers from 0000 to 9999 ? If we just relabel the ten digits of the decimal number system with the characters in the set, and instead of printing out digit symbols we print out the characters, then we have the solution. If we label 0 with a , 1 with b , 2 with c …. 9 with j , then the number 1654 will represent the string “bfed” , 6874 will represent “fhgd” etc. So counting up from 0000 to 9999 and labeling each number with the set characters will generate all r-permutation with repetitions of the set. Notice that this problem does not depend on which characters you have to permute, because you can assign any label to the corresponding numbers. This depends the cardinality of the set, that is the number of characters i the set to permute. If there are 8 characters say “oklijhut” in the set to permute then the problem would be same , but the count would be like counting octal or 8 base number and then assigning labels to corresponding digit values. Let us say there are 13 characters to permute, say “qwertyuiopasd” . Then the count would be like a 13 base number system. The minimum attainable value of a digit position would be 0 and the maximum attainable value would be 12 (0 to 12 are thirteen values). The LSB would increase from 0 to 12 and then reset to 0 making the next significant position to 1, and the counting would proceed as described above and then labeling each value with corresponding labels from the character set will generate the r-permutations of the set. If a number in 13 base is (6)(10)(9)(12)(5) then we get “ypost” after labeling each value with its corresponding symbol from the set. Generally, if the set with which we need to generate r-permutation with repetitions has cardinality n , then we need to generate all r length numbers of base n number system, and then label each values of the number system with the elements of the set. Thus any arbitrary length of set can be permuted by generating all n base numbers with r length. For example if the set consists of all alpha (upper case and lower case) numeric symbols and we need a 5-permutation with repetitions, then we will count all the 5 length numbers of a 26 + 26 + 10 = 62 base number system (a total of 62 5 = 916132832 permutations). Program Implementation The complete source code and it’s description is shown below /* Program to generate all r-Permutation of a set with distinct element * This code is a part of */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> /* type values used in init_char_set() function */ #define UPPER 1 #define LOWER 2 #define NUM 4 #define PUNCT 16 #define ALPHA 3 #define ALNUM 7 #define ALL 23 #define CUSTOM 32 /* pre defined char sets used in init_char_set() function */ #define UPPER_CHAR_SET "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #define LOWER_CHAR_SET "abcdefghijklmnopqrstuvwxyz" #define DIGIT_CHAR_SET "0123456789" #define PUNCT_CHAR_SET "~!@#$%^&*()_+{}|[]:\"<>?,./;'\\=-" #define MAX_CHARS 150 #define MAX_GUESS 20 #ifndef NUL #define NUL '' #endif /* Function Prototypes */ void permute_rep (const char *set, int n, int r); char *init_char_set (short int type, char *custom); int *init_perm_array (int len); void make_perm_string (int *perm, const char *set, char *perm_str, int len, int print_flag); /* Main Function, Drives the permute_rep() function */ int main (void) { char *set = NULL, custom[MAX_CHARS]; int r; printf ("\nr-Permutation with repetitions.\n"); printf ("Enter String Set To Permute: "); scanf ("%s", custom); printf ("\nLength Of Permutations (r): "); scanf ("%d", &r); set = init_char_set (CUSTOM, custom); printf ("\nPermutation Symbol set: \"%s\"\n", set); permute_rep (set, strlen (set), r); printf ("\nfinished\n"); return 0; } /* Function Name : permute_rep * Parameters : * @ (const char *) set : Pointer to the symbol sets to permute * @ (int) n : The length upto which the set would be used * @ (int) r : The length of the generated permutations * Return Value : (void) * Description : Generates all the Permutation with repetitions of length 'r' from the 'set' upto length 'n' . * Optionally prints them in stdout. */ void permute_rep (const char *set, int n, int r) { int *perm; char perm_str[MAX_CHARS]; int i, j; perm = init_perm_array (r); while (perm[r] == 0) { for (j = 0; j < n; j++) { make_perm_string (perm, set, perm_str, r, 1); perm[0]++; } perm[0]++; for (i = 0; i < r; i++) { if (perm[i] >= n) { perm[i] = 0; perm[i + 1]++; } } } } /* Function Name : init_char_set * Parameters : * @ (short int) type : The inbuilt type values to select character sets. * 'type' could be: * 1, 2, 4, 16, 32 or any of these values ORed. These are #defined * @ (char *) custom : Pointer to a custom symbol set to initialize. type should be 32 in, * else this pointer is ignored. * Return Value : (char *) : Returns a pointer to the initialized character set * Description : Allocates and initializes a pointer with a string of symbols to be permuted, and returns it */ char * init_char_set (short int type, char *custom) { char upper[] = UPPER_CHAR_SET; char lower[] = LOWER_CHAR_SET; char num[] = DIGIT_CHAR_SET; char punct[] = PUNCT_CHAR_SET; char *set; set = (char *) malloc (sizeof (char) * MAX_CHARS); if (type & UPPER) { strcat (set, upper); } if (type & LOWER) { strcat (set, lower); } if (type & NUM) { strcat (set, num); } if (type & PUNCT) { strcat (set, punct); } /* Remove redundant elements from custom string and build set. If input set is "hello" * then it will be reduced to "helo" */ if (type & CUSTOM) { int i, j, k, n = strlen (custom), flag; for (i = 0, k = 0; i < n; i++) { for (flag = 0, j = 0; j < k; j++) { if (custom[i] == set[j]) { flag = 1; break; } } if (flag == 0) { set[k] = custom[i]; k++; } } } return set; } /* Function Name : init_perm_array * Parameters : * @ (int) len : The length of the array * Return Value : (int *) : A pointer to the allocated permutation array * Description : Allocates and initializes with 0 an array, which is used for generating 'r' base numbers */ int * init_perm_array (int len) { int *perm; perm = (int *) calloc (len + 1, sizeof (int)); return perm; } /* Function Name : make_perm_string * Parameters : * @ (int *) perm : Pointer to the current permutation count state * @ (const char *) set : Pointer to the symbol set to be permuted * @ (char *) perm_str : Pointer to the string containing permutation * @ (int) len : The length of permutation * @ (int) print_state : A flag. If true prints the permutation in stdout, else does not. * Return Value : (void) * Description : Makes a NULL terminated string representing the permutation of the symbols, * from the 'set' represented by 'perm' state. This labels each position of 'perm' * with the symbols from 'set' makes a string and returns it. * Also prints the string if 'print_state' is true. */ void make_perm_string (int *perm, const char *set, char *perm_str, int len, int print_state) { int i, j; for (i = len - 1, j = 0; i >= 0; i--, j++) { perm_str[j] = set[*(perm + i)]; } perm_str[j] = NUL; if (print_state) printf ("%s\n", perm_str); } Description of permute_rep() function: This receives a const char type pointer set which contains the symbols which are to be permuted, the value of n an integer which indicates the length of the set to be used (generally strlen(set)) and also determines the number system base which would be counted, and it accepts r that is the length of the generated permutations (the value of r in r-permutation). So if we want to generate 4-permutations with repetitions of a set “qwerty” then the call would be Note: If you think to use the whole length of the string you pass everytime, then you may calculate strlen(set) inside permute_rep() and omit passing n. permute_rep ("qwerty",sizeof("qwerty"),4); The permute_rep() function first executes the perm = init_perm_array(r) which allocates an integer array of length r and returns its base address. The outer while loop controls the count and limits the length of the count to r. This works like this: When r = 4 , we are only using position 0,1,2 and 3 . After the count 09999 the next number is 10000 , that is the count goes beyond position 4 making position 5 to change to 1, indicating all 4 permutations have been generated. This acts as a control flag. That is why an extra cell is allocated to perm in the init_perm_array() function. This loop also prints the generated permutation with the help of make_perm_string() (passing print_state = 1). The first for loop counts the LSB from its minimum to maximum. The next statement perm[0]++ makes the LSB exceed it’s maximum attainable value then making it invalid (for the current). That is if n = 18 (when permuting 18 element set) then the first for loop will count the LSB from 0 to 17 and the next statement will take the LSB from 17 to 18, making it invalid. This invalid position is detected in the next for loop and it is reset to zero and the next significant place is incremented and checked again for an invalid value. That is the second for loop is used to reset and increment all the positions except the LSB. This loop runs until the number has not end or it has detected a valid value. Other Functions: Two other functions are defined which are make_guess_string() and init_char_set(). The make_perm_string() function simply labels the values in the perm array with the different symbols from set. Although the make_perm_string() constructs the string in reverse order, it is not needed. the print_state parameter tells the function if to also print the generated permutation or just return the string. This could be helpful generating brute force password hashes and attempting to crack a password. init_char_set() initializes the set of symbols to be permuted. This is made for easy using. Inbuilt types are defines like UPPER, LOWER,NUM,PUNCT,ALNUM,ALPHA,ALL and CUSTOM. Calling this with set = init_char_set (UPPER, set, NULL); will allocate and initialize the pointer set with uppercase alphabets set = init_char_set (UPPER | LOWER, set, NULL); or set = init_char_set (ALPHA, set, NULL); will allocate and initialize set with uppercase and lowercase alphabets set = init_char_set (CUSTOM, set, "qwerty"); will allocate and initialize set with “qwerty” This function also removes redundant symbols from the custom set. that is “aabbccdd” is considered “abcd” . The last parameter is ignored if type is not CUSTOM. A 20 Digit Decimal Counter We will make a 20 Digit or more digit decimal counter with the help of the above process. It can simply be seen that is the set = "0123456789" and r = 1,2,3 ... 20 , the above program could generate this thing. for ( i = 0; i < n; i++) permute_rep (set, strlen(set), i); What we will do is reduce the above function and design to only count decimal numbers, and remove additional functions to label the permutations and save computation. We will initilize the permutation array with the symbols itself. Because the decimal symbols (0 to 9) are adjacent in the ASCII table we can just increment normally to get the next count, and reset is done with the ASCII value of 0. In this case we need to generate permutation in a certain order, for example a decimal counter which is capable to count 20 digit number or a 50 digit number. Normal data-types would overflow several times counting such a large number. which assigns line numbers to a very long file. This method is applied in the GNU cat program with the -n or -b switches are on. A sample of a 20digit decimal counter is presented below: void generate_line_number (void); #define LSB 20 /* pre calculated value 22 - 2, skipping the last two places */ #define LENGTH 23 /* length is 22 valid number length 20 last two positions for null and \t */ char line_number[LENGTH] = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', /* Upper 10 digits */ '\r', ' ', ' ', ' ', '\r', ' ',' ', ' ', ' ',' ', /* Lower 10 digits */ '0', '\t' /* Null terminated and tab character */ }; void generate_line_number (void) { int i; line_number[LSB]++; if (line_number[LSB] == ':') { for (i = LSB; i >= 0; i--) { if (line_number[i] == ':') { line_number[i] = '0'; if (line_number[i - 1] <= ' ') line_number[i - 1] = '1'; else line_number[i - 1]++; } else break; } } } Note that in this implementation the LSB is the rightmost position. The line_number is a pre-formatted array. Each time this function is called it generates a new decimal number. This code was used in the cat equivalent program of Whitix OS project. This does not needs to construct the permutation, as the line_number is already a NULL terminated and tab aligned string. Update Information 14.10.2009 : Source code update. Memory leak fixed. Pingback: All Combinations Without Repetitions « Phoxis Pingback: wcat : A GNU cat implementation | Phoxis Hello, The code you posted , some symbols were lost because the wordpress.com system replaced them with the HTML equivalent code. I have edited then and tried to compile the code. It does not compile here it shows some errors. Probably the first two statements would be cin and not cout . After i fixed the errors, when i ran the code it showed me Segmentation Fault . That means there is some invalid memory usage. Could you please fix the code, so that i can add that here ? And please remove conio.h, as most of the readers would have problem with that library. Pingback: Gerando Permutações-r com Repetição em C | Daemonio Labs Thank you . i will try it could you please tell me step by step what to do to generate permutations using this code? how to use it ? note that this specific problem implements an r-permutation with repetitions. That is, a set of symbols is given, the routine would select all possible subsets of k symbols, and selection of one single symbol from the set is allowed. Each selected symbol is treated as a unique even they may be identical. This can be used to form a counter of base n as the last decimal counter describes. For a description of the code, probably i have tried to writeup an exhaustive description of the process. I would tell you to go through the code. If you need to permutation of n symbols without repetitions, ie, something like : 123, 132, 213, 231, 312, 321 which is something like an n-permutation without repetition, selecting all the symbols and rearranging them in unique positions, then this is not the implementation.
http://phoxis.org/2009/08/01/rpermrep/
CC-MAIN-2013-20
refinedweb
3,460
55.88
> From: Conor MacNeill [mailto:conor@ebinteractive.com.au] > > Dun? > My original comments allowed for this. In other words, I could live with inherited values of properties being mutable in subprojects. This is not the same as allowing changing the value of a property withing a projact execution. > If we adopt mutability of properties then we lose the ability for the > command line or parent build to override the values set up in > the subbuild. > This was the original reason that properties were made immutable IIRC. > Not necessarily, the "-D" or <param>/<property> nested element will behave as the property being defined in the context of the callee. The way I see this to be implemented is very much in the spirit of function invocations: Properties are set only once in the context of execution of a project. A context is started by running ANT or executing the <ant> or <antcall> tasks. - A property has a value if it is defined in some of the callers execution contexts. - A <property> task will associate a value for the property in the current context, if there is no value associated in the current context. - The "-D" and nested <param>/<property> elements of <antcall>/<ant> associate the value in the context of the callee (subproject). which means the subproject cannot change the value of the property. But notive that sub-suprojects can change it, since they are not local. The main problem with this approach is that there is no way to unset a variable in a subcontext. This to me is the basic problem with allowing inheritance. > We also have the issue of managing the property namespace to > avoid name > conflicts. I think this can be a problem with Unix > environment variables > too. > This is true. Any inheritance mechanism will have to dealt with this issue. This is the only thing making me ambivalent about inheritance. >"/> > Actually, if we are going to have mutable properties then I would argue that we are doing scripting. And then we can go into the scripting wars once again :-( > > > >. > I am one who uses those techniques. In many cases you need to be able to set properties (e.g., configure directory locations) based on things like <available>. If all property definitions where at the project level, there is no way to do any conditional configuration. Please, do not tell me that I should use some other configuration tool to generate the values for properties. Unless that tool has the current power of ANT, it wont be able to do what is needed. But if it has the power of ANT, why would anyone need ANT for? Jose Alberto > Conor >
http://mail-archives.apache.org/mod_mbox/ant-dev/200011.mbox/%3C635802DA64D4D31190D500508B9B04104E0F7E@dcsrv0%3E
CC-MAIN-2016-18
refinedweb
442
65.73
The concept of builders is rather popular in the Groovy community. Builders allow for defining data in a semi-declarative way. Builders are good for generating XML, laying out UI components, describing 3D scenes and more… For many use cases, Kotlin allows to type-check builders, which makes them even more attractive than the dynamically-typed implementation made in Groovy itself. For the rest of the cases, Kotlin supports Dynamic types builders. Consider the following code: import com.example.html.* // see declarations below fun result(args: Array<String>) = by p { for (arg in args) +arg } } } This is completely legitimate Kotlin code. You can play with this code online (modify it and run in the browser) here.): fun String.unaryPlus() { children.add(TextElement(this)) } So, what the prefix + does here is it wraps a string into an instance of TextElement and adds } // ... } com.example.htmlpackage (a in attributes.keys) { builder.append(" $a=\"${attributes[a]}\"") }") { public var href: String get() = attributes["href"]!! set(value) { attributes["href"] = value } } fun html(init: HTML.() -> Unit): HTML { val html = HTML() html.init() return html } © 2010–2017 JetBrains s.r.o. Licensed under the Apache License, Version 2.0.
http://docs.w3cub.com/kotlin/docs/reference/type-safe-builders/
CC-MAIN-2017-43
refinedweb
192
59.4
Ok, this is what I am trying to do, I am trying to make it so that every time you press the left mouse button of your mouse, the litttle space ship will fire something.........This is somewhat what I have......... This is how the message loop is organized...... So obviously we will be going through the message pump every time until the window's killed.......I have this on winproc.So obviously we will be going through the message pump every time until the window's killed.......I have this on winproc.Code://message pump for(;;) { //look for a message if(PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { //there is a message //check that we arent quitting if(msg.message==WM_QUIT) break; //translate message TranslateMessage(&msg); //dispatch message DispatchMessage(&msg); } //run main game loop Prog_Loop(); } //clean up program data Prog_Done(); //return the wparam from the WM_QUIT message return(msg.wParam); case WM_LBUTTONDOWN: { Fire(); return (0); }break; This would call Fire which is a function outside of the Program loop and everthing. Well my problem is that when I press the mouse it goes to fire and then it stays there, it doesn't go back to the Prog_Loop or so it seems nothing it's updated......How can I make it so that I can press the mouse and then keep on going with the message loop any idea? I know I am doing something seriously wrong, thanks in advance.
https://cboard.cprogramming.com/game-programming/18492-help-window-gets-killed.html
CC-MAIN-2017-13
refinedweb
240
71.55
UNIX stuff that makes no sense ( the rant) First of all, I love Linux. I have used it exclusively since about 1994 (yeah, the last Windows I actually used for real was WfW 3.11). Let's see how it makes no sense. The Bin Your system has /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin 6 different binary locations. What sense does it make to split bin and sbin? It only makes it harder for regular users to use tools the can need, like netstat and ifconfig. As for /bin and /usr/bin, it makes little more sense, if at all. Sure, put a basic, functional system outside /usr, because /usr can be a network FS. Well, who does that? I mean, I have seen all-local and all-network systems, but I have never seen a /-local, /usr-remote system in ten years. And I suppose someone does it, but that doesn't mean it makes sense. If you want a real, functional, unbreakable system you can use in case of network failure: use a separate partition. Or use a Live CD. Or use a floppy. All of those are more resilient than your /. As for /usr and /usr/local... that's just a throwback to when people were scared of installing software. People should install packaged software anyway. The Libs /lib /usr/lib and /usr/local/lib. Just as much sense as the above. The variable /usr and /var. Here's what I think I heard: /usr is for unchanging application data (bins, libs, docs, etc.) /var is for mutable data (logs, spools, caches). That way, you put /var in a separate partition and if apps run amok, your / doesn't fill. Well... ok, I suppose. Except that the right way to handle that is to make sure your apps don't freaking run amok! Say, logs? Rotate them by size, not by date! Spools? Use disk quotas, and maximum sizes! Caches? They should be space-limited. And all services should be kind enough to figure out when your disk is about to burst and do something graceful with it. Finally: if your /var fills, all your services will crash just as hard as if / filled. So what's the point? That you can log into the crashed box and fix it? You can do that with a full /, too. The root of all evil We live with the concept of a single almighty admin. Why? If every service application had a single point of configuration and monitoring (ie: /etc/app and /var/service/app (in runit ;-) and /var/log/app, it would be trivial, using ACLs, to allow partial management of the system. Sure, there would be a real root for stuff like password management and such, but that's not so bad. Why has no one bothered doing this? Permission to barf The Unix permission system is at the same time harder and less powerful than ACLs. That only on the last two years it has become practical to use ACLs on Linux, and that still you can't count on them in every distro is... ugly. I could go on, but... I think you get the idea. Coming some day: a proposal to fix the mess. Unfortunately, as much as I like Linux/Unix systems I have to agree. All of this becomes especially pointed at the desktop/client end of thing unfortunately. For the diff between /usr and /var: it should be possible to mount /usr read only (to be more secure), while /var should be mounted rw. Indeed. I think the filesystem mess is not too bad though. Unless you are a developer, you shouldn't care about it. That's what I like about Linux, you don't have to give a damn about where your software goes, the package manager will take care of it for you. Of course its better to make sure that you only run sane apps that don't make 10GB log files, but you can never guarantee that. Amen on the ACL's though. I've always thought that the Windows way of handling permissions was much more intuitive (not that ACLs are a Windows tech, but they do have a user friendly implementation). About mounting /usr read-only: Well, unless it's also remotely mounted, it adds zilch more security, since mount -o remount,rw /usr usually succeeds. About it only mattering to developers: Maybe. Too bad I am one ;-) Oh, and you can guarantee that apps don't make 10GB logs. Yes you can. Just use a log service that rotates based on size, and don't rely on the app at all :-) You also forgot /usr/X11R6/bin/ and /usr/X11R6/lib. That said, have you looked at GoboLinux's file system hierarchy? It's something that I wish would catch on with the rest of the Linux world. In short, / looks like this: /Depot - Dumping ground for stuff like music and pics that should be shared between users. /Files - for fonts and non-application files /Mount - like /mnt /Programs - All programs and libraries go here /System - /boot, /etc, and /var rolled into one /Users - like /home Very nice, and works quite well. Version 012 should be coming out within a week or two. Here's that proposal to fix the mess: instead of making an archaic and obtuse directory structure to support flexibility in how you partition your drive, use *directory merging* to merge directories on many partitions into one. That way you can have one standard directory for binaries, but those binaries could still be stored in different partitions, even different computers over the network. Decouple the filesystem namespace from the underlying storage. Directory merging is possible on Linux today using some experimental kernel patches, I believe. It should be fairly easy to make those patches standard in your new distro (which sounds interesting to me). This is your chance to do something radically different that makes your distro unique. If you want to go even more radically further, then I think a KIOSlave-like URL scheme (http, ftp, etc) should be added to the kernel at the lowest level. But that's probably a job for kernel hackers, not KDE guys or even distro makers... The reason you have /usr/[s]bin and /[s]bin is that quite often /usr is a seperate local partition. You need basic tools to deal with things that prevent you from mounting /usr. This is why fsck is in /sbin and why everything in /bin and /sbin are statically linked. He who does not understand unix, is doomed to re-implement it over and over again... your line of argument leads straight to Windows or the old MacOs, don't you think? The binaries are all in one place (Program Files), the user data files too (Documents And Settings), and you have ACL, pseudo-filesystems, no real root, etc etc. Now, if you really want all this stuff, why don't you just use Windows? Are you saying that Microsoft is just getting wrong the implementation details? Don't get me wrong, I'm not flaming here: it's refreshing to think critically about decades-old conventions and solutions. However, you can't just come around and trash the place, especially when is too easy to do so: the Linux Standard Base is so young that only big-biz distributions care to follow it, and everything that's in there has a reason to be like that; a reason that has been heavily discussed for decades by people more knowledgeable than you and me. The filesystem hierarchies have been discussed forever, people have gone away to do their own things (MacOs, Windows, Be, Amiga, etc etc) and eventually they keep coming back to the unix way of filesystem organizaton because of its flexibility and power :) The split-permission thing sounds like SELinux. Giacomo, Your argument is riddled with logical fallacies. 1. The excluded middle, or slippery slope: just because somebody supports changing some aspects previously baked into Unix, you can not immediately assume that they will end up with Windows. This is tantamount to saying that Unix was handed down from mount /dev/sinai , and can never be improved. 2. Roberto has been using Linux for 11 years, and he isn't allowed to have an opinion on what he considers braindead? 3. Putting a smiley at the end of a completely idiotic statement makes you look like a dilweed :) JD: I know /usr is sometimes a separate local partition. I say that you gain nothing from that, though. And you forgot the fallacy of argument from authority ;-) If your /usr gets so bad you can't mount it, you can just as easily use a rescue CD (or a wholly separate system in another partition) and have a much better rescue environment than your crippled / (for example, / will not have sshd!) Giacomo: Well, I grok unix just fine. However, I see that lots of things are just crud. They are done that way because they have been done that way for 20 or 30 years, and noone wants to change them. In fact, we want to cristalyze them, with things like the LSB, which would provide a real reason to implement this silly structure: "We do it that way to be LSB compatible". We are turning unnecessary complication into necessary complication :-( And finally, I just can't take seriously a preference for unix permissions over ACLs just because windows had ACLs first :-P Peter: thanks for the gobolinux pointer, never heard of it! "Well, unless it's also remotely mounted, it adds zilch more security, since mount -o remount,rw /usr usually succeeds." Unless the /usr partition is on some read-only media, which may not be mounted read-write physically. And about the /usr - /var issues : /var and /tmp are often written to and often read from, and additionally to that, /tmp shouldn't mandatorily survive reboots. /usr is, OTOH, often read from and seldom written to. So you may put /usr on some "quick read - slow write" device, /var on "quick read - quick write" device, and /tmp on some volatile device. It is completely irrelevant when speaking about desktops, of course, but it may be relevant for servers / embedded systems. "and mount /etc /var and /tmp from the other medium"... That would be a bit more complicated. Normally, you wouldn't mount /etc, for you use /etc/fstab to mount things. The same applies to /bin and probably to /lib - utilities from there are used to mount things. So, to reformulate and widen my thoughts about various /*'s: /bin /etc /lib - all of these should be where the / is. /sbin - may be united with /bin. Although, I think I understand why there are /sbin and /bin - you may not want a regular user to run some administrative command unintentionally /var - read often, write often, survives reboots. /usr - read often, write seldom ( or not at all), survives reboots /tmp - read often , write often, not required to survive reboots Alex, in the case of a fisically read-only medium, or a slow/fast difference, I guess you should try to put /bin and /lib there, too. So, your best bet is to put / there, and mount /etc /var and /tmp from the other medium. In that case, there is nothing gained from a separate /usr, either. Sorry guys, I didn't want to look like the dork I am :) it's just that... every once in a while this "UNIX filesystem doesn't make sense" conversation shows up somewhere, and someone goes along and makes its own version, and it's ok, everyone is free to fork what he wants... but after all, the hierarchy is a just a bunch of _conventions_; that is, if you can't get enough people to agree with you, you can have the best solution ever, and still go nowhere. So far, it's been quite difficult even to get to the LSB. On the windows comparison I certainly went too far, but... I don't know, when this topic comes up I just can't stand it and lose a bit of fairness :) The filesystem hierarchies have been discussed forever, people have gone away to do their own things (MacOs, Windows, Be, Amiga, etc etc) and eventually they keep coming back to the unix way of filesystem organizaton because of its flexibility and power huh? Those OSes didn't "keep coming back to the unix way [...] because of its flexibility and power", except perhaps for some compatibility with unix programs that expect it. It is funny that the Amiga should be mentioned. It's filesystem made sense and also used a kind of union filesystem in places for handling things like libraries. This feature was called "assign"s. (like LIBS:). You could have multipe library dirs and still refer to a library file by "LIBS:intuition.library" and it just worked and it was sane and this was 20 years ago. -- Simon RE Acls. Acls are not my favorite security primitive. Take a look at capabilities. Not Posix caps ( these suck beyond belief), but real capabilities. Of course, this really does mean saying goodbye to posix. Doomed to repeat it again indeed.. The difference between /bin and /sbin is... "if a normal (not a system administrator) user will ever run it directly, then it must be placed in one of the "bin" directories. Ordinary users should not have to place any of the sbin directories in their path." -- and -- "/sbin should contain only binaries essential for booting, restoring, recovering, and/or repairing the system" The difference is simple, /bin for everyone, /sbin for root. and as far as /usr/(s)bin goes.. the same argument applies, except for the fact that on some systems the root is a tiny fixed filesystem which doesn't have enough room (intentionally or not) to store all of the userspace applications. Again, sbin in /usr is for administrative tools and should not be needed by regular users. as far as /usr/local goes.. just because you haven't seen it, doesn't mean that some of us don't have large clusters of systems that share a common '/' and '/usr' that are remotely netmounted at boot time.. Why store separate (dozens, even hundreds) of copies of all that data when one copy will suffice. We mount /usr read-only and the boxes mount /usr/local (system-specific) for application or system -specific code dependant on the role of the server. I'm sure some of you will call me old fashioned, but some of these architectural structures are in place for a reason.. don't like it.. that's fine -- go use GoboLinux, your own custom layout, or MacOS. Just don't throw away a system you don't understand. I agree about your remarks regarding ifconfig and netstat, but not to the extent a regular user should be given access to the sbin folder, but the opposite.. those tools have a use in userland, thus they should live in /bin or /usr/bin.. /sbin is an administrative toolbox, and should contain only those tools necessary for the administrator to do system-critical tasks necessary for basic operations. I think ifconfig is in /sbin by default more for security reasons than anything else.. on a large multi-user system, there is *no* reason for a regular user to have a use for any of the tools in /sbin. And you've misinterpreted my layout a little, the point of the network-mounted filesystems is to eliminate a disk (common cause of failure) from hundreds of servers.. these servers may be dynamically added or removed from the application pools they serve at will without a significant negative impact on the applications they are 'assigned-the-role' of. This would be overly time-consuming and have no where near the flexibility if the boxes (or at least their drives) had to be removed from the racks. The basic system image is only 1-2GB, the /usr directory is 5-10GB in size, and the /usr/local is dependant on the server role.. between 1GB and 15GB.. the /usr stuff in certain cases could be merged with the root (/) stuff, but in our case the root stuff is all i686, where the usr dirs for some server classes are P4 optimized, and others are K7 Optimized. This gives us the benefit that we only need 1 core boot/root image for our net-boots, and it will start all of the servers.. The only special app resident on the root partition is our config-fetch tool/scripts that choose the right /usr (depending on the arch) and will report to our cluster masters to find the necessary appropriate role (/usr/local). Anyways, I didn't mean to insult, I just found the article critical of a system that has its base in large computing environments. Just my $0.02 Thinko: You are being silly. You assume I don't understand just because I disagree. I, on the other hand, could claim that you agree just because you don't think. Would that be nice? No. For example, for the existance of /sbin, you simply repeat what you have been told. What difference does it make that a normal user doesn't have ifconfig or netstat in his path? They perform a useful function for a non-admin, too!. And *what* is gained from not having them in your path? What's the freaking point? If /usr and /usr/local is only necessary for large installations, then why not make it optional, and use it only when it makes sense, instead of making it the default? BTW: you could do pretty much the same thing with a combination of system-imager, local storage, and a profile-based package manager. It's not like basic system setup is taking all your storage, right? The apps you have on /usr and /usr/local amount to how much? 10GB? 20GB? 50GB? What's the disk size? If we make then the default, we force everyone to live with it. If we make it optional, then only those sysadmins of large installations need to care (and they are better equipped to handle it anyway). Well, my desktop is not a large computing environment ;-) We are installing millions of boxes with a scheme that's only really useful for a few thousand of them. And I still am not sure I understand why there should be stuff in /sbin. AFAICS, anyone can try to run it, it's just not in the default PATH. >And I still am not sure I understand why there >should be stuff in /sbin. AFAICS, anyone can try >to run it, it's just not in the default PATH. Well, "chmod 700 /sbin" it's easier than chmoding particular binaries. Well, why would I chmod 700 /sbin? Unless you have a SUID binary there, users can do no harm by trying to run the stuff. Speaking of GoboLinux - there is Rubyx distro, which takes some ideas from Gobo, and its latest incarnation - Heretix, which comes back to the unix root, by using "normal" names like /bin, but putting packages under /pkg tree. Nice to check out too. I use kernel trustees patch on my old server, which lets you define permissions very granularly. I haven't checked SELinux yet, but i guess it should be possible to do the same with it.
http://ralsina.me/weblog/posts/P291.html
CC-MAIN-2020-34
refinedweb
3,263
71.34
Hi, I have just started learning C++ and while messing around with calling and returning I have unexpected results. As far as I understood it I should be able to use the values returned from other functions outside of 'main' and use them as I would any 'int' value as shown below. But it loops through the program twice for some reason and then doesn't display the user input information as I thought it should. Any pointers would be appreciated. Code:#include "stdafx.h" #include <stdlib.h> #include <iostream> using namespace std; int age() { int ageyouare; cout << "Please enter your age: "; cin >> ageyouare; cin.ignore(); system("cls"); return ageyouare; } int yearofbirth() { int year; cout << "Please enter the year you were born: "; cin >> year; cin.ignore(); system("cls"); return year; } int main() { int y; int a; yearofbirth(); age(); y = yearofbirth(); a = age(); cout << "You are: " << a << "\n"; cout << "And you were born in the year: " << y << "\n"; char f; cin >> f; return 0; }
http://cboard.cprogramming.com/cplusplus-programming/133424-newbie-needs-advice-please.html
CC-MAIN-2014-23
refinedweb
163
68.7
On Wed, 5 Oct 2005, David Leimbach said:>> 1) make namespaces joinable in a sane way>> 2) wait for the shared subtree patch>> 3) make pam join the per-user-namespace>> 4) make pam automount tmpfs on the private /tmp> > I'm not sure what you mean by a joinable namespace. I also am not> sure I want them :-).They are namespaces which processes can join. Right now you can doit by chrooting into /proc/{pid}/root, but this is, as Bodo said,not a very sane API.Without this, a user starting two sessions gets two namespaces,which is profoundly counterintuitive from the user's POV.> I think of namespaces as being fundamental to the process model and> that they are inherited from the parent and new ones are created in a> sort of COW fashion [or at least have similar behavior].Yes, but you can change them too (that's what e.g. mount() is for!)> You might want a session namespace instead of a joinable per-process> namespace but I think that might be a slightly different point of> view.I think that's the idea; a filesystem holding namespaces that you'reallowed to chroot()
http://lkml.org/lkml/2005/10/5/243
CC-MAIN-2016-22
refinedweb
198
69.92
>>. There’s a company that reverses these for their 3rd party usb-controller, and they release their code. check out (I’m just a user, not affiliated with the company in any way) regarding patching into the buttons: what about using solid state relais? I did something similiar for my home automation setup. One main difference as far as i can see: I use an arduino with an ethernetshield as the main controller, so no computer is necessary. I can interface with the system over usb, ethernet, IR or 868 mhz FSK radio. A few reference: Jee labs: Particularly this post: Some german info about the protocol (The pictures might be enough otherwise i will gladly translate)örke.de/Funksteckdosen.htmörke.de/ARCTECHsteckdosen.htm Bye, NsN JeeLabs has one solution to these outlets too. It’s an Arduino with RFM module and software to encode in different protocols. Check it out, JeeNode is very nice. BTW: Instructabliss reports a login failure. It looks like the instrucabliss site either requires its own login, or its proxy login to instructables.com has been suspended. Is instructables.com getting greedy AND snarky? Very cool! It’s always a pain when things aren’t just a simple 0 or 1. ralfm: It even works with a multiplexer, with that you can switch between floating and either Vin or GND. But basically this is a waste of ports and a pain in the butt (because of resistance, soldering, etc), especially if you need radio communication anyways. use opto-isolators across the button contacts – just verify the relative +/- polarity, and connect the opto-isolators accordingly. Nice, but why not just jumper the original buttons with a PIC? :) Yep – we made something like that a few months before – 12 Channels, IPhone Interface and disco mode ;) – based on a velleman k8055, a few relais, transistors and tons of isolation tape ;) And Perl … perl is a weapon Quite inexpensively? It’s cool that he used a bunch of his time to learn this, so there’s good return (knowledge) on capital investment (time == money); however, you can do this with a $20 X10 kit that probably costs less working time to buy than the time spent hacking this system. So, while I give him credit for being awesome, one day when he has kids he’ll be like “man, there’s got to be a solution I can just buy.” These have been reverse engineered before: I even have something like this running for years now. I always wondered if I could just build a very high powered sender, direct it to some big building and cycle through all the available codes… @foo: nope, the ones used at “das labor” are different models with a completely different protocol. the model chr used is a pretty good choice if you’re in germany, as they appear at local stores every few months for only 15€ a kit. I did a similar setup before, using arduinos: X 10 is slaughtered by noise. The most useless thing I ever owned. It couldn’t turn a light on in the same outlet, reliably. Looks good, but surely if it’s a tri-state matrix you could just the fact that avrs can do high/low/high impedance? That you can’t hack the buttons is rubbish, so you can’t pull them to ground? then you simply use an electronic switch to tie the pins, don’t tell me that’s so impossible, $0.80 part will do it. This was nicely done though and is more ‘classy’, but to say the other method can’t be done or is so hard is just silly surely. I recently bought $6 chinese infrared controlled outlet which performed suprisingly well. The outlet programs to any existing remote control easily. It is definitely an alternative method worth looking into. It certainly isn’t as functional as a radio controlled one, but for the price it can work very well for some setups. Does anyone know how much overhead in power usage these things give? Is it constant ~9W or is it dependent on how much the appliance that is pluged in draws.? There’s an interesting project called “Ethersex”. It’s a universal firmware for ATMega’s, that routes tcp and udp over FSK RF modules, ethernet, USB, CAN, RS485, etc. It also supports sending ASK codes using a RFM12 RF module, so you can use it to switch radio controlled outlets. It’s easy to build a USB to RF stick, or an Ethernet to RF gateway, without writing a single line of code. Unfortunately, the website is in german, but the build environment is english. This looks same as tellstick (usb-stick based of a ftdi-chip, pic cpu and rf-chip). The only problem I found was the latency (seems that the codes are sent >2 times at 9600bps which gives latency at the receiver, the driver is however ‘open source’ ^^, and there is one more… The button patch hack can be done on those remotes quite easily. I did it a couple of years ago on my set of RF plugs (exactly like the ones pictured, but UK plugs/sockets). A quick scan across the keypad with a multimeter gave me the matrix layout, then I installed a pin header soldered to the required connections, then stuck it down using hot glue and cut a small square in the remote access it easily but keep it functioning normally when not in use. Then I made an interface board using two cheap HEF4051 8-channel multiplexers to simulate the key presses. The whole hack was quite quick to do. I can document it with pictures/schematics if anyone’s interested. I already have a setup like this at home. Granted, I didn’t do the hard work myself. Below is a link that explains how to control these sockets with an Arduino and a 433Mhz transmitter. Sample code included. It’s all in Dutch, though… i have a dozen philips remote controlled outlets that i want to change to channel F…so one remote works for all of them. is this easy? how’s it done? I am very new to this but what i am trying to acomplish is to control my ir and rf devices ( power sockets and light switches) with my galaxy tab 10.1 via direct blutooth or wifi connection without using a computer or any other device. Basicly what i want is that a device that can revieve my commands over bluetooth or wifi and send them via rf and ir ( according to what device is). i want to control eveyrthing that can be remote controlled by my tablet. According to what i gather and learn it is possible to crate a ir and rf controller to be able to used by smartpohe or comuter. The part that i dont understand is how to remove computer and internet from this build. I would love it if u could help me or send me in the right direcion… Handy library for remote controlled outlets: I can’t wait to integrate the “electric imp” with remote controlled sockets, either by hacking the physical remote or transmitter and protocol emulation. It will be possible to order an imp compatible arduino shield. The code is ready, we’re just waiting for the hardware!!
http://hackaday.com/2011/01/26/reverse-engineering-radio-controlled-outlets/?like=1&source=post_flair&_wpnonce=1a35c759c1
CC-MAIN-2014-10
refinedweb
1,231
70.23
Command Prompt¶ A prompt is quite common in MUDs. The prompt display useful details about your character that you are likely to want to keep tabs on at all times, such as health, magical power etc. It might also show things like in-game time, weather and so on. Many modern MUD clients (including Evennia’s own webclient) allows for identifying the prompt and have it appear in a correct location (usually just above the input line). Usually it will remain like that until it is explicitly updated. Sending a prompt¶ A prompt is sent using the prompt keyword to the msg() method on objects. The prompt will be sent without any line breaks. self.msg(prompt="HP: 5, MP: 2, SP: 8") You can combine the sending of normal text with the sending (updating of the prompt): self.msg("This is a text", prompt="This is a prompt") You can update the prompt on demand, this is normally done using OOB-tracking of the relevant Attributes (like the character’s health). You could also make sure that attacking commands update the prompt when they cause a change in health, for example. Here is a simple example of the prompt sent/updated from a command class: from evennia import Command class CmdDiagnose(Command): """ see how hurt your are Usage: diagnose [target] This will give an estimate of the target's health. Also the target's prompt will be updated. """ key = "diagnose" def func(self): if not self.args: target = self.caller else: target = self.search(self.args) if not target: return # try to get health, mana and stamina hp = target.db.hp mp = target.db.mp sp = target.db.sp if None in (hp, mp, sp): # Attributes not defined self.caller.msg("Not a valid target!") return text = "You diagnose %s as having " \ "%i health, %i mana and %i stamina." \ % (hp, mp, sp) prompt = "%i HP, %i MP, %i SP" % (hp, mp, sp) self.caller.msg(text, prompt=prompt) A prompt sent with every command¶ The prompt sent as described above uses a standard telnet instruction (the Evennia web client gets a special flag). Most MUD telnet clients will understand and allow users to catch this and keep the prompt in place until it updates. So in principle you’d not need to update the prompt every command. However, with a varying user base it can be unclear which clients are used and which skill level the users have. So sending a prompt with every command is a safe catch-all. You don’t need to manually go in and edit every command you have though. Instead you edit the base command class for your custom commands (like MuxCommand in your mygame/commands/command.py folder) and overload the at_post_cmd() hook. This hook is always called after the main func() method of the Command. from evennia import default_cmds class MuxCommand(default_cmds.MuxCommand): # ... def at_post_cmd(self): "called after self.func()." caller = self.caller prompt = "%i HP, %i MP, %i SP" % (caller.db.hp, caller.db.mp, caller.db.sp) caller.msg(prompt=prompt) Modifying default commands¶ If you want to add something small like this to Evennia’s default commands without modifying them directly the easiest way is to just wrap those with a multiple inheritance to your own base class: # in (for example) mygame/commands/mycommands.py from evennia import default_cmds # our custom MuxCommand with at_post_cmd hook from commands.command import MuxCommand # overloading the look command class CmdLook(default_cmds.CmdLook, MuxCommand): pass The result of this is that the hooks from your custom MuxCommand will be mixed into the default CmdLook through multiple inheritance. Next you just add this to your default command set: # in mygame/commands/default_cmdsets.py from evennia import default_cmds from commands import mycommands class CharacterCmdSet(default_cmds.CharacterCmdSet): # ... def at_cmdset_creation(self): # ... self.add(mycommands.CmdLook()) This will automatically replace the default look command in your game with your own version.
http://evennia.readthedocs.io/en/latest/Command-Prompt.html
CC-MAIN-2018-13
refinedweb
653
65.52
Shankar, from yt.mods import * fn = "RedshiftOutput0002" pf = load(fn) halos = HaloFinder(pf) halos.modify["hop_circles"](self, hop_output, max_number=None, annotate=False, min_size=20, max_size=10000000, font_size=8, print_halo_size=False, print_halo_mass=False, width=None) halos.write_out("HopAnalysis.out") hop_circles makes a plot of hop haloes on an existing projection. You need to create the projection first. So... ... halos = HaloFinder(pf) pc = PlotCollection(pf) p = pc.add_projection("Density",0) p.modify["hop_circles"](halos, max_number=etc...) pc.set_width(1.0, '1') pc.save('plotname') My advice is, when you try to use a new function, you should figure out what it's doing and what the inputs are. For example, even if your input was formatted correctly, you haven't defined 'self' or 'hop_output' before you use them in the function call, and it would have failed anyway. Also, 'self' is a special variable in python that is never used as an argument of a function call. Good luck! _______________________________________________________ sskory@physics.ucsd.edu o__ Stephen Skory _.>/ _Graduate Student ________________________________(_)_\(_)_______________
https://mail.python.org/archives/list/yt-users@python.org/message/4SCHXVYNU7CSZQXVEWK3MH3VZFVTGOQ2/
CC-MAIN-2022-40
refinedweb
173
51.75
So I've gotten help already with this program, but I can't seem to get it to print. I know I have to call the methods containing the println statements, but I'm not sure how to go about this. Below is my program. It is supposed to read a string, and then print out the letters in the string and how many times that letter appeared in the string. Then, at the end, it should print out the most frequent letter and how many times that letter appeared. Thanks in advance! import java.util.*; public class LetterDriver{ public static void main(String[] args){ Scanner scan = new Scanner(System.in); String tScan= " "; while(tScan.length() > 0){ tScan = scan.nextLine(); } } }public class LetterProfile { int scoreboard[] = new int [26]; private int index; private int next; private int largest =0; private int largestindex =0;(scoreboard[a]>largest) largest = scoreboard[a]; largestindex = a; } return(char)largestindex; } public int printResults() { largestLength(); System.out.println(largestLength()); } }
http://www.javaprogrammingforums.com/whats-wrong-my-code/25743-program-not-printing-anything.html
CC-MAIN-2016-30
refinedweb
161
73.98
There. Finally, Lua supports userdata as one of its fundamental data types. By definition, a userdata value can hold an ANSI C pointer and thus is useful for passing data references back and forth across the C-Lua boundary.. Several special entries can go into a meta table. In this example, the most important one is __index. This entry contains a table or a function that Lua will consult if its associated table does not have a requested entry. Consider a meta table M whose __index entry is a table P. If M is the meta table for table T, whenever code requests an entry in T that does not exist, Lua will consult table P to see if it has the requested entry. P of course could have its own meta table data. Also, a table can be its own meta table, in which case entries such as __index will be in the table and will show up in table iterators, for example, but will otherwise behave in the same way. Given this, the Lua programmer can now indulge in some actual object-oriented programming by providing a way to create "instances" of a Hello object. The base object looks like this: Hello = {} function Hello:sayhello() print("Hello "..self.Name) end Add a constructor, New, with: function Hello:New(name) -- Create a new, empty table as in instance of the hello object local instance = {} -- Initialize the Name member instance.Name = name -- Set the Hello object as the metatable and -- __index table of the instance. This way -- the Hello object is searched for any member -- (typically methods) the instance doesn't have. setmetatable(instance,self) self.__index = self -- Return the instance return instance end fred = Hello:New("Fred"); fred:sayhello() In this constructor, the Hello table is both the meta table and the __index table of the instance object. Even though the instance table does not have, for example, the sayhello function in it, Lua can find it through the auspices of the meta table's __index entry. Object-oriented programming cognoscenti will recognize this as a prototype-based object system similar to that of the Self and JavaScript languages. In addition to the language itself, Lua comes with a set of runtime libraries. These libraries are also written in ANSI C and are generally linked with the Lua interpreter. As a result, there's no need to set PATH environment variables or to deliver ancillary files when deploying an application with Lua integrated. Lua is a powerful language that can express solutions to problems in a variety of domains. Yet Python, Ruby and Perl are also quite powerful in their way. Lua's primary advantage over other languages is its compact, efficient size. This size, and the ease of integrating and extending Lua into a particular programming problem is the reason Lua is worthy of examination. Lua will probably be easy to integrate into a project build system because it's ANSI C code that requires little in the way of configuration and depends on no external libraries (beyond the C runtime library). It is likely that it will be possible to simply add the Lua interpreter code from the distribution directly into a pre-existing build system. A review of the Makefiles that come with Lua will reveal any useful configuration settings. It's easy to configure Lua for virtually any platform that supports ANSI C development. An easy use for Lua in a program is to process a Lua file as configuration file and retrieve global values set by the Lua code to configure the behavior of the application. Imagine a program that does some lengthy processing. The user needs to be able to set a maximum time that that processing should continue before being canceled if necessary. Call this value maxtime. Here's a function that represents a loadconfig function the program can call to process the user's configuration file: #include <lua.h> #include <lualib.h> void loadconfig(char *file, int *maxtime) { /* Start the lua library */ lua_State *L = lua_open(); /* We'll open the Math Library for them for calculations */ lua_pushcfunction(L,luaopen_math); lua_pushstring(L,LUA_MATHLIBNAME); lua_call(L,1,0); /* Load and compile the file, the use lua_pcall to interpret it */ if (luaL_loadfile(L,file) || lua_pcall(L,0,0,0)) /* my_lua_error simply prints an error message and exits */ my_lua_error(L,"cannot load file: %s",lua_tostring(L,-1)); /* Get the Lua maxtime global variable onto the stack */ lua_getglobal(L,"maxtime"); /* Check that it is in fact, a number. The -1 indicates the * first stack position from the top of the stack. */ if (!lua_isnumber(L,-1)) my_lua_error(L,"maxtime should be a number\n"); /* Take the value off the stack and keep it */ *maxtime = (int)lua_tonumber(L,-1); /* And we're done */ lua_close(L); } The user can use os.getenv to consult the HOSTNAME environment variable and set maxtime to values that are consistent with the use policies associated with given machines..
http://www.onlamp.com/lpt/a/6467
CC-MAIN-2014-52
refinedweb
824
51.07
Every so often the need arises to create a thread safe cache solution. This is my stab at a simple yet fully functional implementation that maintains the essential dictionary semantics, is thread safe and has a fixed, configurable size, for example in a multithreaded http server like CherryPy. Although many dictionary operation like getting an item are reported to be atomic and therefore thread safe, this is actually an implementation specific feature of the widely used CPython implementation. And even so, adding keys or iterating over the keys in the dictionary might not be thread safe at all. We must therefore use some sort of locking mechanism to ensure no two threads try to modify the cache at the same time. (For more information check this discussion.) The Cache class shown here features a configurable size and if the number of entries is too big it removes the oldest entry. We do not have to maintain a explicit usage administration for that because we make use of the properties of the OrderedDict class which remembers the order in which keys are inserted and sports a popitem() method that will remove the first (or last) item inserted. from collections import OrderedDict from threading import Lock class Cache: def __init__(self,size=100): if int(size)<1 : raise AttributeError('size < 1 or not a number') self.size = size self.dict = OrderedDict() self.lock = Lock() def __getitem__(self,key): with self.lock: return self.dict[key] def __setitem__(self,key,value): with self.lock: while len(self.dict) >= self.size: self.dict.popitem(last=False) self.dict[key]=value def __delitem__(self,key): with self.lock: del self.dict[key] Due to the functionality of the OrderedDict class we use, the implementation is very concise. The __init__() method merely checks whether the size attribute makes any sense and creates an instance of an OrderedDict and a Lock. The with statements used in the remaining methods wait for the acquisition of the lock and guarantee that the lock is released even if an exception is raised. The __getitem__() method merely tries to retrieve a value by trying the key on the ordered dictionary after acquiring a lock. The __setitem__() method removes as many items within its while loop to reduce the size to below the preset amount and then adds the new value. The popitem() method of an OrderedDict removes the least recently added key/value pair if it's last argument is set to False. The __delitem__() also merely passes on the control to the underlying dictionary. Together these methods allow for any instance of our Cache class to be used like any other dictionary as the example code below illustrates: >>> from cache import Cache >>> c=Cache(size=3) >>> c['key1']="one" 0 >>> c['key2']="two" 1 >>> c['key3']="three" 2 >>> c['key4']="four" 3 >>> c['key4'] 'four' >>> c['key1'] Traceback (most recent call last): File " ", line 1, in File "cache.py", line 13, in __getitem__ return self.dict[key] KeyError: 'key1' Of course this doesn't show off the thread safety but it does show that the semantics are pretty much like that of a regular dictionary. If needed this class even be extended with suitable iterators/view like keys() and items() but for most caches this probably isn't necessary.
http://michelanders.blogspot.com/2010/12/python-thread-safe-cache-class.html
CC-MAIN-2017-22
refinedweb
549
61.97
09 October 2013 17:18 [Source: ICIS news] LONDON (ICIS)--The October contract price for European adipic acid (?xml:namespace> Market participants said Solvay said last week it had shut down its plant for an upgrade, aiming to reduce carbon emissions by 11,000 tonnes/year and cut energy consumption by 8 megawatts/year. A company source confirmed on Monday that the plant will restart in December. Once the upgrade is completed, part of the capacity is expected to remain temporarily offline depending on demand. The shutdown follows a move by BASF in late February to suspend a line at its 260,000 tonne/year plant in The two shutdowns and the expected reduction in Solvay's production will tighten the availability of A producer said tighter supply would support the case for steady prices. It added that it will push for a rollover in October, but it is also open to reducing prices by €10-20/tonne, reflecting the decrease in the cost of benzene for October. “The market is undergoing a process of rebalancing of supply. For us, this is good news,” it said. However, some buyers are asking for cuts of up to €40/tonne. Buyers are arguing that Solvay's shutdown will not have a huge impact on supply because of various reasons: the company would have already prepared stock ahead of the shutdown, demand toward the year-end is not expected to increase because of uncertain macroeconomic conditions, the market is still oversupplied, and cheaper “We don’t see any problem in buying material even if Solvay stops for two months,” a buyer said. Another buyer said it has settled early and negotiated a €25/tonne decrease from its supplier. The reduction had not been confirmed on the producer
http://www.icis.com/Articles/2013/10/09/9713867/eu-ada-prices-seen-softer-despite-solvay-shutdown.html
CC-MAIN-2014-49
refinedweb
294
56.39
Enhanced, maybe useful, data containers and utilities: A versioned dictionary, a bidirectional dictionary, a binary tree backed dictionary, a Grouper iterator mapper similar to itertools.tee, and an easy extractor from dictionary key/values to variables Project description Extra Dictionary classes and utilities for Python Some Mapping containers and tools for daily use with Python. This attempts to be a small package with no dependencies, just delivering its data-types as described bellow enough tested for production-usage. VersionDict A Python Mutable Mapping Container (dictionary :-) ) that can "remember" previous values. Use it wherever you would use a dict - at each key change or update, it's version attribute is increased by one. Special and modified methods: .get method is modified to receive an optional named version parameter that allows one to retrieve for a key the value it contained at that respective version. NB. When using the version parameter, get will raise a KeyError if the key does not exist for that version and no default value is specified. .copy(version=None): yields a copy of the current dictionary at that version, with history preserved (if version is not given, the current version is used) .freeze(version=None) yields a snapshot of the versionDict in the form of a plain dictionary for the specified version Implementation: It works by internally keeping a list of (named)tuples with (version, value) for each key. Example: >>> from extradict import VersionDict >>> a = VersionDict(b=0) >>> a["b"] = 1 >>> a["b"] 1 >>> a.get("b", version=0) 0 For extra examples, check the "tests" directory OrderedVersionDict Inherits from VersionDict, but preserves and retrieves key insertion order. Unlike a plain "collections.OrderedDict", however, whenever a key's value is updated, it is moved last on the dictionary order. Example: >>> from collections import OrderedDict >>> a = OrderedDict((("a", 1), ("b", 2), ("c", 3))) >>> list(a.keys()) >>> ['a', 'b', 'c'] >>> a["a"] = 3 >>> list(a.keys()) >>> ['a', 'b', 'c'] >>> from extradict import OrderedVersionDict >>> a = OrderedVersionDict((("a", 1), ("b", 2), ("c", 3))) >>> list(a.keys()) ['a', 'b', 'c'] >>> a["a"] = 3 >>> list(a.keys()) ['b', 'c', 'a'] MapGetter A Context manager that allows one to pick variables from inside a dictionary, mapping, or any Python object by using the from <myobject> import key1, key2 statement. >>> from extradict import MapGetter >>> a = dict(b="test", c="another test") >>> with MapGetter(a) as a: ... from a import b, c ... >>> print (b, c) test another test Or: >>> from collections import namedtuple >>> a = namedtuple("a", "c d") >>> b = a(2,3) >>> with MapGetter(b): ... from b import c, d >>> print(c, d) 2, 3 It works with Python 3.4+ "enum"s - which is great as it allow one to use the enums by their own name, without having to prepend the Enum class every time: >>> from enum import Enum >>> class Colors(tuple, Enum): ... red = 255, 0, 0 ... green = 0, 255, 0 ... blue = 0, 0, 255 ... >>> with MapGetter(Colors): ... from Colors import red, green, blue ... >>> red <Colors.red: (255, 0, 0)> >>> red[0] 255 MapGetter can also have a default value or callable which will generate values for each name that one tries to "import" from it: >>> with MapGetter(default=lambda x: x) as x: ... from x import foo, bar, baz ... >>> foo 'foo' >>> bar 'bar' >>> baz 'baz' If the parameter default is not a callable, it is assigned directly to the imported names. If it is a callable, MapGetter will try to call it passing each name as the first and only positional parameter. If that fails with a type error, it calls it without parameters the way collections.defaultdict works. The syntax from <mydict> import key1 as var1 works as well. BijectiveDict This is a bijective dictionary for which each pair key, value added is also added as value, key. The explicitly inserted keys can be retrieved as the "assigned_keys" attribute - and a dictionary copy with all such keys is available at the "BijectiveDict.assigned". Conversely, the generated keys are exposed as "BijectiveDict.generated_keys" and can be seen as a dict at "Bijective.generated" >>> from extradict import BijectiveDict >>> >>> a = BijectiveDict(b = 1, c = 2) >>> a BijectiveDict({'b': 1, 2: 'c', 'c': 2, 1: 'b'}) >>> a[2] 'c' >>> a[2] = "d" >>> a["d"] 2 >>> a["c"] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/gwidion/projetos/extradict/extradict/reciprocal_dict.py", line 31, in __getitem__ return self._data[item] KeyError: 'c' >>> namedtuple Alternate, clean room, implementation of 'namedtuple' as in stdlib's collection.namedtuple . This does not make use of "eval" at runtime - and can be up to 10 times faster to create a namedtuple class than the stdlib version. Instead, it relies on closures to do its magic. However, these will be slower to instantiate than stdlib version. The "fastnamedtuple" is faster in all respects, although it holds the same API for instantiating as tuples, and performs no length checking. fastnamedtuple Like namedtuple but the class returned take an iterable for its values rather than positioned or named parameters. No checks are made towards the iterable length, which should match the number of attributes It is faster for instantiating as compared with stdlib's namedtuple defaultnamedtuple Implementation of named-tuple using default parameters - Either pass a sequence of 2-tuples (or an OrderedDict) as the second parameter, or send in kwargs with the default parameters, after the first. (This takes advantage of python3.6 + guaranteed ordering of **kwargs for a function see) The resulting object can accept positional or named parameters to be instantiated, as a normal namedtuple, however, any omitted parameters are used from the original mapping passed to it. FallbackNormalizedDict Dictionary meant for text only keys: will normalize keys in a way that capitalization, whitespace and punctuation will be ignored when retrieving items. A parallel dictionary is maintained with the original keys, so that strings that would clash on normalization can still be used as separated key/value pairs if original punctuation is passed in the key. Primary use case if for keeping translation strings when the source for the original strings is loose in terms of whitespace/punctuation (for example, in an http snippet) NormalizedDict Dictionary meant for text only keys: will normalize keys in a way that capitalization, whitespace and punctuation will be ignored when retrieving items. Unlike FallbackNormalizedDict this does not keep the original version of the keys. TreeDict A Python mapping with an underlying auto-balancing binary tree data structure. As such, it allows seeking ranges of keys - so, that `mytreedict["aa":"bz"] will return a list with all values in the dictionary whose keys are strings starting from "aa" up to those starting with "by". It also features a .get_closest_keys method that will retrieve the closest existing keys for the required element. >>> from extradict import TreeDict >>> a = TreeDict() >>> a[1] = "one word" >>> a[3] = "another word" >>> a[:] ['one word', 'another word'] >>> a.get_closest_keys(2) (1, 3) Another feature of these dicts is that as they do not rely on an object hash, any Python object can be used as a key. Of course key objects should be comparable with <=, ==, >=. If they are not, errors will be raised. HOWEVER, there is an extra feature - when creating the TreeDict a named argument key parameter can be passed that works the same as Python's sorted "key" parameter: a callable that will receive the key/value pair as its sole argument and should return a comparable object. The returned object is the one used to keep the Binary Tree organized. If the output of the given key_func ties, that is it: the new pair simply overwrites whatever other key/value had the same key_func output. To avoid that, craft the key_funcs so that they return a tuple with the original key as the second item: >>> from extradict import TreeDict >>> b = TreeDict(key=len) >>> b["red"] = 1 >>> b["blue"] = 2 >>> b TreeDict('red'=1, 'blue'=2, key_func= <built-in function len>) >>> b["1234"] = 5 >>> b TreeDict('red'=1, '1234'=5, key_func= <built-in function len>) >>> TreeDict(key=lambda k: (len(k), k)) >>> b["red"] = 1 >>> b["blue"] = 2 >>> b["1234"] = 5 >>> b >>> TreeDict('red'=1, '1234'=5, 'blue'=2, key_func= <function <lambda> at 0x7fbc7f462320>) PlainNode and AVLNode To support the TreeDict mapping interface, the standalone PlainNode and AVLNode classes are available at the extradict.binary_tree_dict module - and can be used to create a lower level tree data structure, which can have more capabilities. For one, the "raw" use allows repeated values in the Nodes, all Nodes are root to their own subtrees and know nothing of their parents, and if one wishes, no need to work with "key: value" pairs: if a "pair" argument is not supplied to a Node, it reflects the given Key as its own value. PlainNode will build non-autobalancing trees, while those built with AVLNode will be self-balancing. Trying to manually mix node types in the same tree, or changing the key_func in different notes, will obviously wreck everything. Grouper Think of it as an itertools.groupby which returns a mapping Or as an itertools.tee that splits the stream into filtered substreams according to the passed key-callable. Given an iterable and a key callable, each element in the iterable is run through the key callable and made available in an iterator under a bucket using the resulting key-value. The source iterable need not be ordered (unlike itertools.groupby). If no key function is given, the identity function is used. The items will be made available under the iterable-values as requested, in a lazy way when possible. Note that several different method calls may precipatate an eager processing of all items in the source iterator: .keys() or len(), for example. Whenever a new key is found during input consumption, a "Queue" iterator, which is a thin wrapper over collections.deque is created under that key and can be further iterated to retrieve more elements that map to the same key. In short, this is very similar to itertools.tee, but with a filter so that each element goes to a mapped bucket. Once created, the resulting object may obtionally be called. Doing this will consume all data in the source iterator at once, and return a a plain dictionary with all data fetched into lists. For example, to divide a sequence of numbers from 0 to 10 in 5 buckets, all one need to do is: Grouper(myseq, lambda x: x // 2) Or: >>> from extradict import Grouper >>> even_odd = Grouper(range(10), lambda x: "even" if not x % 2 else "odd") >>> print(list(even_odd["even"])) [0, 2, 4, 6, 8] >>> print(list(even_odd["odd"])) [1, 3, 5, 7, 9] 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/extradict/
CC-MAIN-2021-43
refinedweb
1,799
51.78
About this project $555 16 Hello, For the majority of the past decade, I've been compiling little stories. I suppose they would be called "novellas". I've made three of them into full-length movies ("The Doctor," "To The Wolves..." and my forthcoming "Blood Jungle," which I wrote under the title "Eviva il Coltello!") Others not adapted to the silver screen are a little escape story involving a trio of strangers who avoid a fate on the gallows ("The Submarine Diaries"), and a little vaudeville number in play form ("Sugar & Dandy"). A collection of about five years worth of lyrics will also be included for you possible perusal. Illiterate? Well, there will be illustrations! In all, "Various Tails" will include: - "The Doctor" - "To The Wolves..." - "Eviva il Coltello!" - "The Submarine Diaries" - "Sugar & Dandy" - "Words for Musics" And it'll be about 250 pages long. If you'd like to help this see the light of day, well, I'd be much obliged. On a sort of tit-for-tat level, you'd even get some things in return (see to the right). Perhaps we can have a little bit of fun. With a handshake, Thomas Nöla Have a question? If the info above doesn't help, you can ask the project creator directly. Support this project Funding period - (30 days)
https://www.kickstarter.com/projects/thomasnola/various-tails-by-thomas-nola?ref=card
CC-MAIN-2017-04
refinedweb
221
75
hello everyone, I am having an issue with getting my java class coding to complete the task. Here it is: I'm coding a a Java class called Roadway that meets the following UML specification: Roadway -length : double -numLanes : int -laneWidth : double -costFactor : double +Roadway(initLength:double, initLanes: int) +setCostFactor(factor:double):void -surfaceArea():double +printCost():void The methods in the above should do the following: • the constructor should give initial values to the length and numLanes attributes from the corresponding parameters, and give the laneWidth attribute the value 8.5. • the setCostFactor method should set the costFactor attribute to the method’s input parameter value. • the surfaceArea method should calculate and return the surface area of the road. Note that this could be calculated as the product of the number of lanes in the road times the width of one lane times the length of the road. • the printCost method should print the cost of the road to the screen. You MUST utilize the surfaceArea method to accomplish this. Note that the cost of the road is just its surface area times its cost factor. Driver code class: Java Code:Java Code:Code : public class RoadwayDriver { /* Note that this driver class does not have any attributes; It merely uses object(s) of another class as needed */ public static void main(String args[]) { int myRoadNumLanes; // how wide is our road (in lanes) ? double myRoadLength, // how long is our road (in feet) ? costFactor; // how much does a square foot cost? // we’ll be reading fromt he keyboad, build a Scanner accordingly Scanner kbd = new Scanner(System.in); // prompt for and get the road length System.out.print("Please enter the length of the new road:"); myRoadLength = kbd.nextDouble(); // prompt for and get the number of lanes in the road System.out.print("Please enter the number of lanes for the new road:"); myRoadNumLanes = kbd.nextInt(); // prompt for and get the cost per square foot System.out.print("Please enter the cost factor:"); costFactor= kbd.nextDouble(); // build up a roadway object using values read in Roadway myRoad = new Roadway(myRoadLength, myRoadNumLanes); // set the roadway’s cost factor from the value read in myRoad.setCostFactor(costFactor); // print out the roadway’s cost. myRoad.printCost(); } } when i run the program, the console terminates after "Please enter the cost factor" question so i am unable to get the cost of the roadway.when i run the program, the console terminates after "Please enter the cost factor" question so i am unable to get the cost of the roadway.Code : public class Roadway { private double length; private int numLanes; private double laneWidth; private double costFactor; private double printCost; public Roadway(double initLength, int initLanes) { length = initLength; numLanes = initLanes; laneWidth = 8.5; } public void costFactor(double factor) { costFactor = factor; } public double getCostFactor() { return costFactor; } public void setCostFactor(double costFactor) { this.costFactor = costFactor; } private double surfaceArea() { double surfaceArea = length * numLanes * laneWidth; return surfaceArea; } public void printCost() { printCost = (surfaceArea() * costFactor); } public double getPrintCost() { return printCost; } public void setPrintCost(double printCost) { this.printCost = printCost; } if anyone could help me as soon as possible, i would really appreciate. thanks
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/14002-help-needed-java-coding-printingthethread.html
CC-MAIN-2014-42
refinedweb
518
53
From Documentation Purpose Since ZK 2.2.0 is possible to add i18n support by using i3-label*.properties files to store localized strings and use resource class Labels to retrieve them. This approach is the most wide spread in ZK for localizing ZUL files, and it was introduced by Minjie Zha in his smalltalk I18N Implementation in ZK. However, this approach has its drawbacks. It requires developers to think first of a key for the text they are going to localize, store it in a i3-label*.properties file together with the localized text, an enable the mechanisms necessary to retrieve keys from a ZUL file. In addition, ZUL files are flooded with keys which sometimes have an obscure meaning. This approach provides also a limited support for customizing texts with parameters, being not possible to place parameters in the middle of a text, for example. This small talk presents a new approach for internationalizing texts both in Java and ZUL files using the power of GNU shell utilities. Goals After this small talk you will know how to: - I18n texts in Java and ZUL files - I18n texts without keeping track of arbitrary property labels - I18n texts with parameters - Support dynamic change of local language seamlessly Introduction to GNU shell GNU shell utilities are perhaps the most popular tools for i18n among free and open source projects. Basically, the idea is to mark text to be localized in the source code with some special tag. For instance: Label lblName = new Label("First name"); Texts to be translated should be wrapped by shell function which later will be called to retrieve a localized string. Label lblName = new Label(shell("First name")); Generally, it could be convenient ro rename shell as _ for shortening tags and make them easier to identify in the code. public String _(String str) { return shell(str); } GNU gettex utilities define a standard workflow we should normally follow: - Mark texts to be internationalized in source code with _ function. - Parse source files fetching msgids. The result of this step is a keys.pot file containing all msgids in our project. - Translate keys.pot into a locale.po (for example, es.po in case of Spanish language). - Convert locale.po files into binary resources that could be used later from a programming language. Example of a GNU shell workflow First, we mark texts to be internationalized in source code with _ function. After that, run command xshell to parse those marks and fetch msgids. The result will be a keys.pot file containing all msgids in our project. find ./src -name "*.java" -exec xshell --from-code=utf-8 -k_ -o keys.pot '{}' \; A keys.pot file has the following structure: white-space # translator-comments #. extracted-comments #: reference... #, flag... #| msgid previous-untranslated-string msgid untranslated-string msgstr translated-string A simple entry can look like this: #: src/main/java/com/igalia/UnexpectedError.java:101 msgid "Run-time error" msgstr "Error en tiempo de ejecución" Every entry consists of a msgid, a msgstr, and list of comments refering to filename and line for every msgid that occurred in the source code. Notice that every msgid in a keys.pot file is in fact unique. Once you got a keys.pot file, it is time to localize it. Run the following command: msginit -l es_ES -o es.po -i keys.pot The example above generates a Spanish locale file (es.po) out of keys.pot. In case es.po file already existed in our project, we could easily update it by running the following command: msgmerge -U es.po keys.pot This will update all missing entries from keys.pot to locale.po. Now you are ready for translating new entries in locale.po file. Use poedit or your favorite text editor to do that. Lastly, convert locale.po files to binary format. These binary files, or resource bundles, can be used later from a programming language to retrieve localized strings. msgfmt --java2 -d . -r app.i18n.Messages -l es es.po GNU shell diagram workflow Understanding GNU shell utilities workflow is essential before continuing with this tutorial. The following diagram, which is part of [GNU shell utilities documentation], summarizes in form of a diagram the steps explained in the previous section. I18n Java files Setting up shell Commons shell Commons provides Java classes for internationalization through GNU shell. shell Commons let us mark texts to be localized in source code, as well as taking care of retrieving localized strings properly. We can think of shell Commons as a bridge between our project and resource bundles generated as result of a shell workflow. shell Commons comes as .jar. There is a Maven repository for it. If you are running a Maven2 project, simply add the following lines to your POM file: <repositories> <!– Add shell Commons repository –> <repository> <id>shell-commons-site</id> <url></url> </repository> </repositories> <dependencies> <!– Add shell Commons dependency –> <dependency> <groupId>org.xnap.commons</groupId> <artifactId>shell-commons</artifactId> <version>0.9.6</version> </dependency> </dependencies> Localizing Java files Consider we wish to add i18n support for the following snippet of code: class MyClass { public void render() { Listheader listheader = new Listheader("Header"); } } shell Commons provides a series of classes for internationalizing text. The most important is I18NFactory. I18NFactory is a factory class which let us instantiate a resource bundle from a specific locale, and use it from source code for localizing strings. class MyClass { I18n i18n = I18NFactory.getI18n(this.getClass(), new Locale("Es", "es), org.xnap.commons.i18n.I18nFactory.FALLBACK); public void render() { Listheader listheader = new Listheader(i18n.tr("Header")); } } In the example above, I called I18NFactory.getI18n() for retrieving a resource bundle for es_ES locale (Spanish language, Spanish dialect from Spain). The third parameter, provides a default resource bundle in case es_ES resource bundle did not exist. In render() method, I called i18n.tr to wrap “Header” text. i18n.tr is used to mark texts to be internationalized. When processing java source files with xshell command we should parametrized it properly so it can recognize tr as a marker. On the other hand, typing i18n.tr every time we need to mark a text, plus instantiating a i18n object for every .java file, can be tedious and repetitive. Fortunately, this can be improved: public class I18nHelper { I18n i18n = I18nFactory.getI18n(I18nHelper.class, new Locale("Es", "es), org.xnap.commons.i18n.I18nFactory.FALLBACK); public static String _(String str) { return i18n.tr(str); } In the example above, I created a I18nHelper class. This class provides a static _ method that can be used from any class for internationalizing strings. import static org.navalplanner.web.I18nHelper._; class MyClass { public void render() { Listheader listheader = new Listheader(_("Header")); } } Where to place Resource Bundles Sometimes I18nFactory complains about it could not find a requested resource bundle. Resource bundles, are the result of a Gettex workflowo, being generated on the last step via msgfmt command. In GNU shell terminology these binary files are called Message Objects (.mo files). In Java Message Objects are called resource bundles. After executing msgfmt, if everything went OK, you will get a Messages_XX.class file, where XX stands for the name of the locale (ES, for example). Since resource bundles are binary files, you must put them under your target/ directory. By default, shell Commons expects to find resource bundles under target/classes directory. shell Commons Maven plugin Apart from shell Commons jar library, there is also a Maven2 plugin for shell. shell Maven plugin is basically a wrapper for some GNU shell commands: xshell, msmerge and msgfmt. Run the following maven goals from command line to: - mvn shell:shell, parses .java files and generates keys.pot file. - mvn shell:merge, executes previous command plus generates locale files (es.po, de.po, cn.po, etc). - mvn shell:dist, executes previous command plus generates a resource bundle file, Messages_XX.class, for every locale file. In case you want to know more about how to setup this plugin, please check the following link: Setting up shell Commons for i18n Java files. I18n ZUL pages Localizing ZUL files First of all, we are going to modify I18nHelper.java class from previous section. What basically I am going to do is to add a getI18n() method. This method instantiates a I18n object. ZK engine provides method Locales.getCurrent(), which returns the current locale. Instantiation queries for current locale, loading it in case it exists, or using a default one instead. In addition, this new implementation provides an extra memory cache for storing instantiated i18n objects (Click to download final version of I18nHelper.java). public class I18nHelper { private static HashMap<Locale, I18n> localesCache = new HashMap<Locale, I18n>(); public static I18n getI18n() { if (localesCache.containsKey(Locales.getCurrent())) { return localesCache.get(Locales.getCurrent()); } I18n i18n = I18nFactory.getI18n(I18nHelper.class, Locales .getCurrent(), org.xnap.commons.i18n.I18nFactory.FALLBACK); localesCache.put(Locales.getCurrent(), i18n); return i18n; } public static String _(String str) { return getI18n().tr(str); } } After that we are going to create a tag-lib which is simply a facade for I18nHelper. <?xml version=”1.0″ encoding=”ISO-8859-1″ ?> <taglib> <uri></uri> <description></description> <function> <name>_</name> <function-class>com.igalia.I18nHelper</function-class> <function-signature> java.lang.String _(java.lang.String name) </function-signature> <description></description> </function> </taglib> Name it i18n.tld and save it under your /WEB-INF/tld/ directory (Click to download i18n.tld). Now you are ready to include i18n.tld tag-lib from any ZUL file. Include it and use the i18n prefix accordingly. For instance, <zk> <?tag-lib </window> </zk> Load this ZUL page on your favorite browser and see what happens. Basically what we are doing here is to rely on I18nHelper. I18nHelper exposes _ function for localizing strings passed as a parameter. I18nHelper.getI18n() instantiates a i18n object querying a specific locale resource bundle. A resource bundle contains localized strings and knows how to convert msgids to locale strings. How to compile msgids from ZUL files The first obstacle that we need to surpass to generate a resource bundle for a ZUL page successfully is parsing that page searching for texts wrapped by ${i18n:_(’%s’)} string. GNU shell utilities support a myriad of programming languages but unfortunately shell does not support XML files. However, this is not a problem as parsing a XML file is much easier than parsing source code of a programming language. I wrote a small Perl script: shell_zul.pl, which does exactly that. Run it like this: shell_zul.pl --dir path_to_zul_files --keys existing_keys.pot_file You can ommit the --keys parameter, so a new keys.pot file will be created in your current directory. This option can be useful in case you have an existing keys.pot file, generated prior as the result of processing a set of Java files for example. Once your keys.pot file is up-to-date, create a localized version out of it (locale.po). Lastly, run msgfmt to generate a locale resource bundle out of locale.po. Supporting arguments Generally text messages need extra parameters. For example, message “Confirm deleting element?” should be localized as ‘”Confirm deleting {0}?”, item.name’. To sort out this problem, we can extend I18nHelper and overload _ method with extra arguments. public static String _(String str) { return getI18n().tr(str); } public static String _(String text, Object o1) { return getI18n().tr(text, o1); } public static String _(String text, Object o1, Object o2) { return getI18n().tr(text, o1, o2); } public static String _(String text, Object o1, Object o2, Object o3) { return getI18n().tr(text, o1, o2, o3); } public static String _(String text, Object o1, Object o2, Object o3, Object o4) { return getI18n().tr(text, o1, o2, o3, o4); } To make use of these new functions, we need to expose them in i18n.tld tag-lib. Tag libs do not support function overloading, so we need to provide different names for each function. For instance, we may add a new function, __, that receives one extra parameter. <function> <name>__</name> <function-class>com.igalia.I18nHelper</function-class> <function-signature> java.lang.String _(java.lang.String name, java.lang.Object arg0) </function-signature> </description> </function> Now you are able to localize strings in ZUL pages that require one extra parameter. <label value="Hello user"/> Can be localized as: <zscript> String I18n as a Macrocomponent Another way of supporting arguments in ZUL files is to encapsulate I18nHelper funcionality into a HTMLMacroComponent. First of all, create a HTMLMacroComponent, save it as i18n.zul at webapp/common/components/ (Click to download i18n.zul). <zk> <label value="@{self.i18n}" /> </zk> Create its corresponding Java file (Click to download I18n.java) and save it as I18n.java at webapp/common/components/. I18n tag is able to receive up to 4 arguments, named arg0, arg1, etc. Finally, add this new HTMLMacroComponent to your lang-addon.xml file. <component> <component-name>i18n</component-name> <component-class>com.igalia.common.components.I18n</component-class> <macro-uri>/common/components/i18n.zul</macro-uri> </component> Now you are ready to use i18n tag in ZUL pages for i18n texts. <i18n value="Confirm deleting {0} ?" arg0="@{item.name}"/> HTMLMacroComponent vs Taglib Most part of the time we may just need to localize single values inside attributes, in this case using a tag-lib is the right way to go, for example: <button label="${i18n:_('Accept')}"/> Tag-libs are OK for static texts. Static texts are evaluated only once when the ZUL page is rendered for the first time. When showing texts with data bindings, we must use i18n tag. In most cases, strings with arguments have their arguments bound to dynamic data. As rule of thumb, whenever there are arguments, i18n tag is the right choice. <i18n value="Confirm deleting {0} ?" arg0="@{item.name}"/> However, enabling i18n tag-lib to support a different number of arguments can be convenient if we need to substitute an argument inside a literal value. Consider the following example: <window title="Error ${requestScope['javax.servlet.error.status_code']}"/> This is a very particular case but it still can happen in your code. Adding an extra __ function in your tag-lib can solve this problem. <window title="${i18n:__('Error', requestScope['javax.servlet.error.status_code'])}"/> NOTE: There is no need to interpolate requestScope variable as it is already inside another interpolation (${i18n:…}) Conclusions This small talk proposes a new approach for internationalizing textx inside ZUL pages as well as Java files for your ZK applications. This approach is based on GNU shell, probably the most wide-spread way of i18n in the FOSS world. This new approach provides clear advantages to developers as they do not need to spend time thinking of meaningless keys and keeping track of them manually across different i3-label*.properties files, which in the long-run means saving time and automatizing the whole process of translating and localizing. Download You can download all sample files in this small talk here: i18n.tar.gz.
http://books.zkoss.org/wiki/Small%20Talks/2009/September/I18n%20Java%20and%20ZUL%20files%20with%20GNU%20gettext
CC-MAIN-2014-42
refinedweb
2,497
50.73
The TypeScript module is nothing new to the JavaScript programmer. The simplest module is something like: module MyModule{export var myVariable;} module MyModule { export var myVariable; } You can define variables, objects, classes, interfaces and functions within the module. Everything that you define is created in JavaScript within an encapsulating object with the same name as the module. So to access myVariable you would have to write MyModule.myVariable Anything that you don't export is private to the module and cannot be accessed by the external world. The module is implemented in JavaScript as an anonymous function that is executed at once to create an object that contains all of the modules members. Modules can extend existing modules of the same name. Modules can be internal, i.e. defined in the same file, or external in another file of the same name. The import MyModule instruction loads MyModule.js. import MyModule There is a lot more to say about the fine detail of modules but essentially what we have is the CommonJS, AMD or the namespace idiom in JavaScript made slightly easier to use. The TypeScript class construct is much what you would expect. You can define a class: class MyClass{} class MyClass and the body of the class can contain functions, variables and objects. A constructor of the same name as the class is declared using: constructor(parameters) A class can inherit from another class, or as we shall see later from an interface using the extends or implements keyword. To call the base class constructor you use the super keyword. Members of the class can be declared as static and these belong to the constructor function and so appear to belong to the class rather than the instance. You have to use the this keyword when working with class or instance members. You can override inherited methods and properties by simply redefining them. Instance members can be declared as public or private with the default being public. This sounds a wonderful step forward because JavaScript objects can't have private members but as it turns out neither can TypeScript objects. The private declaration is taken notice off only at compile time and if you try to access a private member then you will generate a compile time error. There are ways of dynamically accessing private members at runtime without generating an error. Classes are implemented in JavaScript by the creation of a standard constructor function of the same name. Inheritance is implemented by chaining prototype objects. Once again most of this is available in standard JavaScript if you use the appropriate idiom. TypeScript simply provides a perhaps easier and clearer way of writing it. Of course it is the type system that makes TypeScript either worth using or not. By comparison the rest is fairly simple stuff. Imposing a type system on a superset of JavaScript is no simple matter because to contain JavaScript objects can dynamically change their type. In JavaScript there is no concept of a fixed type - objects simply acquire and lose the methods and properties they need. In addition to this difficulty functions are first class objects, i.e. they are object you happen to be able to call and evaluate, and this makes the concept of type even more sophisticated. What do JavaScript programmers do to cope with this situation? They resort to duck typing. Forget the ideas of a type hierarchy based on inheritance. All that matters is that an object has the properties and methods you want to use. Interestingly this is the approach that TypeScript takes, but it is heavily disguised as static hierarchical typing. In TypeScript a type is simply a specification for a set of methods and properties an object has. It can be taken as a statement of what it is safe to use and what the object is expected to support. The type system starts with any, which you can consider to be the top of the type hierarchy, but it is best thought of as a statement that nothing is known about the type. In other words, you can use any method or property in any way that you like and no compiler errors will be generated. Clearly if we are going to rely on type checking we need to use any as little as possible. The primitive types are number, boolean, string, null and undefined and they directly correspond to the JavaScript primitive types. To allow functions to act as procedures i.e. to not return a result, we also have the special type void which means the absence of a value. Whenever possible the system will infer a type for a variable. For example, var i=1; allows the system to infer that i is of type Number. After this assigning say a string generates a compile time error. Type inference is impressive but it can be a problem. Consider the following: if (false) { var i = 2; } else { var i = "hello"; } This is perfectly valid JavaScript and the type of i is clearly String. However in TypeScript i is typed as Number and the else clause generates a runtime error. Perhaps the message is that you shouldn't write code like this, but you also need to be aware that type inference is lexical and not semantic. You can explicitly type a variable using a type annotation. For example var i:number=1; sets i to be of type number and initializes it to one. Clearly using explicit type annotation is a better idea than relying on type inference. You can also form arrays of types using type[ ] - for example number[ ] is a numeric array. Functions are just objects you can call but in TypeScript you can specify the functions signature - the types of the parameters and return value. Notice that the return value is included in the signature - this is unusual. Functions can also have required and optional parameters, marked by a trailing ? within the signature. You can also include a rest parameter which accepts any additional parameters - it has to be of type any[] For example: function myFunction(total:number, name:string):string; defines a function with a signature number,string return string. The function function myFunction() :void; accepts no parameters and returns no result. When you call a function the parameter types have to match the signature. Notice that if you don't specify a signature then one is inferred and type checking is performed using it. You can also use function overloading i.e. same function with different signatures. In this case you can call the function without error if the call matches any of the signatures you specify. function myFunction(x:number) :void;function myFunction(x:string) :void; function myFunction(x:number) :void; function myFunction(x:string) :void; This sounds exciting and useful but you have to implement the overloaded function in the original JavaScript style i.e. you have to work out what the types actually are in the call: function myFunction(x:number) :void;function myFunction(x:string) :void;function myFunction(x: any): void { if (typeof x == "string") { do something with string } else { do somethign with number }}; function myFunction(x:number) :void;function myFunction(x:string) :void;function myFunction(x: any): void { if (typeof x == "string") { do something with string } else { do somethign with number }}; The type of the function doesn't include the actual implementation using any.
http://i-programmer.info/programming/other-languages/4884-getting-started-with-typescript.html?start=1
CC-MAIN-2016-26
refinedweb
1,232
62.48
I disagree on the 5-10 year timeframe for nmigen usability. I have used VHDL code in nmigen design, used cocotb with modelsim (proprietary I know) for mixed-signal sim. But I agree this is own development not general available. @fatsiefs:matrix.org I meant 5-10y since someone decides to (re)invent a language, not from now onward. nmigen has been 3y in development after 10y of migen and +10y of myHDL. It didn't come out of nowhere. By the same token, 3y ago cocotb was dead, after a very successful start. FOSSi, Kaleb and others spent the last 2 years working so hard, and they still have at least 1y of development for starting to consider it mature. Note that my reply was targeted at a person that suggested he would write his own HDL from scratch. I suggested him to better build on any of those existing projects/languages precisely so those can get to maturity faster. You would compare nMigen to VHDL? I think they pretty different in approach. nMigen is a Python metaprogramming framework on top of a functional RTL-oriented DSL. VHDL is a more traditional simulation language. @ktbarret, could you please elaborate? I'm thinking about a user who needs to learn both hardware design and a language for hardware description at the same time, as a tool for them to use in the following 1-2 decades. I don't think whether the implementation is a metaprogramming language or a traditional language is relevant. It's about what they can express and what they cannot. Entities/architectures/modules/components/bodies, structs/records/interfaces, FFs/memories, boolean logic/muxes, fixed-point and floating-point DSP... there are mature FP toolboxes for MyHDL I know of. But isn't this a bit off topic? @hackfin, would mind providing any reference? We can continue in hdl/community, if you prefer. Ive been thinking of the board that the MisTER project uses, which is a DE-10 Nano (intel). How is the ecosystem with that vs the xilinx based stuff of the basys3 @vblanco20-1 I suggest you ask in the symbiflow channel in IRC, and/or in project mistral. Support for intel/altera devices is less advanced than Lattice or Xilinx. For Xilinx, there are two PnR tools, nextpnr and VTR. For Intel, I think they are working with nextpnr only. I would recommend an ECP5 device and a board with an Artix. I would stay away from Zynq, unless you have any actual usage for the single or dual ARM cores. You cannot use the PL without understanding and initialising the PS. I have a PYNQ-Z1 and some Arty, and there is no advantage in the first one for RTL only designs. However, Zynq is very interesting if you want to run Linux on ARM and accelerate things in the FPGA. the de10nano is used in the mister project which is something i could contribute to or have fun tinkering with I believe that the mister project might greatly benefit from being ported/adapted to an open board based on one of the largest ECP5. However, mister seems to be not only the FPGA board, but a whole stack of boards... the main thing is on the de-10 nano, but the extras are to give it extra ram, more usb ports, and analog output (VGA) @vblanco20-1 With some ECP5 or Artix boards you would have some of those extras. For instance, as direct alternative to Arty/Zybo. @umarcor and they still have at least 1y of development for starting to consider it mature. Probably a lot more than that, especially with how few contributors we have, how averse to large changes the project is, and how grindy the review process is. To meet some of the needs of users we need to do significant rewrites of many of the components, but I don't see that as possible... And there is a lot of related work that needs to be done: At the current pace I see it as 4 more years. I don't think whether the implementation is a metaprogramming language or a traditional language is relevant. Sure. I didn't know to what extent you were trying to make comparisons. I suggested him to better build on any of those existing projects/languages precisely so those can get to maturity faster. This is kind of what I am doing as a verification framework on top of cocotb. It keeps changing and it's looking more and more like an HDL... Processes, "modules" (probably need a better name since Python already has modules), channels and synchronous channels (blocking send returns after placement in queue vs recv by destination, which a generalization of a "signal"), accompanied by a set of HDL datatypes making their way into cocotb. @ktbarrett, thanks so much for acknowledging that. I believe that VUnit, OSVVM and others are in a similar state. Even though their codebase is more mature (OSVVM +20y, VUnit almost 10y), the integration with others, writing articles, tutorials, etc. is a challenge we all need to address, because we are very few in each of the projects. This is kind of what I am doing as a verification framework on top of cocotb. It keeps changing and it's looking more and more like an HDL... (...) accompanied by a set of HDL datatypes making their way into cocotb. I don't know if I already told you about my conception of using cocotb's Python interface for driving the VHDL Verification Components of VUnit and/or OSVVM. Not something I will solve in the following weeks or months, but that is my target in say 5 years. Hence, there is lots of conceptual overlapping with what you are trying to achieve. Channels, message passing, queues, a virtual memory with permissions, etc. all those software tools for verification are already written in VHDL and customised for the standard interfaces. We should not reimplement that in Python nor do bit-banging through indirect cosimulation interfaces. Unfortunately, I'm not expert enough yet for proposing an specific implementation for achieving that. First things first, I need to solve the envvar management in VUnit, which that cocotb user asked, and which I'm finding I need for other use cases (customising LD_LIBRARY_PATH when doing cosimulation with VUnit and GHDL through VHPIDIRECT). all those software tools for verification are already written in VHDL and customised for the standard interfaces. We should not reimplement that in Python nor do bit-banging through indirect cosimulation interfaces. Well, this is kind of the entire point of cocotb. Write testbenches in Python instead of VHDL or (System)Verilog. I could see implementing drivers/monitors in VHDL or SystemVerilog and controlling them from a cocotb test as a (very) useful optimization and to cover cases where the VPI isn't sufficient (tri-state drivers), but that would require a lot of tooling because I would like something like that to be automated. One of the things people like about cocotb is not having to write any VHDL/(System)Verilog for the testbench, or even write a top at all. And I don't see how that precludes implementing the same functionality in cocotb to handle the cases where moving the implementation to HDL is not possible or just too time consuming to be useful. You might be interested in pybfms which is similar to this. IIRC it uses VPI system tasks to enable communication between cocotb and Verilog BFMs. I'm not familiar enough with cocotb+verilator or cocotb+iverilog yet That reminds me of one more task to reach maturity: Mature the GHDL and Verilator VPI/VHPI interfaces so cocotb will work with them. but that would require a lot of tooling because I would like something like that to be automated. A verification component is a black-box with a software API on one side and a hardware interface on the other. Adding an VC between the HDL interface and the software procedure is the most automated and transparent solution for the users. They should not write any code in any case, just their application specific software procedure. The question is whether VCs need to be written in HDL only, in Python only, or half HDL half Python. I believe it needs to be the last one. We can request developers to know both languages, even though users won't. Currently, developers need to know VPI/VHPI although users do not. I agree it would require tooling, but not more than it required to automate the usage of HDL only VCs or Python only VCs. That is a library management issue we have in the EDA industry, not specific in this case. You might be interested in pybfms which is similar to this. IIRC it uses VPI system tasks to enable communication between cocotb and Verilog BFMs. Yeah, that's kind of the idea. Anyway, we first need to solve how to call VHDL subprograms from a foreign language, which is not defined yet. That's part of the VHDPI discussion, but it might not get into the first revision. In ghdl-cosim there is an example of the opposite: using a VHDL protected type with foreign attributes for exposing a C API in VHDL. The idea is the same: get a handle of the class/object from the other language and call the methods as the software API of the "standard interface". Mature the GHDL and Verilator VPI/VHPI interfaces so cocotb will work with them. This is my priority with GHDL. I need to get to implement some changes myself so I can actually start fixing things and not just annoying Tristan with bug reports and requests. In the last days, I did a lot of enhancements for pyVHDLModel which is used by pyVHDLParser and also GHDL. The VHDL language model is the basis for the dom namespace in pyGHDL. I think until end of the week I can finalize a first pretty-printing demonstrator, which parses a VHDL file with GHDL's libghdl, uses GHDL's Python bindings and transforms GHDL's internal data structure (IIR) to a Python-based document object model (DOM) that represents a VHDL file with instances of classes and references (points) among them. The pretty-printer example emits the translated object model to text. From there it should be easy to provide other output formats like JSON or YAML (if needed). Of cause, users can use the object model in there own libraries or tools based on GHDL's Python API. Even if my own project pyVHDLParser is not as advanced and working like GHDL, it's till planned to have a second source besides parsing via libghdl to create a object model using pyVHDLModel as a common interface. What is it good for? We can now think about generating documentation - especially in Python based tools like Sphinx - from VHDL code parsed by libghdl. What I can do so far is: std_logic_vector(BITS - 1 downto 0) Example output (pretty printed DOM): Document 'testsuite\pyunit\SimpleEntity.vhdl': Entities: - entity1 Generics: - bits : in positive Ports: - clock : in std_logic - reset : in std_logic - q : out std_logic_vector(bits - 1 downto 0) Architectures: - behav Packages: PackageBodies: Configurations: Contexts: cli/DOM.pywhich can be called with a VHDL file as parameter to call the pretty-printing example code. ah, just the usual job setup overhead (fetching containers, fetching repo, etc) or is there something else? The opposite. Containers are fast. Windows is slow.
https://gitter.im/ghdl1/Lobby?at=60bb849e3908f10174348adb
CC-MAIN-2021-43
refinedweb
1,924
62.48
A class to calculate and manage a variety of time parameters. More... #include <sg_time.hxx> A class to calculate and manage a variety of time parameters. The SGTime class provides many real-world time values. It calculates current time in seconds, GMT time, local time zone, local offset in seconds from GMT, Julian date, and sidereal time. All of these operate with seconds as their granularity so this class is not intended for timing sub-second events. These values are intended as input to things like real world lighting calculations and real astronomical object placement. To properly use the SGTime class there are a couple of things to be aware of. After creating an instance of the class, you will need to periodically (i.e. before every frame) call the update() method. Optionally, if you care about updating time zone information based on your latitude and longitude, you can call the updateLocal() method periodically as your position changes by significant amounts. Definition at line 63 of file sg_time.hxx. Create an instance based on a specified position and data file path. This creates an instance of the SGTime object. When calling the constructor you need to provide a root path pointing to your time zone definition tree. Optionally, you can call a form of the constructor that accepts your current longitude and latitude in radians. If you don't know your position when you call the SGTime constructor, you can just use the first form (which assumes 0, 0). Create an instance given a data file path. Definition at line 163 of file sg_time.hxx. Definition at line 184 of file sg_time.hxx. Definition at line 166 of file sg_time.hxx. Definition at line 169 of file sg_time.hxx. Definition at line 181 of file sg_time.hxx. Definition at line 172 of file sg_time.hxx. Definition at line 178 of file sg_time.hxx. Definition at line 175 of file sg_time.hxx. Update the time related variables. The update() method requires you to pass in your position and an optional time offset in seconds. The offset (or warp) allows you to offset "sim" time relative to "real" time. The update() method is designed to be called by the host application before every frame. Definition at line 189 of file sg_time.cxx. Given lon/lat, update timezone information and local_offset The updateLocal() method is intended to be called less frequently - only when your position is likely to be changed enough that your timezone may have changed as well. In the FlightGear project we call updateLocal() every few minutes from our periodic event manager. Given an mjd, calculate greenwich mean sidereal time, gst Definition at line 397 of file sg_time.cxx. Given a date in our form, return the equivalent modified Julian date (number of days elapsed since 1900 jan 0.5), mjd. Adapted from Xephem. Definition at line 311 of file sg_time.cxx. Given an optional offset from current time calculate the current modified julian date. Definition at line 361 of file sg_time.cxx. Format time in a pretty form Definition at line 562 of file sg_time.cxx. this is just a wrapper for sgTimeGetGMT that allows an alternate form of input parameters. Definition at line 212 of file sg_time.hxx. Return unix time in seconds for the given date (relative to GMT) Definition at line 466 of file sg_time.cxx.
http://simgear.sourceforge.net/doxygen/classSGTime.html
CC-MAIN-2017-30
refinedweb
559
58.48
wcstombs() Convert a wide-character string into a multibyte character string Synopsis: #include <stdlib.h> size_t wcstombs( char* s, const wchar_t* pwcs, size_t n ); Arguments: - s - A pointer to a buffer where the function can store the multibyte-character string. - pwcs - The wide-character string that you want to convert. - n - The maximum number of bytes to store. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The wcstombs() function converts a sequence of wide character codes from the array pointed to by pwcs into a sequence of multibyte characters, and stores them in the array pointed to by s. It stops if a multibyte character exceeds the limit of n total bytes, or if the NUL character is stored. At most n bytes of the array pointed to by s are modified. The wcsrtombs() function is a restartable version of wcstombs(). Returns: The number of array elements modified, not including the terminating zero code, if present, or (size_t)-1 if an invalid multibyte character is encountered. Examples: #include <stdio.h> #include <stdlib.h> wchar_t wbuffer[] = { 0x0073, 0x0074, 0x0072, 0x0069, 0x006e, 0x0067, 0x0000 }; int main( void ) { char mbsbuffer[50]; int i, len; len = wcstombs( mbsbuffer, wbuffer, 50 ); if( len != -1 ) { for( i = 0; i < len; i++ ) printf( "/%4.4x", wbuffer[i] ); printf( "\n" ); mbsbuffer[len] = '\0'; printf( "%s(%d)\n", mbsbuffer, len ); } return EXIT_SUCCESS; } produces the output: /0073/0074/0072/0069/006e/0067 string(6)
https://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/w/wcstombs.html
CC-MAIN-2018-51
refinedweb
247
65.42
Roger Pack <rogerdpack2 <at> gmail.com> writes: > That's the reason I initially proposed the > (rather kludgey) -i "input -r 24" type input. Are input files then forbidden to contain a space, a hyphen, hyphen and "r" or is some complicated rule that defines that a space followed by a hyphen, a space and a valid option is not an input file? What about new (later) options? Will they change the rule or will we reserve some option namespace? And what should I do with the file "input -r 24" I just created? Sorry, I am just trying to explain that there is no simple solution for the problem you describe (if you believe it exists), while there are some very good reasons not to touch the interface if it is not absolutely necessary. Carl Eugen
http://ffmpeg.org/pipermail/ffmpeg-devel/2012-October/133332.html
CC-MAIN-2016-22
refinedweb
136
69.01
While Javascript usage continues to grow at a rapid pace, including server side with Node.js, Javascript developers have not been able to directly work with distributed computing engines such as Apache Spark which does not provide a Javascript API. The EclairJS project changes that by providing an API, and enables developers to use Apache Spark’s large-scale analytics, streaming, SQL and machine learning features by writing only Javascript. EclairJS consists of two components. One component is the EclairJS server called EclairJS-Nashorn which sits in front of Apache Spark and enables the second component, the EclairJS client which is a Node module called EclairJS-Node, to communicate with Apache Spark. Apache Spark is built on top of the Java Virtual Machine and the EclairJS-Nashorn component allows us to extend the various parts of Apache Spark to support Javascript natively. In a production environment the IT department would probably setup an Apache Spark cluster with the EclairJS server sitting next to the Apache Spark Master. But in lieu of the IT folks and to help you try out EclairJS, we have created a Docker image containing an Apache Spark and EclairJS server setup that you can deploy on IBM Bluemix. With this setup running on Bluemix, it is a simple matter to also run a Node application in Bluemix and make it communicate with Apache Spark in the Docker container. Note that Bluemix provides a 30-day free trial (no credit-card needed) so you can try out EclairJS in Bluemix at no cost. In the rest of this post, I’ll first describe how to setup Docker and the Docker image containing Apache Spark and the EclairJS server in Bluemix. Then I’ll go on to describe a simple web application and how to deploy it onto Bluemix. Setting up Docker Docker containers provide a convenient way to package pre-built environments that can be quickly deployed, either locally on your development machine or to hosted solutions like Bluemix. You will need to have Docker running locally as we will be using it to push the container to Bluemix. Follow this page to install Docker locally on your development machine and use the Getting Started Tutorial if you don’t already have Docker installed (version 1.10 or higher is needed). You will also need to download the Bluemix command line tools as well as the Cloud Foundry command line tools (Bluemix is built on top of Cloud Foundry). Next you will need to install the appropriate IBM Containers Cloud Foundry plug-in for your operating system (follow step 5 on that page). Bluemix provides every user with a private Docker registry where they can store Docker images, and you will use your registry to store a copy of the Spark-EclairJS image. Before you can use your registry, you need to give it a unique name. To do this from your command line, log into Bluemix and set the registry name: $ cf login $ cf ic namespace set your_registry_name_here $ cf ic login Setting Up Spark With Docker set up, we can push the Spark-EclairJS Docker image to the registry by executing the following commands, and be sure to substitute in the registry name you set above: $ cf ic init $ cf ic cpi eclairjs/minimal-gateway registry.ng.bluemix.net/<your_registry_name_here>/minimal-gateway This one-time operation builds and pushes the image to your Bluemix repository. Next we create a Docker container based on this image, called eclairjs/minimal-gateway, which will provide a working environment for us to use. ((If you are unfamiliar with the differences between Docker images and containers, see here).) $ cf ic run --name eclairjs -p 8888:8888 -m 128 registry.ng.bluemix.net/<your_registry_name_here>/minimal-gateway This operation creates a Docker container named eclairjs based on the image. It may take a while to complete but you can check on the status of container by running the following command: $ cf ic ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 879ada59-5e6 registry.ng.bluemix.net/<your_registry_name_here>/minimal-gateway:latest "" About a minute ago Running 27 seconds ago 8888/tcp eclairjs You can also monitor the state of the Docker container by going to Bluemix’s Dashboard which will list all of the containers you have created. Once the status of the Spark-EclairJS container is Running, you need to request a public IP address for it because Bluemix applications cannot connect to Bluemix Containers using their private IP addresses. The command to request a public IP address is: $ cf ic ip request OK The IP address "<your.ip.address>" was obtained. The command will output an IP address. We bind that address to our Docker container so we can access it with the command: $ cf ic ip bind <your.ip.address> eclairjs OK The IP address was bound successfully. Building a Simple Spark Application Now that we have a Spark instance running on Bluemix we can start developing our Node program. For our example we will create a Bluemix application that uses Node to provide a webpage with a button that executes a simple Spark program. The full source code for this application can be found on Github. A Bluemix Node application is very similar to any other Node application, with two differences. One, there is a manifest.yml file in the root of the project that allows us to control an application’s environment by specifying parameters such as memory and disc quotas. Two, Bluemix provides environment variables that define the host and port to listen on so that the application can be accessed. As with any Node program we start with a package.json file, and we define our main file as index.js: { "name": "bluemix-simple-template", "version": "0.0.1", "scripts": { "start": "node --harmony index.js" }, "main": "index.js", "dependencies": { "express": "~4.12.0", "eclairjs": "*" } } The index.js file (located in the same directory as package.json) is shown in the next two code snippets, and it contains our backend logic and the setup for Express which we use to provide a simple web frontend for the example. The only Bluemix specific part here are the evironment variables VCAP_APP_HOST and VCAP_APP_PORT that are passed to Express: // index.js // use express for a webserver var express = require('express'); var port = process.env.VCAP_APP_PORT; var host = process.env.VCAP_APP_HOST; // setup the express server var app = express(); app.use(express.static('public')); var server = app.listen(port, host, function () { }); We now use Express to create an endpoint /do which will execute a very simple Apache Spark program. In this case we use Spark to parallelize an array of numbers, which will distribute the data among the Spark slave nodes. This will return an Resilient Distributed Dataset ( RDD) that represents the data stored across all the nodes. We then multiply each number in the RDD by 2 using the map operator, which traverses all the data and generates a new RDD. After that we collect the data from the nodes and send it back to the browser: // index.js, continued var eclairjs = require('eclairjs'); // our main entry point app.get('/do', function (req, res) { var spark = new eclairjs(); var sc = new spark.SparkContext("local[*]", "Simple Spark Program"); var rdd = sc.parallelize([1.10, 2.2, 3.3, 4.4]); var rdd2 = rdd.map(function(num) { return num * 2; }); rdd2.collect().then(function(results) { sc.stop(); res.json({result: results}); }).catch(function(err) { sc.stop(); res.json({error: err}); }); }); } We also create a public/index.html file to contain our frontend. It provides a simple form with a button that when pressed will call the /do endpoint using an XMLHTTPRequest, and then output the results to the web page. <!-- public/index.html --> <html> <head> <title>EclairJS Bluemix Example</title> "> <script> function _loadListener() { document.getElementById("result").innerHTML = this.responseText; // renable the run button document.getElementById("runBtn").removeAttribute("disabled"); document.getElementById("runMsg").style. <h2>EclairJS Bluemix Example</h2> <div> <button id="runBtn" type="button" onclick="doExample()" class="btn btn-primary">Run</button> <div style="display: inline-block; margin-left: 8px;"> <span id="runMsg" class="btn status bg-info">Running...</span> <span id="finishedMsg" class="btn status bg-success">Finished</span> </div> </div> <div id="result"></div> </div> </body></html> Deploying to Bluemix The final step is to deploy your application to Bluemix. To do this, login to your Bluemix account, go to the Dashboard and click on Create App. Choose Web for the type of application, select the SDK for Node.js bundle, and give your application a name during the rest of the setup. Once you have completed these steps on Bluemix, you will need to edit the manifest.yml file and change the value of the name parameter to the application name you just specified in Bluemix. In addition, change the value of JUPYTER_HOST to be the public IP address you previously assigned to the Spark-EclairJS container. applications: - path: . memory: 1024M instances: 1 domain: mybluemix.net name: Your_Application_Name disk_quota: 1024M env: JUPYTER_HOST: YOUR.IP.ADDRESS Bluemix is now ready to host the actual code of your application, so you can push your application to Bluemix by executing the following three commands in the directory where the application exists: $ bluemix api $ bluemix login $ cf push ... requested state: started instances: 1/1 usage: 1G x 1 instances urls: yourappname.mybluemix.net last uploaded: Sat Aug 13 02:18:39 UTC 2016 stack: unknown buildpack: SDK for Node.js(TM) (ibm-node.js-4.4.7, buildpack-v3.6-20160715-0749) state since cpu memory disk details #0 running 2016-08-12 07:19:36 PM 0.1% 85.6M of 1G 72.4M of 1G Pushing the application will cause Bluemix to install any dependencies listed in the package.json file. Bluemix will list the result of the push and if everything went as planned it will show the state of the application as running. You are now ready to access your application from a browser. The application’s public URL is provided as the value of the urls: field that was returned when you pushed the application, and it should have the form yourappname.mybluemix.net. Assuming you can access the URL, clicking the blue Run button will call the /do endpoint, execute the Spark code, and output the results on the page as shown in the screenshot below. Bluemix allows Node applications to easily scale, and EclairJS now allows Node developers to directly harness the large-scale data processing power of Apache Spark. Visit the EclairJS project to find out more and try out our examples including Spark Streaming and Machine Learning as well as our application examples. … [Trackback] […] Read More here: developer.ibm.com/node/2016/08/25/running-apache-spark-applications-with-node-js-on-ibm-bluemix/ […]
https://developer.ibm.com/node/2016/08/25/running-apache-spark-applications-with-node-js-on-ibm-bluemix/
CC-MAIN-2017-22
refinedweb
1,798
54.02
hey..I need to convert a 8 value bool array to char.How can I do this? You can use the bool array as a "bit-position" array for the representation of a char. #include <iostream> using std::cout; using std::cin; using std::endl; int main(){ bool bits[] = {0, 1, 0, 0, 0, 0, 0, 1}; char c = 0; for(int i = 0; i < 8; i++) c += (bits[i] >> i); // 0 or 1 times 2 to the ith power cout << c << endl; // should print out A cin.get(); return 0; } Edit: I'm not near a compiler, so the bit-shifting operator may need to be switched but the logic is straightfoward. Hopefully this helps! =) -Alex I had char boolsToChar(bool* bools){ char c = 0; for( int i = 0; i < 8; i++ ) if( bools[i] ) c += pow(2,i); return c; } but clearly this is not as nice a solution as above, For multiple reasons. One being that I get a warning for converting a double to a char and two I have a conditional statment that i clearly don't require Anyhow the solution above compiled for me, but I needed to change it around a little to come up with 'A'. bool bits[] = {1, 0, 0, 0, 0, 0, 1, 0}; char c = 0; for(int i = 0; i < 8; i++) c += (bits[i] << i); // 0 or 1 times 2 to the ith power cout << c << endl; // should print out A cin.get(); Hmm, try changing char to unsigned (if it exists @_@ ) Edit: I am really tired #_# I didn't realize I made the array back-asswards XD XP How about this, rather unusual method ;) #include <iostream> struct octet { union { char val; struct { unsigned h : 1; unsigned g : 1; unsigned f : 1; unsigned e : 1; unsigned d : 1; unsigned c : 1; unsigned b : 1; unsigned a : 1; }; }; }; int main() { bool bits[] = {0, 1, 1, 0, 0, 0, 0, 1}; octet o; o.a = bits[0]; o.b = bits[1]; o.c = bits[2]; o.d = bits[3]; o.e = bits[4]; o.f = bits[5]; o.g = bits[6]; o.h = bits[7]; std::cout << o.val; // 01100001 = 'a' std::cin.ignore(); } Theres practically no maths involved :) Thanks a lot! . ...
https://www.daniweb.com/programming/software-development/threads/158909/converting-bool-8-to-char
CC-MAIN-2017-26
refinedweb
375
79.9
Ole hyvä ja kirjaudu sisään! Jos et ole vielä rekisteröitynyt, sekin onnistuu ohessa. Howdy, Usually I have no problem replacing text on pages, but for some reason I am not getting it to work on Reverso.net. To demonstrate the problem, here is an absolutely barebones script: // ==UserScript== // @name Reverso Debug // @namespace reverso // @description Demonstrates problem with Reverso page // @include // @include // @version 1 // @grant none // @run-at document-idle // ==/UserScript== (function() { document.body.innerHTML= document.body.innerHTML.replace( new RegExp('DICTIONARY', 'g'), '<b>=== SUCCESS! ===</b>' ) })() As you can see, Using GM 3.9 which is the highest version supported by my browser. Would be hugely grateful for any help, as I am completely stuck. In advance, big thanks! Viestejä yhteensä Dictionarybut your regexp is not case-insensitive. Use 'gi'instead of 'g'. Thank you, @wOxxOm That sounds a lot more complex than it used to be! Will have a look at the examples you sent. Hello again @wOxxOm, Hope your day is going well. I spent the last few hours trying to experiment with TreeWalker. I see how it lets us modify the page one element at a time. With a basic replace example, it is running. But when I start to beef up the script, I must be making a basic mistake with the TreeWalker constructor, and at this stage I have hit a wall. I wonder if you would be willing to take a quick look at this excerpt in case something jumps out at you? There are two alert statements here: the first works (after defining the filter function), the second doesn't (after trying to create the TreeWalker). This excerpt starts at the stage where we've figured out that YES we want to modify that page (the do_replace boolean) and we have defined the adequate parse_pattern and replace_pattern. Thank you in advance for any thoughts you can spare! If you need to replace with HTML (that is to create a tag or change one), it's better to rework the whileloop and use direct DOM manipulation instead, which is something you can pursue yourself. A simplified and slower version of the loop for HTML is shown below: @wOxxOm Thank you for explaining all this. Alright, now understanding loud and clear that in dynamic pages I shouldn't replace innerHTMLdirectly... Thank you for insisting. The script I was working on does add a lot of tags. Because I still had a lot to do on it, I finished it in the usual way and shared it here on GreasyFork: Reverso Spanish Enhancer script But as soon as I have time I'd like to dive into what you are talking about, and make that my standard way of working going forward. I think once I have one script working in that way, it will be easier, but the first one is always the hardest. :-) Thank you for your extremely kind and careful help, which I really appreciated. Wishing you a great week! @wOxxOm Hope you've had a great week. I know how annoying it can be to spend time giving great advice to people who don't follow it... So I just want to let you know that I fully rewrote my Reverso Enhancer Spanish to use direct DOM manipulation instead of innerHTML.replace() It was a steep learning curve and makes the script quite a bit longer but it was worth it. Of course that's just the beginning — I realize that I have everything to learn as I never sat down to learn JS. Big thanks for your encouragements and support!!! Wishing you a fun weekend, -R
https://greasyfork.org/fi/forum/discussion/comment/65735/
CC-MAIN-2019-39
refinedweb
604
72.87
Rider 2020.1 now runs the backend on .NET Core runtime by default on macOS and Linux and delivers Xamarin Hot Reload and Dynamic Program Analysis. It introduces an easy way to configure the severity of the editor, and it adds dataflow analysis for integer values as well as faster code completion. The Debug window has been reworked, and the Extract Class refactoring and Coverage Filters are now available. Say hello to Rider .NET Core edition! The backend finally runs on .NET Core runtime by default on macOS and Linux, instead of the Mono runtime. You will instantly notice: By the way, the current .NET Core version is the latest and greatest 3.1, which has a lot of performance improvements compared to the 3.0 version. Please note that there is no Windows support for now, only macOS and Linux. We are planning to add Windows support later this year. Do you want to learn more about the transition from Mono to .NET Core and see the performance charts? Check out this blog post! If you experience any problems with the Rider backend running on .NET Core and want to move back to the Mono runtime, select Help | Switch IDE runtime to Mono. And if anything goes wrong for you, don’t forget to tell us. Initial support for Xamarin Hot Reload is here! Now Rider automatically applies changes made in Xamarin Forms XAML to the application under debugging on a device or a simulator, without rebuilding and redeploying the whole application. Please note there is a limitation: If a PC/laptop with Rider and an iOS device are not in the same WiFi network, a Hot Reload will not work, even if the iOS device is connected to the PC/laptop through USB. Apart from that, Xamarin support gets one important fix: the “Invalid target architecture 'arm64e'” error no longer appears when running Xamarin.iOS projects on an iPhone XS Max device. Check the blog post for more updates. We are happy to introduce Dynamic Program Analysis. Every time you run your project in Rider, DPA starts collecting memory allocation data. Once you close the application, DPA will show you a list of detected problems: closures, and allocations to large and small object heaps. The great thing about it is that you do not need to start any “profiling sessions” and get snapshots. Just work as usual, and all the data will be collected in the background, with almost zero overhead. Testing DPA on a variety of real solutions has demonstrated a slowdown of only 0 to 2 percent. Please note: DPA is available only on Windows, and you do not need a separate license to activate it. Learn more: Auto-Detect Memory Issues in your App with Dynamic Program Analysis This version of Rider introduces a new type of code analysis to track the usage of integer values in your application. This new type of analysis tracks how the values of all int local variables vary, and it verifies the correctness of all common operations on such variables to detect useless or possibly erroneous pieces of code. Namely, it warns you about: trueor falseresults. switchcases checking intvalues. 1, addition of 0, etc. intoverflows. 0. To improve the precision of analysis, we’ve also added two new JetBrains.Annotations attributes to use with type members and parameters of the int type: [NonNegativeValue] and [ValueRange(from, to)]. These attributes specify how the values of the particular int members can vary in runtime. ScriptableObjectsand values of serialized fields. Boo.Lang.Listor System.Diagnostics.Debugin its code completion for Unity projects.). In Rider 2020.1, code analysis reports compilation warnings related to nullable reference types and provides quick-fixes for most of them. There are also several new inspections and quick-fixes: asyncoverloads of methods when available instead of syncoverloads. nameofexpression instead of using the typeof(SomeType).Name construction to get the name of the current type. Over the past year, we have received a few reports of the code completion popup taking too long to appear. We’ve done our homework, and now the code completion popup displays much faster after you begin typing, especially in large solutions. Another very handy feature that has landed in this release is that members marked as Obsolete can be hidden in code completion if you don’t want to see them there. Last but not least, completing an item from the code completion popup now respects your code style settings. We have completely reworked the UI for the Debug tool window to make it as clean and uncluttered as possible. When there’s only one debug session running, the tabs layout is simplified, as all tabs are now on one single level. Tab captions take up less space, so there is more room for debugger content. And when there are multiple sessions, one more tab layer is added to separate the sessions. At the same time, we’ve combined the Threads and Frames views. If you don’t need the Threads view at the moment, you can hide it by clicking the “Hide threads view” icon. We have also updated the debugger engine to make your debugging experience even better: This new feature lets you easily change the editor’s highlighting levels. With just one click from a non-modal popup, you can turn on or off Code Vision, Parameter Hints, Unity Performance Hints, Errors, Warnings, Suggestions, Context actions, and many more elements. Look for the Pencils icon in the bottom right-hand corner of the code editor tab. We’ve tweaked the toolbars in the Unit Test Session and Unit Test Explorer windows. In addition to that, we’ve added three big features: Learn more: Test Runner Updates in Rider 2020.1 In Rider 2019.3, we added an experimental TFS client which provided a dramatic speed improvement for the "Checking for changes" action. In the current release cycle, we’ve continued to put a lot of effort into the client. Finally, our TFS client hits its first release and brings a lot of improvements. Let’s mention the two most significant ones. First, enabling the Version Control Integration now works for TFS workspaces locally created with Visual Studio. This means you no longer need to re-create a local workspace from scratch in Rider. Second, we have greatly boosted the performance of the Delete and Rollback operations. To start using the TFS client, go to Settings | Version Control | TFVC and enable it. Rider, like all JetBrains IDEs, now uses JetBrains Mono as the default font in all themes. We hope you will enjoy it! One more ReSharper feature that has been missing in Rider until now is finally here: namespaces can be auto-imported when code is pasted from a file in the solution. If you edit NuGet-related files manually, we think you’ll be happy to get assistance from Rider, as it now offers initial support for editing NuGet.Config, packages.config, and *.nuspec files, including code completion, syntax validation, and the quick documentation popup. These smaller enhancements are also worth mentioning: One more highly requested and long-awaited refactoring available in ReSharper has finally arrived in Rider – Extract Class. Wondering why you need this? Imagine you have a class doing work that should be really done by two different classes. Using this refactoring is the safest and most effective way to decompose that complex class into two single-responsibility classes. Extract Class will help you choose methods and fields to move from the old class to the new class. It will also warn of any broken dependencies and accessibility issues, and suggest conflict resolution options. The Solution Explorer view introduces two new useful folders that provide you with more information about your project: Implicit references as a subfolder for the Assemblies folder, and MSBuild import targets. In addition to that, there are several small updates: To give you more control of the unit test coverage results that you get in Rider, we’ve added Coverage Filters. To specify them, go to Preferences/Settings | Build, Execution, Deployment | dotCover | Filtering. If you do performance profiling on Linux or macOS, we have good news for you: .NET Core applications can finally be profiled in Tracing mode on these operating systems. Also, you can now attach the profiler to .NET Core applications on Linux. We’ve added several new features to Rider’s decompiler and IL Viewer: To improve F# support in Rider, we’ve made tons of improvements and fixes that should help you in your daily routine: this.Property), and indexer expressions ( "foo".[1]). ()expression. For more updates and fixes, please see the GitHub repo. What’s New in IntelliJ IDEA 2020.1
https://www.jetbrains.com/rider/whatsnew/2020-1/
CC-MAIN-2022-40
refinedweb
1,453
56.15
On Mon, Aug 1, 2011 at 3:11 PM, Vasiliy Kulikov <segoon@openwall.com> wrote: >. > > Can you please identify what commit breaks the system? Reverting this one fixes the oops for good: 5774ed014f02120db9a6945a1ecebeb97c2acccb (shm: handle separate PID namespaces case) >> The following oops is >> printed on boot, and as a result, more than 300 zombie kworker >> kernel processes are resident. I don't see this oops on x86 or x64. > > Do you have the same configs for x86 and mips? MIPS is UP, SLAB without preempt, x86 is UP/SMP, SLUB with preempt. It's not SLAB/SLUB and not preempt, and both MIPS+x86 have all namespace options enabled. both configs are temporarily available here: Thanks! Manuel Lauss
http://www.linux-mips.org/archives/linux-mips/2011-08/msg00007.html
CC-MAIN-2015-48
refinedweb
118
74.39
import Koa from "koa"; import Router from "koa-router"; import request from "supertest"; const app = new Koa(); const router = new Router(); const client = request.agent(app.listen(3000)); router .get("/", async (ctx, next) => { try { let cv = ctx.cookies.get('temp'); if (cv) { The console.log(cv)// the second request did not get the value of the cookie, and the cookie was not stored, possibly because the content-type is set incorrectly. ctx.type = 'image/jpeg'; ctx.body = '233'; //Originally it was a buffer type data, which is brief here. ctx.status = 200; } else { await ctx.cookies.set('temp', '123456', {maxAge: 99999}); ctx.type = 'image/jpeg'; ctx.body = '233'; ctx.status = 200; bracket } catch (e) { console.log(e) ctx.status = 400; bracket }) app .use(router.routes()) .use(router.allowedMethods()); describe("test", () => { it("1", done => { client .get('/') .expect(200, (err, res) => { if (err) { done(err) } else { //The first request is that header inside has a set-cookie cookie = res.header["set-cookie"][0]; console.log(cookie); done() bracket }) }); it("2", done => { client .get('/') .expect(200, done) }); }) However, after I changed the content-type to another type, it can be stored correctly. Is there a problem with setting the content-type to image/jpeg? I checked that there is the content-type image/jpeg. Different browsers have different treatments for different content-type. It was found that these treatments were customized by the browser manufacturer after customization of the browser. So I guess it is possible that you gave image. His logic inside thinks there will be no cookie addition. Try a different browser?
https://ddcode.net/2019/04/20/why-cant-i-store-cookie-after-setting-content-type-to-image-jpeg/
CC-MAIN-2021-21
refinedweb
261
62.04
as written in MDN at July 2016: This feature is not implemented in any browsers natively at this time. It is implemented in many transpilers, such as the Traceur Compiler, Babel or Rollup. So here is example with Babel loader for Webpack: Create folder. Add package.json file there: { "devDependencies": { "babel-core": "^6.11.4", "babel-loader": "^6.2.4", "babel-preset-es2015": "^6.9.0", "webpack": "^1.13.1" } } Open folder in command line. Run: npm install. Create 2 files: cats.js: export var cats = ['dave', 'henry', 'martha']; app.js: import {cats} from "./cats.js"; console.log(cats); For proper using of babel-loader should be added webpack.config.js file: module: { loaders: [ { test: /\.js$/, exclude: /(node_modules|bower_components)/, loader: 'babel?presets[]=es2015' } ] } Run in command line: webpack ./app.js app.bundle.js Now in folder will be file: app.bundle.js. Create index.html file: <html> <body> <script src='app.bundle.js' type="text/javascript"></script> </body> </html> Open it in browser and see result in console: [ 'dave', 'henry', 'martha' ]
https://riptutorial.com/webpack/example/20995/usage-es6--babel--modules-example
CC-MAIN-2021-49
refinedweb
171
55.81
JCU’s ‘power couples’ of 2013, p. 10-11 CARROLL NEWS THE The Student Voice of John Carroll University Since 1925 Thursday, February 14, 2013 Tuition for 2013-14 year set to rise Ryllie Danylko Dan Cooney The Carroll News John Carroll University’s full-time undergraduate tuition rate will increase 3.9 percent for the 20132014 school year to $33,330. The rate was $32,130 for this current school year. In addition to the tuition hike, “room and board rates for next year’s resident students will vary based on the building, room type and amenities and meal Tuition of some Ohio private universities – Information provided by Richard Mausser plan chosen,” according to a letter written by JCU President, the Rev. Robert Niehoff, S.J. dated Feb. 8 and addressed to parents and guardians informing them of the increases. A detailed breakdown of the cost of attendance for undergraduate students available on jcu.edu/tuition lists the room and board price at $10,040, which is the cost of a standard double room with a 14-plus meal plan (14 meals per week with 100 plus points). Please see TUITION, p. 3 Franciscan Muskingum Baldwin Wallace Mount Union Otterbein University Capital University John Carroll University Ohio Northern University Case Western Reserve University Oberlin College Vol. 89, No. 14 Students petition to keep profs Jackie Mitchell Assistant Campus Editor A petition is circulating around John Carroll University to allow two Gerard Manley Hopkins visiting professors from the English department Robert ‘Bo’ Smith and Thomas Roche, to teach at JCU for a longer period of time, according to statements made during the open forum at last week’s Student Union meeting. Smith and Roche began teaching at John Carroll in the fall of 2011 through the Gerard Manley Hopkins Professorship in British Literature. Their visiting professorships are scheduled to conclude at the end of this semester. The petition was created by junior Emily Stolfer, who took Smith and Roche’s Major British Writers class last year by chance. “I was supposed to have Mary Moroney. I heard the teacher was changed, and I was scared because I am not the best English student, so I was seriously considering dropping the class,” she said. “After the first class, all those worries and inhibitions went away because they created a supportive active environment for me to really learn the material. Since then, I have taken Bo’s Acting for Shakespeare class and am currently in his Acting for Film [class].” She continued, “They have meant so much to me the past two years that I had to try and keep them here. These professors are in demand, and they want to stay with us at our school. They deserve to stay here and students love them, so I am fighting so they can.” Chair of the Department of English John McBratney said that Hopkins visiting professors do not typically stay at JCU for a long period of time. “It was envisioned from the beginning as a kind of temporary appointment,” he said. “And their appointment is actually the longest of any of the Hopkins professors. Before them, at most, I think a Hopkins professor had been here Please see PETITION, p. 3 Cost of attendance with room and board Lil’ Sibs Weekend filled with smiles eteria,” Malloy said. She said one of the kids’ favorite parts, though, was meeting all of her friends and seeing Staff Reporter what the college experience was all about. “All they really know of college is that Lizzy is Once again, Lil’ Sibs Weekend brought students and their siblings together for a week- off at school, and she tells crazy stories when she comes home. Having them here, they get end of fun-filled activities. This year, however, brought about a few changes from the event to explore this home-away-from-home in every way,” she said. in past years. The “Paradise” theme took a long time to plan. Jessica Kreuzer, president of Please see LIL’ SIBS, p. 2 the Residence Hall Association, said, “Between myself and my executive board of Brittnay Madore, Rachel Distler and Alexandra Freyvogel, as well as our advisers, Lord Edwin ‘Eddie’ J. Carreon and Jessica Chandler, plus our wonderful RHA members, everyone played an important part in organizing this past weekend.” Fifty-five students participated; the majority of siblings, all 12 years old and under, arrived Friday night. Kreuzer explained that the weekend was a success, considering RHA worked to provide activities that both the siblings and the students would enjoy. “I think Lil’ Sibs Weekend is important for students at John Carroll because it gives the students a chance to hang out with their siblings in a different atmosphere rather than just hanging out at home,” she said. While most students invited their brothers and sisters for the weekend, many also invited other friends of family. Sophomore Liz Malloy invited her 11-year-old brother, Tommy, and 9-year-old sister, Vanessa, as her “little sibs.” She said, “It was a huge hit with Tommy last year, so we invited Vanessa to come out and spend the weekend with us too.” The students and their sibs were provided activities throughout the day Saturday to parPhoto courtesy of CSSA ticipate in, including watching Jungle Terry, the showing of the movie “Madagascar,” and a Sophomore Christine Varricchio volunteered to work with US Together refugee carnival of games. children on Lil’ Sibs Weekend. “The big hits of Saturday were swimming, making build-a-bears and dinner in the caf- Alyssa Brown Index Campus Arts & Life Sports World News 2 4 6 12 Finance Diversions Editorial Op/Ed Classifieds 14 15 17 18 20 Inside this issue: Pope Benedict XVI announces resignation, p.13 Find us online issuu.com/ Like us on Facebook @TheCarrollNews thecarrollnews Campus 2 Feb. 14, 2013 Campus Briefs The Carroll News Putting their skills to good use Business students help local lower-income families file taxes Delta Tau Delta wins international award The John Carroll University chapter of Delta Tau Delta has been awarded a Hugh Shields Award for their overall excellence. A Hugh Shields Award is awarded to the top 10 chapters of Delta Tau Delta in the world. JCU’s chapter is currently ranked third out of 123 chartered chapters worldwide. A Hugh Shields Award is the highest honor that can be bestowed on a chapter of Delta Tau Delta. The members of the fraternity said they are honored, humbled and excited to have the award bestowed on them and are happy that their hard work has paid off. The Living Person presents ‘Dare You to Move’ Campus Ministry and The Living Person are presenting “Dare You to Move,” a program to celebrate life and learn more about The Living Person challenge. The event will focus on challenging individuals to make a commitment to their spiritual, intellectual and/or physical pursuits in order to give greater glory to God. The event is free and will include musical guests Chelsea Gilbert and Sam Brenner. In addition, John Greco of the Cleveland Browns will come to talk about how his faith life has influenced his professional football career. Food, games and prizes will be provided. The event is from 9 p.m. to 12 a.m. in the Atrium of the Lombardo Student Center. Nominations now being accepted for the Beaudry Award Nominations are now being accepted for the Beaudry Award, the only student award given at commencement in May. The award is given to a graduating senior for his or her achievement in the following areas: academic achievement, commitment to Christian values, leadership activities and service to the John Carroll University community and/or the local community. All students, staff, faculty and administrators are welcome to nominate a graduating senior for the award. Nomination forms are avaliable in the Campus Ministry office and online at the Campus Ministry website. Forms are due Tuesday, March 12. and moderate-income working families through tax reductions and wage supplements. The EITC Coalition provides free tax Staff Reporter preparation at different locations to low-income families in the community, reducing taxes and increasing refund. The coalition’s As Benjamin Franklin put it, “The only things certain in life primary focus is to aid employed workers in maintaining their are death and taxes.” However, low-income families often need independence from welfare and does this with the help of local help preparing their taxes in the most cost-effective manner. volunteers. VITA, a program funded by the IRS, offers free tax help to people The coalition recruited JCU students, alumni and staff volunwho make $51,000 or less and need assistance in preparing their teers to prepare the taxes of qualified low-income families. To tax returns. This program provides low-income families with become a volunteer, an individual had to possess a certain level IRS-certified volunteers who offer free basic income tax return of comfort with taxes and tax law. The University held a six-hour preparation. Through this program, qualified individuals in the training session on Jan. 26, where a member of the coalition local community can go to libraries, shopping malls and other taught volunteers how to use web-based software programs proconvenient locations and receive preparation and electronic filing vided by VITA and issued through the IRS. of their taxes. Not only does this program provide help to the community, Ted Steiner, the coordinator of immersions and special probut it also provides students with real-life experience preparing grams for the Center for Service and Social Action, said, “Taxes taxes. “This program teaches the volunteers about people’s lives, are something everyone has to do and something everyone because when you do taxes, you learn a lot about a person. From struggles with; so if there’s a way to help, we should be doing it.” this experience, volunteers will receive real-life education,” said Enter The Earned Income Tax Credit (EITC) Coalition. The Steiner. “We also recruit volunteers to help out at the Famicos EITC is a refundable tax credit that increases the income of lowFoundation, a not-for-profit affordable housing developer and social service provider, on five Saturdays during tax season. These dates include Feb. 16 and 23, March 16 and 23, and April 13. Students, alumni and staff are all invited.” “It’s a different way to help people out,” said senior Erica Deimel, who is volunteering. “Taxes are confusing to people. It’s a very serious offense not to file your taxes. It’s knowledge that I have to help people. We kind of get to know them in a very different way. I’m looking foward to the experience.” Senior Rich Mazzolla said volunteering helps him find a happy – Ted Steiner medium between service and something he enjoys doing. “I know Coordinator of Immersions and a lot of accounting majors like the extra practice,” he said. “It’s Special Programs for CSSA tough for business students, other than physical labor, to give back doing something that we do.” Lauren Kluth “Taxes are something everyone has to do and something everyone struggles with; so if there’s a way to help, we should be doing it.” Students bond with lil’ sibs over balloon animals and face paint From LIL’ SIBS, p. 1 In addition to the normal activities, seniors Asurupi Gurung, Lauren Gunderman, Esther D’Mello and Cedric Jackson, all members of the Arrupe Scholars Program, organized for 24 local children of refugee parents from Nepal and Bhutan to come to JCU, acting as student volunteers’ “little sibs” for Saturday’s events. Junior Julia Blanchard volunteered as a student sib. “The boy who was my little brother for the day was 9 years old. He really loved getting his face painted and the balloon animals,” she said. The students and kids got more than just balloons from the event. Blanchard said, “It was a lot of fun. I loved getting to hang out with the kids because I don’t get to hang out with them very often, and they really seemed to enjoy themselves. They didn’t lose energy the entire day; they didn’t even want to go home.” Gurung, Gunderman, D’Mello and Jackson had been planning this event for the entire school year. “We were inspired by our previous experiences with the refugees in Cleveland,” D’Mello said. Once a month, John Carroll teams up with US Together, a refugee resettlement agency, and brings parents and children to the University for a day. Adults are given help with a variety of things, including resume building, computer usage and interviewing skills, while the children have learning activities. “The Arrupe Scholars organization was given funds by the DepartPhoto courtesy of CSSA ment for Applied Ethics to bring the refugee children from US Together to campus for Lil’ Sibs Weekend festivities,” Jackson said. The Junior Megan Hazel spent time with children from Nepal and Bhutan during Lil’ Sibs Weekend. project was a way of culminating their “Refugee” senior project. Correction: In the Thursday, Feb. 7 issue of The Carroll News, we wrote that there would be 25 tickets available for the Taylor Swift concert sponsored by SUPB. There will only be 16 tickets available. Campus Safety Log January 30, 2013 February 3, 2013 Auto accident hit-skip reported on the Main Drive at 7:03 p.m. Criminal mischief reported in Sutowski Hall room 234 at 4:13 a.m. February 1, 2013 Theft reported in the RecPlex at 2:26 p.m. February 5, 2013 Theft reported in the Boler School of Business at 7:31 p.m. These incidents are taken from the files of Campus Safety Services, located in the lower level of the Lombardo Student Center. For more information, contact x1615. Campus 3 The Carroll News Feb. 14, 2013 Next year’s tuition revealed: JCU ranks in the middle From TUITION, p. 1 However, with the renovation of Murphy Hall, students will have the option of living in triples next year for a lower rate. A full list of rates is available on jcu.edu/reslife. Richard Mausser, the University’s vice president for finance, said the concept of pricing room and board differently based on the options chosen by students is called differential pricing. He said that while the renovation of Murphy Hall is part of what motivated this change, most other universities already use this model, so JCU probably would have adopted it eventually. “The Murphy project is going to be a different kind of housing stock than we have in place right now across-the-board. A double in there we cannot price the same as a double someplace else,” he said. “It’s going to force us in that situation anyway, so we wanted to get to that place now.” He said this model makes more sense given the variations in quality of residence halls. For example, some of the residence halls are air-conditioned, and those rooms will cost more than those that are not. The University raised tuition 4.8 percent for both last school year (2011-2012) and this school year. Full-time undergraduate tuition was $30,660 during the 2011-2012 school year. Both the technology fee and health and wellness fees will go up $50, to $450 and $300, respectively. The Student Activity Fee will remain at $400 for next school year. The combination of tuition and fees, without room and board, brings the total to $34,480 for full-time undergraduate students for next school year. Students taking classes at the University this summer will pay $700 per credit hour, the same amount charged last year. Mausser said the main priorities when determining tuition costs for each academic year are maintaining the quality of education and staying competitive. Things like maintenance, health care and the IT infrastructure are putting increasingly expensive demands on the school financially, and Mausser said he and his colleagues must carry out this “balancing act.” Tuition is not the first place that the board turns when trying to cover these costs, he said. Mausser also said that the tuition increase by itself does not cover these costs. “We have gone to virtually every one of our external vendors and either switched them or restructured deals with them to significantly reduce our cost base,” he said. According to Mausser, the process involved with determining tuition raises is a complicated one. A main component of this is staying up-to-date with the tuition of schools similar to JCU, both geographically and academically. “We have to be informed about what’s happening around us … It’s market-driven now,” Mausser said. He emphasized that the University’s Board of Directors ultimately make the decision on fee schedules and works hard to keep the cost of tuition down. “The board members do not take tuition increases lightly,” he said. “There’s a pretty in-depth conversation that goes along with the tuition increase. This year, we didn’t want to go where we were at in prior years, and we didn’t. The president would have liked to have kept it lower, but we had these competing issues of cost and balance,” said Mausser. He also stressed the importance of JCU’s net price – the amount students pay after subtracting financial aid and scholarships – over what he terms the “sticker price” of $33,330. “The sticker price, which is what the increase gets applied to, is irrelevant, I think, because nobody pays the sticker price,” Mausser said. “Financial aid and net tuition is what everybody’s looking at, and I think that’s what everybody should look at.” According to numbers from the National Center for Education Statistics and its College Navigator, JCU’s average net tuition price for full-time beginning undergraduate students has decreased over the past three school years for which statistics are available. From an average net price of $21,945 in 2008-2009, the rate dropped to $21,850 in 2009-2010 and $21,322 in 2010-2011. The averages reflect costs for resident students, not commuters. Cost is consistently a concern for prospective students and their families, said Brian Williams, the University’s vice president for enrollment. But he believes JCU is in a favorable position regionally and nationally with the cost and value of a Catholic education at a private institution. “Our admission process addresses cost and value in a very upfront and direct way with families. Our staff is very personalized with families and provides a clear sense of why they should consider a JCU degree and experience,” Williams said via email. “As one example, we have a college cost calculator on our site that was completed by over 500 families this fall. I believe the way our enrollment staff works as an admission and financial contact for families allows us to get to know families and their unique concerns early in the process. This allows up to help them through the scholarship and need-based process and let them see that it is possible to plan for and afford John Carroll.” Despite the rise in the full-time undergraduate tuition rate for next year, interest in JCU has grown among prospective families. As of Feb. 10, according to information from Williams, the University is ahead in applications and acceptances compared to last year. So far, JCU has received 3,457 applications and accepted 2,793 of those applicants. “This has allowed us to act on admissions decisions and offer acceptances much earlier, and we are actually 11 percent ahead in offering admission to students,” he said via email. “We still have a lot more work to do between now and May 1 to make sure that students choose to enroll at JCU among the other offers they receive.” According to the John Carroll University 2012-2013 Fact Book, freshman enrollment dipped this year. While JCU received more inquiries and applications, and accepted more students, fewer enrolled. Freshman enrollment rose from 661 in 2009, to 702 in 2010 and 744 in 2011. In 2012, 681 enrolled as freshman at JCU, out of 3,490 applications submitted and 2,843 accepted. Williams said the University is focused on bringing freshman enrollment back above 700 students for the class of 2017. “We have a solid number of new majors being added at the school over the last few years that students are starting to see; and beyond the classroom, we are adding lacrosse to our athletic offerings, the upcoming Murphy Hall renovation and have many good stories to tell students,” he said. “Those positive stories in the media and in our process are really beginning to take hold.” Williams said that institutional aid awards are level-funded, which means that the amount awarded initially to students stays the same throughout his or her four years. In addition, JCU need-based funds don’t diminish based on the Free Application for Federal Student Aid (FAFSA), which is a practice maintained at many other institutions. “Current students should always explore all of the options available to them whether as grants, loans or student employment options. Our financial aid staff is the best first point of contact to have that discussion,” Photo from JCU website Williams said. “Specifically, when families Richard Mausser, vice president for have seen a significant change in their family finance, explained how various factors income and savings from when they started contribute to the price of tuition. The at JCU, we try to help families through our tuition for the 2013-2014 academic year appeals process as best as we can.” will be raised 3.9 percent to $33,330. Students vying for visiting professors to remain at JCU From PETITION, p. 1 for an academic year ... And typically they’re here for a semester or even less,” he explained. While McBratney was unaware of any petitioning for Smith and Roche, he said the information did not take him by surprise. “It doesn’t surprise me because a petition was begun at the University of Notre Dame, where they were previously, and that petition was heard, but it was rejected,” he explained. Nevertheless, JCU students are fighting to have their petition heard. “John Carroll would be at a huge loss if these two men were to leave the school. Their credentials alone should be 14 enough for them to stay. To say the least, they care about their students’ both intellectual and personal growth,” said junior Luke Hearty, a supporter of the petition. Senior Rachel Halle, who also signed the petition, echoed these sentiments, and said, “I have never had a pair of professors who have helped me more in class than these two men. I have learned more in a class with them in the last four weeks than I have in any other class. Bo and Tom are the best professors I have ever had.” Although the professors are well liked and highly respected, McBratney said he doesn’t anticipate an extension of the professors’ time at John Carroll occurring. The department faces the limitations of the Hopkins professorship program as well as difficulties scheduling courses if the professors were to stay for a longer dura- tion of time. “The way that the Hopkins professorship is structured, they really can’t stay beyond this year. I’ve talked to John Day, the provost and academic vice president, and he’s been quite clear about this, that as much as we really like them, and value them we can’t convert the Hopkins into a kind of extended professorship,” McBratney said. “I think it’s really out of the question, from my standpoint, just given what the provost has said, and also given that we’re hiring a tenure track assistant professor in Renaissance literature in the fall. We’re actually interviewing job candidates for that position right now. This would be someone to succeed Christopher Roark. Given that, I think it’s really unlikely that we would have room for them, as much as we would like to make room for them.” Campus Calendar : Feb. 14 – Feb. 20 Thursday 15 Friday “One Billion Rising” SUPB wing and spa flash mob at 10:50 night at 9 p.m. in the a.m. at Grasselli Dolan Atrium. Library and 12:45 p.m. in Schott Dining Hall. 16 Saturday SUPB off-campus bowling event at 7 p.m. 17 Sunday 18 Monday Kulas Grant sponsors President’s Day the Blue Man Group at the Palace Theater from 6:30 to 10 p.m. 19 Tuesday SUPB Spring Concert Series hosts Passion Pit at the Cleveland Masonic and Performing Arts Center at 7 p.m. 20 Wednesday “Backpacks to Briefcases” program sponsors a cooking workshop at Cuyahoga Community College from 6 to 8 p.m. Arts & Life 4 Feb. 14, 2013 The Carroll News Warm up & rock the city Ohio City showcases its fourth annual Brite Winter Festival ing to Fox, “Close to half of the festival are upcoming artists from Northeast Ohio, and the other half are traveling in from several regions of the Midwest and east coast.” Genres range from indie, folk, electronic, acoustic, rock, soul and punk. Featured artists include, but are not limited to, “The Floorwalkers,” “Total Babes” and “Bethesda.” “Brite Winter is non-stop action, which is good because you have to keep moving to keep warm,” added Fox. Last year, this one-day only festival attracted around 10,000 music-goers. The same, if not more, is predicted this year. With the help of their sponsor, GE Lighting, the talent and art illuminate the city. Other sponsors include The Cleveland Institute of Art, the Cleveland Museum of Art, Cleveland State University and Old Angle. “Students should take the RTA down, especially those of legal drinking age since Brite Winter will have an outdoor beer garden,” advises Fox. “This is one of the largest music festivals that will happen in Cleveland all year round, and it is completely, 100 percent free.” Stop over, warm up, stay awhile, meet new people and see what the city has to offer. Alexandra Higl Arts & Life Editor Battling the winter blues? Have a case of the cold weather jitters? The cure to heat up with some music, art and good company is just around the corner. The fourth annual Brite Winter Festival returns to Ohio City’s Market District on Feb. 16. Brite Winter kicked off in 2010 under the direction of Case Western Reserve University graduate students and is currently run by a volunteer committee. JCU Alum, Thomas Fox ’08, co-chairs the winter music extravaganza. Fox is the managing partner of Cleveland’s Bad Racket Recording Studio – the company that selected the festival’s musical talent. “I personally got involved with Brite Winter on recommendation from a friend,” said Fox. “The idea of getting people together for an outdoor party with live bands in the winter time seemed bold, difficult and awesome – so I went for it. Three years later, it’s one of the best things I’ve ever worked on.” The breakdown of the festival: 48 bands, six stages, giant Skeeball and 18 art installations – all at the ready to entertain young Clevelanders for no cost. Over 1,200 bands throughout the country applied for the chance to rock their way into the hearts of the Brite Winter crowd. Accord- Photos from britewinter.com A fashion week to remember The CN highlights Fall 2013’s New York Fashion Week Karly Kovac Staff Reporter The styles on the runway were not the only thing capturing attention at this year’s Mercedes Benz Fashion Week in New York City. With people eager to see 90 top designers’ collections and a snow storm that barely carried everyone into the Big Apple safely, French publishing exectuive Marie-José Susskind-Jalou was not happy. Just as the opening show began (Zac Posen’s collection) a group of fire marshalls ordered the clearing of 60 seats due to the arrangement being a fire . nel.. ha om C hazard. Public relations attempted to rectify the situation, but the iritatated Susskind-Jalou was not pleased at the seat change. This dispute led to Susskind-Jalou slapping one of the seat coordinators in the face. Though a $1 million dollar lawsuit is pending due to the incident, this episode was a minute disruption compared to the fabulous week that was filled with up and coming new styles for 2013. With many powerful statements made by the world’s top designers, the styles from Chanel stole the show this year with the “hula hoop bag.” Designer Karl Lagerfield’s idea for the bag is both innovative and practical. Lagerfield said in Vogue Magazine, “You need space for the beach towel, and then you can put it into the sand and hang things on it.” Other styles included a restoration of the print jean trend, with models sporting more of a wide-flare fit and a Big Bird-inspired line by the designer Céline. Some sources feel that this may be a political stand against the potential cutting of national funds for the PBS channel. Although there were many show-stopping numbers on the runway this year, makeup was a definite and alternate focus. Chanel’s bejeweled eyebrow trend emphasized the beauty of not just the clothes that the designers make, but the exquisiteness of the models that advertise them. Designer notables...Fr From Kate Spade... More information available at britewinter. com and facebook.com/britewinter Pick-Up Line of the Week “Hello. Cupid called. He says to tell you that he needs my heart back.” Have a pick-up line you’d like to share with us? Submit it to ahigl15@jcu.edu. Entertainment Calendar “Night of the Loving Dead: Flim with Live Music” om He rve Le ger... SPACES 8 p.m. $9 2.15 Blue Man Group PlayhouseSquare Palace Theater 7:00 p.m. $10 2.16 “Avenue Q – School Edition” Beck Center for the Arts 7:30 p.m. $12 2.20 The flirty and fun polka dot collection The hul a hoop b ag Cavaliers vs. New Orleans Hornets Fashion Week 2013: Feb 7 -14 The d r hoo u f x u fa Photos form glamour.com Quicken Loans Arena 7:30 p.m. $10 Arts & Life The Carroll News Love, hate and the supernatural MOVIE REVIEW “Beautiful Creatures” Samantha Clark The Carroll News “Beautiful Creatures” is the film adaptation of a novel by the same name written by Kami Garcia and Margret Stohl. Starring Alden Ehrenrieich (Tetro, 2009, and Twist, 2011) as Ethan Wate and Alice Englert (The Water Diary, 2006 and 2008) as Lena Duchannes. On the first day of Ethan’s junior year he wakes from a recurring dream of a girl he doesn’t know, only to find that she has transferred to his small-town high school. The town The Valentine’s Day Playlist 5 of Gatlin, S.C. hasn’t had a new student since the third grade. The new girl, Lena Duchannes and her family of “Casters” (the movie’s name for witches) quickly become the talk of the town. As the two grow closer, secrets of the town of Gatlin are uncovered, and the powers of light and dark fight over the destiny of one girl are revealed. The promotional commercials that have been broadcast on television lend the impression that this movie is dark and intense. While it is a rather intense look at the supernatural, it is also a high school love story. There are just enough comedic moments to make the audience laugh as well as scenes that invoke curiosity. The storyline itself is fast enough to keep the watcher’s interest while lingering in the right places to amp up the mystery factor on the things the audience isn’t in the know about yet. Interspersed between the “scary images” and slight violent scenes are several sexual innuendos. Clearly, this movie was designed to entertain and not to provoke thought; but in the middle of the semester, when it’s freezing outside, this is a great way to lift the cold weather blues. This movie had it all: a plot teeming with moments of laughter, sadness and intrigue. Photo from paranormal-goddess.blogspot.com Feb. 14, 2013 Behind the scenes... The CN had the opportunity to chat with some of the cast and directing team of “Beautiful Creatures.” Here’s what they had to say: The Carroll News: What’s the story about, who are your characters and how do they relate? Alden Ehrenreich: Well, I play Ethan Wate, a young guy living in a small town who is desperate to get out of this town. I meet Lena Duchannes who is the new girl in town, and I have all these visions of adventures in the life I want to live outside the town. When I meet her, she sort of embodies everything that’s exciting and all those adventures. Then it turns out she is a caster, and we have to struggle against the forces of her family that are trying to keep us apart so we can stay together. Alice Englert: And on the other side of it, Ethan [helps] Lena display her humanity, which in the end actually redeems and elevates the cast again. Emmy Rossum: Ridley is a dark caster; our characters call themselves “casters,” that’s a fancy name for witches that they preferred to be called casters. And Ridley had been claimed for the dark side when she was 16. And so she has been kind of fully embracing that side of herself, and she is a bit of villain in the book and in the film. But a different kind than we have seen before. The movie is obviously based on a bunch of young adult novels, all of which I’ve read. But I had only read the first one before I understood and got the part. So I was relatively new to the series myself. – Interview by Paul Mullin For the complete interview with Alden Ehrenreich, Emmy Rossum and Alice Englert, visit jcunews.com. Who is your celebrity crush? “Mine” Taylor Swift “No One” Alicia Keys “My Heart Will Go On” Celine Dion “Maybe I’m Amazed” Paul McCartney “I Got You Babe” Sonny & Cher The Singles Awareness Day Playlist “Jessica Alba”Alba” “Jessica Freshman Kyle Vermette Sophomore Kyle Vermette “Beyoncé “Beyonce”” Freshman Will Cameron “Forget You” Cee Lo Green “Miss Independent” Kelly Clarkson “Jennifer Lawrence” Lawrence” “Jennifer Junior Elliott Elliott Woyshner Woyshner Junior “Justin Timberlake” “Justin Timberlake” Freshman Emma Freshman McCarthy Emma McCarthy “Somebody That I Used to Know” Gotye feat. Kimbra “Ridin’ Solo” Jason Derulo “Single Ladies” Beyoncé “Ian “Ian Somerhalder” Somerhalder” Sophomore Sophomore Lexi Lexi Korczynski Korczynski “Luke Bryan” “Luke Bryan” Paige Barkume –Compiled by Alexandra HiglFreshman Freshman Paige Barkume and Haley Denzak Photos from abecnewsradio.com,, wikipedia.org and wallsonline.org Photos from abecnewsradio.com,, wikipedia.org and wallsonline.org Sports 6 Feb. 14, 2013 Mentz’s Minute The Carroll News Blue Streaks battle until the finish, but fall short, 71-68 JCU falls at home to rival Wilmington, drops to 13-10 overall Jake Hirschmann Zach Mentz Sports Editor Advertising on NBA jerseys? I’m going to be sick ... Ladies and gentleman, I have some very disturbing and unfortunate news that I must bring to your attention. Before reading the rest of this column, it’s probably best that you make sure you have a puke-bag nearby – you might need it for this one. On the morning of Monday, Feb. 11, the NBA announced its plan to release the league’s newest uniforms – the Golden State Warriors’ sleeved, yellow jerseys. Yes, you read that right; I said sleeved. As in, sleeves on jerseys. Can you picture that? Neither can I, at least I couldn’t at first. The Warriors will debut these alternate, sleeved jerseys at home on Feb. 22 against the San Antonio Spurs. I know, I know, don’t puke yet. Stick with me. The NBA refers to these sleeved jerseys as the “first modern shortsleeve jersey” in all of professional basketball. Adidas, the uniform provider of the NBA, describes the new jerseys as “the first-ever super lightweight stretch woven short with maximum ventilation for player comfort.” While those descriptive words all sound really nice and innovative at first glance, allow me to translate what they really equate to: B.S. The first inclination upon hearing this news is to simply think, “What’s the point of adding sleeves to the jerseys?” Well, allow me to answer that question for you. The NBA isn’t unveiling these jerseys because of their “lightweight stretch” or even because they look cool (because they don’t). Instead, the NBA is releasing these new, sleeved jerseys for one predictable reason: money. It’s not exactly a secret that the NBA wants to eventually sell advertising space on team uniforms, and adding sleeves to jerseys only adds more real estate for the league to sell to potential advertisers. Sam Amico, the NBA columnist of FOXSports.com, wrote recently: “NBA teams don’t want to look like European soccer clubs, but they do want to maximize their advertising revenue. If that means placing ads on uniforms, then that’s exactly what NBA teams will do.” So there you have it. The NBA will likely begin putting advertisements on jerseys starting next season, and it’s only going to expand. Maybe decades from now, the NBA will have players wear full jackets and sweatpants to allow for maximum advertising space. That could really generate some dough. On one hand, this could be seen as a great business move, as selling ad space could generate an estimated $100 million. On the other hand, this is quite literally the definition of “selling out.” Follow @ZachMentz on Twitter or email him at zmentz14@jcu.edu Staff Reporter Another tough home loss left the John Carroll women’s basketball team looking for answers after Wilmington eked out a 71-68 win over JCU on Saturday, Feb. 9. The Blue Streaks were looking to use this as a bounce back game after getting blown out by Baldwin Wallace last week, but the bounces did not go their way, and they came up just short. The first half left nothing to be desired. The Blue and Gold (13-10 overall, 6-10 OAC) came out knowing they needed the win and pulled away to a nine-point lead halfway through the first half. Unfortunately for the Blue Streaks, Wilmington responded with a run of their own and was able to knot it up at halftime with a score of 40-40. JCU came out of the gate and scored seven quick points, giving the team a four-point lead with the momentum. At this point, it appeared that JCU might make a run and really spread the game out, but Wilmington held tough and showed why they are competing for a spot atop the OAC. The Quakers held a 67-64 lead with just under four minutes to go when JCU turned it up defensively. The Blue and Gold put together a solid team effort as they held Wilmington to only four points down the stretch, but the offense could not find the bottom of the net and only matched those four points. The final came out to 71-68, dropping the Blue Streaks to seventh in the OAC with two games to play. Although the team did not pull out the victory, there were contributions across the board from the whole team. Junior forward Photos courtesy of JCU Sports Information Sophomore Beth Switzler (above) dishes the ball while sophomore Meghan Weber (below) gets set in the post. Missy Spahar once again put up a We had Wilmington shaken up, and double-double with 22 points and we left it all out on the court. As a 10 rebounds, while sophomore team, that is all we can ask of one forward Meghan Weber came up another,” Weber said. “Wilmington big off the bench, only scoring is a great team and have been outtwo points, but having seven very rebounding their opponents by a important rebounds in 20 minutes margin of five to eight rebounds. We of game play. were only out-rebounded by two, “Our shot selection and shoot- with 40 total rebounds an improveing percentages have improved ment from the last matchup against each game. We had a solid team them, where we were out-rebounded effort stemming from the bench, 48-34. We are getting better every the coaching staff and the players. game and are playing some of the best basketball now [that] we have all season.” John Carroll will close out the regular season on Saturday, Feb. 16 on the road against Marietta. A road victory over the Pioneers would be a huge boost for this team going into the OAC Tournament, which begins on Monday, Feb. 18. No matter what happens this week, the Blue and Gold are guaranteed a matchup with the Pioneers on Monday at home. Editor’s Note: The Blue Streaks played their second-to-last game of the regular season last night as they hosted the visiting Otterbein Cardinals at the DeCarlo Varsity Center. For final scores, box scores, statistics, game stories and more, please go to. 2012-2013 JCU Blue Streaks season statistics Points: M. Spahar, 16.3 ppg B. Switzler, 12.2 ppg Rebounds: M. Spahar, 9.3 rpg $ B. Switzler, 6.8 rpg Assists: A. Lustig, 5.3 apg $ E. Mog, 5.0 apg 3 Point Percentage*: E. Mog, 35.7 A. Lustig, 31.7 FG Percentage*: B. Switzler, 53 ^ E. Johanason, 50 *Minimum 25 attempts $ First in the OAC ^ Second in the OAC JCU men stumble on the road against the Quakers Hot-shooting Wilmington routs JCU, sends squad to third consecutive loss Dale Armbruster Staff Reporter In late season situations, teams often rely on their veteran players to lead the team down the stretch. On Saturday afternoon, a group of underclassmen carried the weight for the men’s basketball team. Sophomore David Hendrickson scored 15 points off the bench, but it was not enough, as John Carroll fell to the Wilmington Quakers, 84-66, at Fred Raizk Arena. More often than not in head coach Mike Moran’s tenure, his second group has been counted on for fresh legs, defensive stops and a strong transition offense. After a long season in which those underclassmen have played a key role in the rotation, Moran took their influence to a whole new level. On Saturday, Moran started off the game against the Quakers with the “second platoon,” leaving his starters on the bench. The starters came in after nearly three minutes, but the message was sent that the Blue Streaks would do anything to stop their losing slide. Unfortunately for John Carroll, Wilmington had the momentum of Senior Night and Malcolm Heard II on their side. Neither team was able to find their footing early, until a Heard jumper at 16:00 started an 18-2 run over the next four minutes. After trailing 23-4 at that point, the Blue Streaks rallied to only trail by 11 at the half, but the damage was done. Heard erupted for 18 points in the first half. He would finish with 22 points and 10 rebounds. Heard’s performance was reminiscent of his 34-point performance last Feb. 23, when the Quakers upset the Blue Streaks, 79-74, in the Ohio Athletic Conference Semifinals. Many of the current Blue Streaks were not on the roster for that game, but have still felt the aftereffects of the now three-game winning streak in the matchup by the Quakers. The second half saw Moran emptying his bench to give young players time. Freshman Simon Kucharewicz was impressive in the second half, compiling eight points, six rebounds and two blocks in the later minutes. He would finish with nine points, 11 rebounds and three blocks. John Carroll fell to 10-12 overall and 7-9 in the OAC, while Wilming- Photo courtesy of JCU Sports Information Sophomore David Hendrickson (above) and the Blue Streaks fell on the road to Wilmington, 84-66. ton improved to 11-12 and 9-7 in the OAC. It was the third consecutive loss for John Carroll, a team that has now been defeated by double digits or more in seven of their nine conference losses. The Blue Streaks have locked up a home playoff game, which will most likely take place as part of a rare doubleheader on Monday night at the DeCarlo Varsity Center. The team will likely be the fifth or sixth seed and will play immediately following a playoff game involving the women’s basketball team, which has locked up the sixth seed for the OAC Tournament. Editor’s Note: The JCU men’s basketball team played their secondto-last game of the 2012-2013 regular season last night as they traveled to Westerville, Ohio to take on the host Otterbein Cardinals. For final scores, box scores, statistics, game stories and more, please go to www. jcusports.com Sports The Carroll News 7 Feb. 14, 2013 JCU Swimming and Diving teams prepare for OAC Championships Zach Mentz Sports Editor Women’s Swimming and Diving Having had the last two weeks to prepare for the upcoming Ohio Athletic Conference Championships, the John Carroll University women’s swimming and diving team knows one thing: It’s go time. The Blue Streaks (7-7, 4-1 OAC) ended the regular season by winning their last two meets, defeating both Hiram College and Baldwin Wallace University in the process. With a little bit of momentum on their side, the Blue Streaks will be ready to compete at the Championships, which span from today through Saturday, Feb. 16 in Akron, Ohio. The Blue and Gold will be led by senior Julia Adams, the reigning OAC Women’s Swimmer of the Year. Adams won three individual events at the Championships last season en route to helping JCU pick up a third-place finish among six teams. Sophomore Victoria Watson will also be depended upon to pick up points for JCU, as she ended the regular season with a first-place finish in the 100-yard freestyle event against Baldwin Wallace. Sophomore Karyn Adams, the younger Adams sister, also took home a first-place finish against BW by winning the 50 freestyle with a time of 26.40. After finishing in third place at the OAC Championships in each of the last three seasons, it’s safe to say that the Blue Streaks are ready to reach new heights. Competition will begin at 11 a.m. on Thursday, Feb. 14 at the Ocasek Natatorium on the campus of The University of Akron. The start time of 11 a.m. will be the same on both Friday, Feb. 15 and Saturday, Feb. 16 at the same venue. Men’s Swimming and Diving While the women’s team has finished in third place for three consecutive years at the Ohio Athletic Conference Championships, the men’s team has done something similar: They’ve finished in second place each of the past three years. Now, with more than two weeks passing since their last meet, the Blue Streaks (4-10, 1-4 OAC) will have their sights set on picking up that ever-elusive first-place finish. While struggling somewhat during the regular season, there is undoubtedly still a core of talent on the Blue Streaks’ roster that will be depended upon this weekend. The Blue and Gold will be led by senior Drew Edson and junior Nick Holvey, both of whom were big contributors in JCU’s narrow 118-109 loss against Baldwin Wallace to end the regular season. Edson fared well at the OAC Championships last year, finishing second in the 200 Photo courtesty of JCU Sports Information Senior Rachael Mizner (above) and the rest of the Blue Streaks will compete for an OAC Championship this weekend. freestyle event and fifth in the 500 freestyle to help pick up points for the Blue and Gold. On the other hand, Holvey contributed by finishing in third place in the 200 IM event, while picking up a fourth-place finish in the 100 butterfly. Sophomore Nick Bockanic will also need to do his part if the Blue Streaks are to have success this weekend. Bockanic finished in first place in the 100 back event against Baldwin Wallace, finishing with a time of 59.33 The OAC Championships will take place at the Ocasek Natatorium on the campus of The University of Akron. The Championships will span over the course of three days, beginning today and ending on Saturday, Feb. 16. Competition will begin at 11 a.m. on all three days. In the Mid-February Meet, sophomore Gage Marek was the lone Blue Streak to finish third or higher in an individual event. The sophomore earned bronze in the 1,000-meter run, thanks to a time of 2:40.89. The Blue Streaks will compete twice this coming weekend in both the Greater Cleveland Championships on Friday, Feb. 15 and the Kent State Tune-Up on Saturday, Feb. 16. Sophomore Emily Mapes was the star for JCU at the All-Ohio Championships. She emerged victorious from the 5,000-meter run in 18:29.14, a full six seconds ahead of the second-place finisher. The Blue and Gold’s distance medley also snatched a first-place finish at the meet in Westerville. Senior Maureen Creighton, junior Nicki Bohrer, sophomore Haley Turner and freshman Angelica Bucci combined to earn the gold. The Blue Streaks had a quiet day at the Mid-February Meet at Baldwin Wallace. The only individual finisher to place third or higher for JCU was junior Megan Landon, who took third in the 500-meter event. The Blue and Gold will next compete at the Greater Cleveland Championships on Friday, Feb. 15 before competing the following day in the Kent State Tune-Up on Saturday, Feb. 16. JCU Indoor Track and Field teams round up a busy weekend on the road Joe Ginley Assistant Sports Editor Men’s Track and Field The Blue Streaks finished in the middle of the pack in both of the meets the squad competed in over the weekend. The men’s indoor track and field team placed ninth out of 18 schools with 39 points in the Mid-February Meet on Friday, Feb. 8, and finished 10th out of 16 teams at the All-Ohio Championships on Saturday, Feb. 9. Senior Mike Minjock led the Blue and Gold at the All-Ohio Championships, snagging first in the long jump. The former indoor All-American was tops in the event with a 7.01 meter jump. Another JCU senior, Pat Burns, captured third place in the 3,000-meter run, with a time of 8:50.26. In relay events, the Blue Streaks were led by the distance Basketball Women’s Track and Field Photo courtesty of JCU Sports Information Sophomore Haley Turner (above). medley team. Sophomore John Cameron and freshmen Michael Hydzik, Will Cameron and Matt Chojnacki combined to give John Carroll a time of 10:27.33, good for third in the event. The Blue and Gold closed out the weekend with a pair of mid-range finishes. The women’s indoor track and field bagged eighth place out of 18 competitors on Friday in the Mid-February Meet at BW and netted ninth out of 18 squads in the All-Ohio Championships held on Saturday, Feb. 9. Streaks of the Week Basketball Basketball Indoor Track & Field Indoor Track & Field David Hendrickson sophomore Missy Spahar junior Beth Switzler sophomore Emily Mapes sophomore Mike Minjock senior Though the team suffered its third straight loss on Saturday, dropping an 84-66 decision to Wilmington, Hendrickson had a solid game. The sophomore led the Blue Streaks in points, scoring 15 on the day, five of which came on free throws. The forward shot nine of 18 from the field for JCU, but it was not enough, as the Blue and Gold fell to the Quakers, 71-68. Spahar notched 22 points and 15 rebounds on the day, continuing her outstanding season. While averaging 12.2 ppg and 6.8 rebounds per game, the sophomore is quietly having a great season. Recently named to D3hoops.com’s Team of the Week for Jan. 28- Feb. 3, Switzler posted 11 points and six rebounds Saturday. The sophomore captured the women’s indoor track and field’s lone individual top finish at the All-Ohio Championships on Friday. Mapes snagged gold in the 5,000-meter run with a time of 18:29.14, winning by over six seconds. Minjock captured the Blue and Gold’s only individual first-place finish of the weekend. The wily veteran earned the gold in the long jump, beating out the competition with a jump of 7.27 meters in the event. Check The Carroll News Out Online! Do you want to advertise in our newspaper? Please contact us at CarrollNewsAds@gmail.com. Happy Valentine's Day h h l p The Carroll News Follow @TheCarrollNews on Twitter Like “The Carroll News” on Facebook Carroll News The Free double meat with the Any Footlong ™ Sub Valid only at: Cedar & Warrensville 13888 Cedar Rd., Univ Hts Ph. (216) 371-1929 purchase of any Footlong™ sub Valid only at: Cedar & Warrensville 13888 Cedar Rd., Univ Hts Ph. (216) 371-1929 Buy any Footlong ™ or 6” sub at regular price and a 30 oz. drink and get another sub of equal or lesser price FREE Valid only at: Cedar & Warrensville 13888 Cedar Rd., Univ Hts Ph. (216) 371-1929 (Does NOT Include Premium or Supreme Sub) (Does NOT Include Premium or Supreme Sub) Offer expires 2/28/13 Offer expires 2/28/13 Offer expires 2/28/13 (Does NOT Include Premium or Supreme Sub) Informing the Carroll Community Since 1925 Power C 10 Ask me what’s my best side, I The Carroll News The Carroll News presents John Carroll Univers ‘Power Couples’ of 2013 & Chelsea Gerken Ty McTigue Chelsea is a junior who is the vice president of programming for Student Union, a member of Chi Omega sorority and has gone on two immersion trips to Honduras. Ty is a junior who is the senior orientation leader, a tour guide, a member of Sigma Phi Epsilon Fraternity and a marketing intern at General Electric. How did you meet your boyfriend/girlfriend? TM: A rendezvous at City and East. CG: Ty and I both lived on the first floor of Sutowski, freshman year. & Alyssa Br Chuck M How long have you been together? TM: 657,436 minutes CG: Do people still get “asked out?” If so, Ty, want to go out with me? Kidding, a little over one year. What are your plans for Valentine’s Day? CG: Sounds silly, but we love IHOP because it’s open late and serves breakfast all day long. Our schedules are busy so we have a 10 p.m. IHOP date this Valentine’s Day. What’s better than pancakes with your best friend? What love advice do you have for others? TM: If you’re looking for love, stop looking. Because when you’re not looking for it, that’s when you find the best kind. At least that’s what happened with me. Catie is a junior in Kappa Kappa Gamma sorority, on the Relay for Life Leadership Team and an employee at the Student Call Center. Ken is a junior who is the president of Beta Theta Pi fraternity, a tour guide, on the Relay For Life Leadership Team and went on an immersion to New Orleans. How did you meet your boyfriend/girlfriend? KC: We grabbed the tongs for the chicken in the caf at the same time. It was love at first sight. Later that night we went to Homecoming and hit it off. & Catie Kirsch Ken Clar What is your favorite thing about your boyfriend/girlfriend? KC: I love that Catie values her family background so much and that she will sacrifice so much to do great things for other people and have tons of fun in our relationship. CK: My favorite thing about Ken is how he always puts others first; he really doesn’t know how to be selfish. What love advice do you have for others? KC: Guys – One thing I can tell you is that if you can find a woman that loves hanging with your guy friends, you hit a home run. CK: Communication and honesty are key. If you don’t have both, it won’t work out. Always tell each other how you’re feeling; even if you know it might hurt at the time it will make you stronger in the long run. These couples were nom John Carroll Couples 11 I stand back and point at you! Feb. 14, 2013 & Ta y l o r H a r t m a n Kyle Mazurek sity’s 3 & How long have you been together? KM: 15 months. What are your plans for Valentine’s Day? TH: Well, last weekend, we had our Valentine’s Day date at Sushi Rock. We had to schedule last week because Kyle is competing in the OAC Swimming and Diving Championship meet in Akron from Feb. 13 to Feb. 17. However, I’m able to go see him compete, and I’m really excited to cheer him on. Who pays on dates? TH: We alternate on payments, depending who books the date. KM: Whoever plans the date. What love advice do you have for others? TH: Patience. Respect. Time. I’m going to quote one of my idols here: “If you can’t love yourself, how the hell are you going to love somebody else?!” KM: You will only be successful in love if you have a lot of patience and can be honest with yourself and significant other. rown Mulé Taylor is a sophomore psychology and sociology double major , the president of Allies, vice president of Psychology Club and often volunteers with Labre. Kyle is a sophomore on the swim team, a member of Allies and will attend the Jamaican immerison trip this May. Alyssa is a junior Arrupe Scholar, works with the CSSA and has gone on two immersion trips to El Salvador Chuck is a junior resident assistant in Hamlin Hall and a member of the JCU Track and Field and Cross Country teams. What is your ideal date? CM: Yeah, a safari trip would be pretty legendary, drive around lions like they’re traffic cones. AB: A trip to a cool aquarium. We really like animals. What are your plans for Valentine’s Day? CM: Yeah, we’re going to have a friend turn his room into a restaurant. He is going to cook us a three-course dinner. AB: Well, last year we went to Don Tequilas and bought a half chocolate cake from Heinens, went back to his room and ate it off the platter with spoons. I’m assuming something like that again. Compiled by: Spencer German & Ryllie Danylko What helps keep you together? CM: Go Bills! AB: We talk to each other and do fun things. What love advice do you have for others? CM: Yeah, sometimes you gotta slay Bowser to get Peach. AB: Dr. Seuss was right – find somebody who is just as weird as you who can accept your weirdness and you’re set. minated by members of the l community. Kelly is a junior tour guide and the vice president of Students Empowering Women. Chris is a junior who is in Sigma Phi Epsilon fraternity, and went on an immersion trip to Nicaragua What are your plans for Valentine’s Day? CW: Monster Jam is coming to Cleveland. KE: ... and dinner at Bahama Breeze. What is your favorite thing about your boyfriend/girlfriend? CW: Her confidence and outgoing personality. KE: His hair. But seriously ... he is sensitive, has an admirable work ethic and makes me laugh everyday. What was your first date like? CW: Terrifying. KE: He was scared to hold my hand. What’s the best gift your boyfriend/girlfriend has gotten you? CW: A Saint Christopher medal. KE: A monogrammed ring. What love advice do you have for others? CW: Give each other space and communicate your feelings. KE: You need to know how to be happy with yourself before you can be happy with someone else. & Kelly Ek Chris Wank World News 12 Feb. 14, 2013 Around the World 1 1 2 The Associated Press. Information reported as of Tuesday night. 3 2 5 3 4 Rogue cop’s fate unclear Silvia Iorio The Carroll News North Korea conducts third nuclear test The Associated Press Christopher Dorner, who was fired from the LAPD in 2008. Dorner is the suspected of killing three people, including a policeman. AP between the person in the cabin and officers around the home before the blaze began.. Dorner’s anger with the department dated back at least five years, when he was fired for filing a false report accusing his training officer of kicking a mentally ill suspect. The first victims were Quan’s daughter, Monica Quan, 28, a college basketball coach, and her fiance, Keith Lawrence, 27. They were shot multiple times in their car in a parking garage near their Orange County condo. Information as of 12:45 a.m. Wednesday.. The test is a product of North Korea’s military-first, or songun, policy, and shows Kim Jong Un is running the country much as his father did, said Daniel Pinkston of the International Crisis Group think tank..” Record snow hits the Northeast hard Staff Reporter The blizzard that took over the northeast is just about over, aside from the snow keeping residents of some cities indoors. According to CNN, freezing temperatures kept the snow from melting. In Connecticut, 40 inches fell in the city of Hamden. Heavy snowfall and strong winds blasted through northeastern cities. The blizzard has also left thousands without power, and during this past weekend, it contributed even more snow. About 40 inches of snow was dumped, and the blizzard is responsible for killing nine people as well as leaving many without power. Utility companies reported on Sunday that 350,000 people were still without electricity across a nine-state region, according to Reuters. Airports began to re-open on Sunday, as about 5,000 flights were canceled on Friday. Some transit was still suspended as of Sunday morning. Another storm was also expected to occur across the Northern Plains. From Colorado to Minnesota, a foot of snow and high winds were supposed to hit. Also, South Dakota was the worst-hit, with winds of 50 mph establishing white-outs and then reaching to North Dakota, Nebraska, Wyoming and Wisconsin. Over the weekend, Rhode Island, Connecticut and Massachusetts took the hard end of the blizzard. The storm also reached Maine, leaving 31.9 inches of snow in Portland, breaking the 1979 record. In Connecticut, five deaths occurred, and there were two in New York and Boston. These were accidents of carbon monoxide poisoning in cars. In one case, an 11-year-old boy tried to keep warm in the car, but the exhaust of the car was blocked. This has been a source of investigation due to the number of people trying to keep warm in cars and the snow blocking the exhaust pipes, therefore causing carbon monoxide poisoning. Snowmobiles were used for road rescues this past Friday and Saturday. Normalcy in the skies and on the roads returned on Sunday, and dig-outs were finally able to begin. AP Snow made the streets difficult to navigate in Connecticut on Saturday following a record-breaking blizzard. Over 350,000 people are without power, and the below-freezing temperatures are keeping the snow from melting. Through this week, the roads and transpor- being dug out, but everyone was doing the tation are expected to make a recovery. As best they could. Information from CNN was used in this of Sunday, residents said that there really wasn’t anywhere to put the snow that was article. The Carroll News 4 World News Hearings bring many issues for nominees Brennan and Hagel 13 Katelyn’s Candor: Feb. 14, 2013 Foreseeing 2016 Alyssa Giannirakis Staff Reporter Chuck Hagel and John Brennan both dealt with tough senators and heavy questioning during their respective confirmation hearings. Defense Secretary-designate Hagel was questioned repeatedly in his eight-hour hearing on Jan. 31 about the Iraq war, Iran and Israel. According to a number of sources, including current Defense Secretary Leon Panetta, Hagel seemed unprepared when addressing the questions from the Senate Armed Services Committee. Panetta spoke about the hearing on NBC’s “Meet the Press” Sunday, Feb. 30, saying, “What disappointed me was that they talked a lot about past quotes, but what about what a secretary of defense is confronting today? What about the war in Afghanistan? What about the war on terrorism? What about the budget sequester and what impact it’s going to have on readiness? What about Middle East turmoil? What about cyber attacks?” The White House is confident in Hagel and his abilities. So is Senate Majority Leader Harry Reid (D-Nev.). Reid said on “This Week” with George Stephanopoulos that he is confident that Hagel will be confirmed and that he is being unfairly judged. In contrast to Hagel’s performance, CIA director nominee John Brennan was able to answer questions regarding drones and torture clearing and seemingly to the best of his knowledge. According to U.S. News and World Report, Brennan focused on what he would do differently with the agency if he were confirmed as director. 5 Katelyn DeBaun Asst. World News Editor CIA Director nominee John Brennan, pictured above, was questioned about drone strikes and torture clearing by the Senate. Chuck Hagel, the potential Defense Secretary, was questioned on his views of Iran, Israel and the Iraq war. When discussing drone strikes, he made it clear that they are not used to punish terrorists. He said, “We only take such action as a last resort to save lives when it’s determined that no other action can be taken,” according to a report on PBS. Brennan was also able to comment on the controversial 6,000-page intelligence report on torture and counterterrorism techniques. According to CNN, Brennan said he is waiting for the final review of the report before drawing any conclusions. In his opening statement to the committee, Brennan said, “I believe my CIA background and my other professional experience have AP prepared me well for the challenge of leading the world’s premier intelligence agency at this moment in history, which is as dynamic and consequential as any in recent decades, and will continue to be in years ahead.” It is clear that Brennan is confident in his abilities and carried himself confidently during his confirmation hearing. Hagel, on the other hand, did not exude the confidence the Senate was looking for in a new secretary of defense. Information from NBC News, US News and World Report, PBS, and CNN contributed to this report. Pope Benedict XVI to resign from post, first time in 600 years President Obama and First Lady Michele Obama visiting with Pope Benedict XVI in 2009. On Feb. 11, the pope announced that he will be resigning from his post, citing health problems as the cause. The Associated Press and staff reports. The Feb. 28 resignation allows for a fasttrack conclave to elect a new pope, since the traditional nine days of mourning that would follow a pope’s death doesn’t have to be observed. It also gives the 85-year-old Benedict AP great sway over the choice of his successor. Though he will not himself vote, he has handpicked the bulk of the College of Cardinals — the princes of the church who will elect his successor — to guarantee his conservative legacy and ensure an orthodox future for the church.. And by Easter Sunday, the Catholic Church will almost certainly have a new leader, the Vatican’s chief spokesman Rev. Federico Lombardi said — a potent symbol of rebirth in the Church on a day that celebrates the resurrection of Christ. Thoughts on the Pope’s announcement are visible on the campus of John Carroll University. Edward Hahnenberg, a professor in the Dept. of Theology and Religious Studies, said, “One of the most important things about Pope Benedict’s resignation, theologically, is the reminder that the papacy is an office, not an individual. It is a ministry more than it is a man.” In addition, The Rev. William M. Bichl, S.J. said, “On reflection, and on seeing recent pictures of the Pope, he’s made a good decision. He’s old, tired and physically weaker than just a few months ago. I wish him a happy and healthy retirement. One thing that seems universal around the world is the surprise of the Pope’s resignation, as well as who is next in line. I have a confession to make. Despite the fact that the election just occurred a few months ago, and President Obama was re-inaugurated several weeks ago, I am already looking ahead to the 2016 presidential election. I’m not alone in this, though. Political analysts are already contemplating several likely contenders around, including former Secretary of State Hillary Clinton, Vice President Joe Biden, former Florida Gov. Jeb Bush and Sen. Marco Rubio (Fla.), just to name a few. As a left-wing individual, many would expect me to favor either Clinton or Biden. On the contrary, much like Tina Fey said while portraying Sarah Palin on SNL in 2008, I’m “going rogue.” Out of all the possible candidates for 2016, I most favor New Jersey’s Republican governor, Chris Christie. I may not necessarily agree with all of his political ideals, but I do respect what he has accomplished during his term in office. First and foremost, during Hurricane Sandy, he left behind the fear for bipartisanism that has become commonly associated with the GOP and worked with Obama to be as helpful to the citizens of New Jersey as he could, calling the president “supportive and helpful to [the] state,” according to Politico. He is also one of the few political leaders to immediately start working toward gun control legislation after the Sandy Hook shooting in Connecticut. He attacked the NRA for using the deaths of young children as an argument against gun control and started the SAFE task force to lead the way in safer gun sales and the increase of availability to mental health services within the state. However, his desire for more gun control makes him unpopular within his own party, as does his belief that climate change is a real process, and that the Department of Defense shouldn’t interfere with illegal immigration. Another obstacle in the way of a potential 2016 presidential race for Christie could very well be Christie himself. He has long been targeted due to his weight, which raises concerns that he may not be healthy enough to be the next president. He appeared on “The Late Show with David Letterman” last week, and although he ate a donut on the set as a joke, he explained that as governor he has to go through various physicals and is probably “the healthiest fat guy you’ll ever meet.” While I understand that Christie’s weight is sufficient cause for concern, he wouldn’t be the first president with significant health issues. William Howard Taft was so large that he got stuck in the White House bathtub. John F. Kennedy had Addison’s disease, an endocrine disorder, and Franklin Delano Roosevelt had polio. Then there’s William Henry Harrison, who died 32 days into his presidency after getting pneumonia, supposedly when he did not dress properly for his inauguration. Overall, I believe that if Christie is considered healthy by doctors, then his weight should not get in the way of his decision to run for office. If he is seen as a suitable candidate by the American people, that should be enough. It is true that he has not mentioned his plans for 2016, but I believe that he should run. I believe his outspoken personality and tendency to lean middle-right in political beliefs would be a welcome change in today’s age of outrageously right-wing politicians who don’t wish to compromise. Contact Katelyn DeBaun at kdebaun16@jcu.edu 14 Feb. 14, 2013 Business & Finance Seasonal illness fuels earnings for stores Drugstores see a boost to performance due to flu-like symptoms Patrick Burns It’s once again that time of the year where the flu virus is rampant, and many of our immune systems have been sent into battle. However, drugstores could not be happier about what the Centers for Disease Control and Prevention have described as one of the worst flu seasons in a decade. Store names such as CVS, Walgreens and Rite Aid have seen quite healthy financial results in the past quarter amidst all the sickness. Sales of both prescription and over-thecounter drugs were huge drivers of success for the drugstores.Walgreens alone had an increase of 2.3 percent in the past month for flu prescriptions. Other remedies, such as cough medicine, pain relievers and a whole variety of overthe-counter medicines also saw a boost From ogamcom.net in demand. Rite Aid saw sales of these non-pharmacy goods rise by 4.2 percent. Flu season has been kind to drugstores across the country in the form of increased Looking at drugstores on a nationwide scale profits. Prescription and over-the-counter drugs are the biggest moneymakers. is even more noteworthy: For the week Flu shots can see margins of over 50 for drugstores like CVS. ended Jan. 26, sales of over-the-counter The easy shopping experience is not medicines were up 24 percent compared percent, while cough drops and nasal sprays can see over 40 percent. Coupled with the taken for granted, as drugstores account to the year before. This flu season has also given light to panic that has spread with the severity of for $3 billion of the $6.5 billion in annual an interesting phenomena known as “The this flu season, it makes sense as to why cough and cold sales. Drugstore chains have Halo Effect.” When consumers buy their drugstores have performed so well and pleased Wall Street overall. CVS Caremark had earnings per share of $1.14, beating out respective medicines, they also tend to be continue to do so. Another major factor that has aided the analyst consensus of $1.10. drawn to other complementary products. CVS also outperformed on a revenue These include thermometers, vitamins and pharmacies is their convenience. When fresh toothbrushes. Some stores are capital- people are sick they tend to head to the local basis by reporting $31.4 billion versus the izing on this by encouraging their patrons drugstore as opposed to their supermarket, expected $31.13 billion. Despite a marvelto purchase these products. For example, as they are often located closer to peoples’ ous past quarter, it is very likely the EPS and revenues may see a drop in the coming Walgreens has a flu season checklist in homes. Larry Merlo, CEO of CVS, described months. store comprised of a whole array of essenThe flu season will subside, and the tials for staying healthy during this time a customer’s thoughts: “I’m really not thinking about driving the extra few miles, sales of flu and cough-related products are of the year. destined to drop along with it. Until that These kinds of results are not outland- and then have to park far away to get into time, stores such as CVS will welcome the ish, as Todd Hale of Nielsen’s Consumer & the store.” When someone is sick and has to buy a increased performance of their products and Shopper Insights group says “Pharmacies enjoy an uplift during strong flu seasons.” medication, more than likely he or she will its addition to their bottom line. Information from The Wall Street JourPerhaps this can be traced to the remarkable try and make the trip as short as possible. These short trips equate to big sales figures nal was used in this report. profitability of flu-related products. Budget talks move forward for the EUthe. Scandal hits crisis-laden Spain The Associated Press Staff Reporter The Associated Press The Carroll News ‘credit. Both sides had threatened to walk away from the table — again — if they didn’t get what they wanted.. The EU budget includes items meant to generate economic growth in the future. It also funds regulation and administration in such areas as mergers and competition, the review of national budgets to ensure they do not include excessive deficits and banking supervision.. Spain’s leading newspaper, El Pais, €322. Spaniards struggling under spending cuts and tax hikes are outraged.. Barcenas, 55, was the second-in-command of €22 million ($29.7 million) in Swiss bank accounts. Barcenas’ lawyer denied that his client’s vast wealth was the result of corruption, saying he made it through business investments outside his party job over the years. In a brief TV interview outside his Madrid apartment, he insisted the documents were false — in spite of claims from experts that they match his handwriting.. None of Rajoy’s colleagues in Parliament have shown any signs of defecting.. Diversions 15 The Carroll News Sudoku Easy A bit harder Febuary 14, 2013 Genius The first Person to submit all three completed sudoku puzzles wins A free mcdonalds small fry from the carroll newsroom! Good Luck, everyone! NAME THAT TOON! What the toon doesn’t say about the tune: “Maybe I’m a different breed. Maybe I’m not listening. So blame it on my ADD baby ” Be the first to submit the answer and your email address to The Carroll Newsroom, and get your picture in next week’s paper! ANSWER:____________________________________________ CONNECT THE DOTS! Cartoon by Nicholas Sciarappa TIC-TAC-TOE CHALLANGE “Best Pizza in Cleveland Featuring Homemade Sicilian Cooking” Our Hours Mon - Thurs: 11:am - 10 pm Fri - Sat: 11:00am - 11:00 pm 12305 Mayfield Road Cleveland, OH 44106 (216) 421-2159 mamasantas.com Richard-Carla for Hair All JCU Students Haircuts $20 Happy Valentine’ s Day! 2263 Warrensville Center Rd University Heights (216) 371-9585 Editorial 17 The Carroll News Editorial Feb. 14, 2013 Commitment to service , Cartoon by Nicholas Sciarappa NOTABLE QUOTABLE “ “Don’t feel bad if you don’t win. I’ve never won, and I have my own eyelash line. Take that, Bon Iver.” Editorial Petition on a mission — Katy Perry, on introducing the Best New Artist category at the Grammy Awards Recently, a petition began circulating moving to extend the appointment of visiting professors in the English department, Robert “Bo” Smith and Thomas Roche. Students who had positive experiences with the professors started the petition. Smith and Roche began teaching at JCU in the fall of 2011 through the Gerard Manley Hopkins Professorship in British Literature. Typically, visiting professors under this professorship stay for a period ranging from less than a semester to an academic year. Smith and Roche have stayed the longest of any Hopkins professor at JCU to date. Despite the students’ sincere efforts to secure more years of teaching, the English department does not anticipate extending the stay of the professors. Scheduling is cited as a main issue in extending Smith and Roche’s appointment. It is understood that this visiting professorship program cannot be extended. However, since students have had such a positive experience with these professors, hiring them as adjunct faculty should be considered down the road. Furthermore, an extensive evaluation of the current professors should take place to ensure that students have the opportunity to learn from the best possible professors.. “ Recently, John Carroll students have been starting and participating in projects which benefit both the John Carroll and Cleveland communities. One of the programs allows students to contribute their unwanted, gently used clothes to the Clothes Closet, an on-campus store for used clothing. Students have the option of exchanging a donated item for another in the store. Some students have chosen to donate clothing free of exchange, though. The Clothes Closet exchange program enables students to obtain new clothes free of cost. This is very beneficial to students who need new clothes but can’t afford them. It also contributes to campus sustainability by reusing unwanted clothing instead of throwing them away and constantly consuming new products. The Earned Income Tax Credit (EITC) is a refundable tax credit that implements tax reductions and wage supplements to low-and-moderate income families. The EITC Coalition has recruited John Carroll students, alumni, and staff. Members of the John Carroll community will help prepare the taxes of low-income families. Both of these projects exemplify John Carroll’s commitment to community service. The EITC Coalition and The Clothes Closet provide goods and services to those in need. Those who have participated in these projects are commended for their actions. Increased opportunities to participate in service on campus might cause even more students to engage in helping the community. HIT & miss Hit: JCU cross country boys’ “Harlem Shake” video miss: JCU’s tuition increasing Hit/miss: Pope Benedict XVI announced his resignation from the papacy Monday morning; he is the first pontiff to step down since 1415 Hit: President Obama announced in his State of the Union address that 34,000 troops will be withdrawn from Afghanistan within a year miss: A Carnival cruise ship with 4,229 passengers was stranded in the middle of the Gulf of Mexico after a fire destroyed the engines Hit: The military will now extend some family benefits to same-sex partners miss: Chris Brown totaled his car while attempting to dodge paparazzi Hit/miss: Carrie Underwood wore a $31 million necklace to the Grammy Awards miss: Facebook is being sued by a Dutch company over its use of the “like” button miss: Kristen Stewart Hit: New research shows that dogs are able to understand situations from a human perspective miss: A film critic called actress Melissa McCarthy “a female hippo” and “tractor-sized” in a review of her new movie “Identity Thief” Email your hits & misses to jcunews@gmail.com Editor in Chief DAN COONEY dcooney13@jcu.edu Managing Editor Brian Bayer Adviser Editorial Adviser Robert T. Noll Richard Hendrickson, Ph. D Business Manager Gloria Suma Photographer Zak Zippert Campus Editors Ryllie Danylko Spencer German Jackie Mitchell Abigail Rings Arts & Life Editors Alexandra Higl Haley Denzak Mitch Quataert Editorial & Op/Ed Editors Grace Kaucic Nick Wojtasik World News Editors Cartoonist Sam Lane Katelyn DeBaun Nicholas Sciarappa Business & Finance Editor Copy Editors Andrew Martin Sports Editors Zach Mentz Joe Ginley Diversions Editor Nicholas Sciarappa Allison Gall Alyssa Giannirakis Katii Sheffield Abbey Vogel Tracey Willmott Delivery Lexi McNichol Matt Riley Op/Ed 18 Feb. 14, 2013 OURVIEW Spencer German Campus Editor What about the rest of the year? It’s Valentine’s Day. It’s the worst day of the year (well, other than every Monday of the year) but otherwise, the worst day of the year. Now let me explain, because I have a feeling everyone reading this right now probably has that stereotypical thought of “Oh, he’s just bitter because he’s had bad Valentine’s Day experiences and blah blah blah.” Well, in reality, and contrary to popular belief, none of the Valentine’s Days I’ve ever been part of have been bad, and I’d actually say they have been pretty normal. I’ve only ever been in one relationship that ran through a Valentine’s Day, and I’d say that one was pretty normal too. So ask me why on earth is Valentine’s Day the worst day of the year? And I’d respond, Where do you want me to start? Valentine’s Day is probably the single-most fluke of a holiday I have ever lived through. First of all, whether you’re in a relationship or not, Valentine’s Day symbolizes the one day of the year when love is forced. All that happens on Feb. 14 every year is people feel obligated for once to show that they care about someone. If they don’t have someone they rush to find someone on that day that will agree What about the rest of the year? to “be their Valentine.” What a joke. Think about it. If you really love someone, or even just like them or care about them as much as you say you do, then the things you do on Valentine’s Day should be things you are already doing on any given day. In other words, you should show how much that person means to you the other 364 days of the year that aren’t called “Valentine’s Day.” It’s basically like people hear the title “Valentine’s Day” and the first thought is, “What should I buy? What should I get? What should I do?” If you don’t think about that any other day, then what is the point of forcing it now? It shouldn’t be an obligation, but unfortunately that is what it has become. In my opinion, it is more impressive if you get a girl flowers on a Wednesday afternoon in mid-October just because you want to than if you do it for Valentine’s Day. Ask any girl that, and I bet they would agree. Now don’t get me wrong: If you don’t care all the other days, then go ahead and let Feb. 14 be the one day you try, which ironically enough brings me to my next point of why today is the worst. Valentine’s Day is a day that allows bad boyfriends to make up for their mistakes from the past year. So many times I’ve seen or heard a girl complain about how bad her boyfriend treats her all year long, or how rude her boyfriend was to her last week, or how he won’t kiss her in public, and she’s upset. Then, Valentine’s Day rolls around and boom, she’s got flowers falling out of her closet, chocolates that could feed a third world country and PDA everywhere they go. All of a sudden, everything is good again till the next time she gets cheated on or the next time they fight. Enough is enough! If you’re using Valentine’s Day to make up for your mistakes, and that’s the only day you really care, you probably aren’t happy. Now don’t get me wrong, I make mistakes too; but I’m confident that if you asked my girlfriend, Brittany Fleming, if I show her I love her every single day, she would say yes without any hesitation. That’s not to say I’m any better than anyone else, but just that Valentine’s Day is so overdone. I’d rather show someone their worth on a daily basis than on a Hallmark holiday like today. To be honest, I like thinking back to the days when you wrote a Valentine for everyone in your class and put them in their little bag so they could go home and read how much people cared about them. That’s how Valentine’s Day should be, sharing the love with everyone, not just putting on a fake show. All in all, Valentine’s Day has gone from representing love, devotion and connection between you and someone you truly care about, and become more about what can you buy to show that you care about that person? The Beatles said it best … “Can’t buy me love.” I’ll stand by that until the day I die. That being said, do the right thing today, and then repeat it for the next 364 days after that. Happy Valentine’s Day, Brittany! I love you! Contact Spencer German at sgerman13@jcu.edu Wonderword : What does flibbertigibbet mean? “A toothless woman from West Virginia.” Haley Turner, sophomore “A nickname that Allison Pschirer calls her mom. ” Ned Barnes, sophomore “An animal that is both a fish and a frog.” Alex Dirr, sophomore Flibbertigibbet: A silly, flighty or scatterbrained person The Bayer Necessities: Brian Bayer Managing Editor Love is perhaps the most universally explored theme of human existence. Every great king has spoken of it – Jesus (the King of Men), Elvis (the King of Rock ’n’ Roll) and even Larry (King Live). So what more can a humble student say about it? Probably nothing, but I’ve never claimed to be humble, so here are some of my thoughts on the subject. Last week, we heard the Scripture that describes love as “caring, compassionate, blind, etc.” That’s all true, I’m sure, but it’s so much more than that – Love is a badass bat out of hell, Iron Man/Hulk combo that can steal your very being and give you the strength of the Spartan armies or the weakness of Samson without his hair. So yes, I agree with what the Bible The Carroll News calls love, but I also think it’s a teensy bit more. A lot of people fear that we throw the word “love” around too easily. Personally, I think we don’t say it enough. Don’t mistake this for me claiming we should say it without thinking. Absolutely not! But is it that bad of an idea to be vulnerable? I think the world would be a brighter place if more people were willing to open themselves up like that. Many can’t tell the difference between “like a lot” and “love.” Here’s a hint: You don’t love something if it can’t return your affection. For example, I like chocolate a lot. I once ate a five-pound Hershey bar. It was awesome. But it never told me how much it cared about me. On the other hand, I love my family. But eating them wouldn’t make me happy like the Hershey bar did, because they have something else to offer other than confectionary perfection – their love in return (and I don’t imagine Bayer meat tastes very good anyway). After much meditation, fulfillment, heartache and growth, I’ve come up with a barometer of sauciness in what I call the “Spectrum of Lovin’.” I’ve broken it down into three simple levels. Let me first clarify that the number one obstacle you might encounter is thinking that love only applies to that somebody special in your life. Wrong again – love applies to everybody you encounter. So here’s the Spectrum: 1) To have love for. If love were a water park, this would be the kiddie pool. Having love for one another is the most important part of being human (or at least enjoying being human). This is the kind of love you should share with your neighbor. It’s familiar love, and everyone deserves it. We often have this belief that we need to earn each other’s love. I don’t believe this is true. Perhaps we can earn their hatred, but we should at least start with the loving part. 2) To love. This is the next step up. Congratulations, you’ve moved onto the wave pool. If you straight love someone, they are Cooney Meets World: Retreating from the grid Dan Cooney Editor in Chief I. Contact Dan Cooney at dcooney13@jcu.edu Unpacking love probably pretty special to you. Somehow they have broken past that first level and touched your heart in a deeper way. This kind of love should be an eternal fire that mustn’t ever be extinguished. If you tell someone you love them, you should love them forever. I maintain this to be true in my own life – there isn’t a single person I have ever said, “I love you” to that I don’t still hold a special place for in my heart. Sure, this might seem scary – it’s a great way to get hurt. I’m sure a lot of people celebrating “Singles Awareness Day” this week have gotten to this level with a significant other and maybe gotten hurt. Man up (or woman up), and realize that being vulnerable is okay. Closing your heart to love doesn’t protect you or make you brave; it just shields you from the potential of tomorrow. This level of devotion is also the kind of affection that should be shared with your family members. Whether you consider your family to be your parents, grandparents, siblings or friends, make sure you remind them you love them. 3) To be in love with. Hold on a second, Tex. This is the big one – the vertical speed slide of the water park of love. You better be sure, or else you might fall right off. You should have love for almost everyone; you should love your family and those who have been close with you; but if you’re in love, that’s the chocolate mousse of devotion. This should be reserved for one other person who captures your thoughts and your heart. This is the kind of love that you should share with your God and that solitary other, because that’s really the only avenue by which you can fall in love. This level is the “bat out of hell, Iron Man/Hulk combo that can steal your very being and give you the strength of the Spartan armies or the weakness of Samson without his hair” kind of love. And once you find that, I imagine it’s pretty neat. So, how do you love? Contact Brian Bayer at bbayer13@jcu.edu Op/Ed The Carroll News The Op/Ed Top Ten: Romantic Comedies 1. “Sleepless in Seattle” 2. “My Big Fat Greek Wedding” 3. “Love Actually” 4. “Notting Hill” 5. “When Harry Met Sally” 6. “The Princess Bride” 7. “Definitely Maybe” 8. “50 First Dates” 9. “How to Lose a Guy in 10 Days” 10. “40-Year-Old Virgin ” Clara Richter Staff Columnist 19 Feb. 14, 2013 Off the Richter: A broad abroad hasn’t yet. Maybe I just haven’t been here long enough to stop feeling like a little bit of a tourist. Then again, maybe the whole time here I will feel like a tourist. I hope not. I am trying my best to just assimilate. I try to do what the other Irish students do and live how they live, for the most part. I feel most out of place when I make peanut butter and jelly because they don’t eat that here, and they think it’s very strange that I do. I shared mine with one of my roommates. She wasn’t blown away by it. Other than the PB & J, I do what I can to blend in. I’ve started watching rugby. It’s actually a great sport, way better than most that we play in the states. Not to say I don’t like American football, and watching baseball for hours on end does have its own special appeal; but if you consider yourself a man’s man, you should try playing a rugby match. I don’t think that I would want to run into any of the members of Ireland’s team on the street. They’re big. And they’re tough. And they’re scary looking. They are rugby players, but they could also be used as muscle for hire. They don’t wear pads. They’re constantly tackling one another. And, while it’s fairly low impact, I think that any tackle when all you’re wearing is essentially a soccer uniform, without the shin protectors, hits pretty hard. Try it sometime. Let me know how it goes. If you can. Another thing I’ve started doing is calling soccer by its proper name, “football.” I did it a bit before I left the states, but I doubt I’ll come back calling it soccer at all. It just doesn’t make logical sense to not call it football. American football is hardly played with the feet. We should probably come up with another name. Sorry guys. I’m not trying to be a hater, but if you think about it, our way really just doesn’t make much etymological sense. Football is just the tip of the iceberg with words that I’m trying to incorporate into my vocabulary. They call sweaters “jumpers” and cookies “biscuits,” and I got made fun of because I called potatoes “potatoes” instead of the usual “spuds.” They use the word “grand” a lot. I don’t know yet if I want to start using that one. Holden Caulfield finds it phony, and so do I generally. Although, with their accents they make it sound much nicer. And I know that we aren’t supposed to buy into stereotypes and believe that certain things are true about entire populations of people, but what you know about the Irish having foul language is pretty much true across-the-board. But it doesn’t really seem so foul because they’re so casual about it. Whether or not I’ll come home with an Irish brogue remains to be seen; but even if I don’t, at least I know I’ll have a few linguistic souvenirs in the form of slang. Cheers! DUBLIN – I wish I could tell you that in the past two weeks I’ve been on all kinds of grand and glorious adventures, and I’ve met interesting people and fallen in love and pet a baby sheep (I guess that’s called a lamb) and seen amazing sights, but instead I was in bed sick with a cold, which is very exciting. But since I’m back in the real world this weekend, I intend to make the most of it. My friend Maggie and —Compiled by Grace Kaucic and Nick Wojtasik I are joining a couple of other girls and going to the Aran Islands, which are located basically at the mouth of Galway Bay and are supposed to be beautiful and kind of remote and one structure exists to make us happy and of the only places in Ireland where the comfortable. Some may even believe Irish language is completely preserved. the system adheres to quotable values And you can bike around the islands, and wisdom. and you know I like that. My commentary shouldn’t be misI don’t think it has hit me fully understood. Strongly adhering to a set that I’m in another country and that of values is a very good thing. Yet, we I’m going to be here for another three must adhere to the right things. Deterand a half months. The only time I mining the what the right things are is Nick Wojtasik get bothered by the distance is when a subjective process. On an individual Asst. Editorial & Op/Ed Editor basis, many things are inconsequential. I think about the time difference. I’m Everyday, the members of the John But there are things which are important five hours ahead of you guys, and let Carroll community receive Speedbumps me tell you, the future is super rad. and for which we should fight. emails, “offering a chance to slow down, Other than that, though, I still When it comes down to it, our reflect and proceed.” The marked words efforts to persuade people to believe don’t walk about on the average day of religious, philosophical, literary certain things are futile. Choosing to conscious of the fact that I am in a and business figures offer advice and believe an argument contrary to one’s foreign country. I am international. insight on spirituality, vocation and all beliefs is conceding to incorrectness, I am technically a foreigner here. I Contact Clara Richter at components of life. These words can be and people do not like to feel like they keep waiting for it to hit me, but it crichter14@jcu.edu insightful, inspirational and comforting, are wrong. People will believe what and all are meant to help guide us along they want; there is absolutely nothing the paths of our lives. that can be done about this, no matter Though hundreds of Speedbumps how wrong their beliefs seem to be. have been sent, most of them express If a person changes it is only because similar messages, making it appear that they chose to change. Accepting this a satisfying life follows from universal reality can help us to bring about change truths. Through repeated exposure to despite the problems human fallibility these truths, credibly based in the signifiand the ego bring to the table. Are you a Communication major? cance of the composer’s significance, To cause change, the best we can one would hope the advice would take do is present relatable information to hold and make a difference in the readindividuals. The reasoning process must Are you a Boler student? ers’ lives. However, continuing along happen within a person. Just like the the same systemic path, which society Speedbumps try to help guide people to has been following for hundreds of years Want to improve your resume? and along a successful path, the things and from which the common human about which we are passionate can be seldom deviates, puzzlingly contradicts realized by others with the help of our the hopeful goals of spreading important guidance. Through the presentation of wisdom. evidence, a person must be made to realThere is a saying that goes, “You ize that a problem relates to and affects can’t win an argument with an ignorant them. Surely, they must be called out man.” The truth is we are all ignorant: subtly to make them realize they are in ignorant of our own ignorance. No violation of something very important, matter how revelatory any argument or Benefits but they mustn’t feel attacked; engaging motivational saying is, a person cannot the defensive only sets a cause further Practicum credit change another person. back. People who were racist in the 1950s Many believe that what sets humans and 1960s are probably still racist today, apart is our ability to reason. But, what Hands-on experience in the newsroom no matter how convincing their grandseems to dominate that ability are the children’s arguments for acceptance are. emotions which can paralyze our logic. Though we are constantly reminded that The trick is to engage emotions which Learn Adobe Photoshop and InDesign there is more to life than money, we conaid our cause. To fight for something, we tinue to pursue it despite the displeasure must not fight something else. We must that constant quest brings. Innumerable work with something to change it. All of Become a better writer quotes tell us what values to have and to those Speedbumps are pointless if it is pursue our dreams to become who we not realized how they apply specifically are designed to be. How soon after realto an individual and their situation. Submit a letter of intent to Dan Cooney at dcooney13@jcu.edu if interested. izing the importance of those values are T.S. Eliot wrote, “This is the way our minds empty of them? Is anyone’s the world ends / Not with a bang but childhood dream to ruthlessly pursue a whimper.” While our demise might, scholastic perfection for at least 16 years indeed be us being crushed to an inwhile denying themselves sustaining, significant fragment of what we once simple pleasures to chase grandiose, fabwere, it is possible that new beginnings ricated ones? How many times must the The Carroll News reserves the right to edit letters for length and to reject can also come about in this way. Startinsightful wisdom be argued for before ing with a gentle whimper inside the letters if they are libelous or do not conform to standards of good taste. All people change their minds? opposition can bring about a bang of Though I haven’t done the precise letters received become the property of The Carroll News. Anonymous letchange on the outside. math, my estimates say that a large ters will not be published. Letters to the editor must not exceed 500 words number of the Speedbumps tell us to Contact Nick Wojtasik at do many of the things which we refuse and must be submitted to jcunews@gmail.com by 5 p.m. on Sunday. nwojtasik13@jcu.edu to do; we already believe the current Nick’s Knack: Roadblock You need us Join The Carroll News! We are currently looking for an Asst. Business & Finance Editor. Got something to say? CLASSIFIEDS For Rent FOR RENT - Available July 1, 2013. Colony Road. South Euclid. 4/5 bedroom, 2 bath home close to campus. All appliances, including washer/dryer included. Front porch, back deck, no basement. Call/text Jeff at 440.479.2835 or email at BetaMgmtGroup@gmail.com for more details. Two and three bedroom duplexes on Warrensville for rent. Call Curt at 216337-7796 Modern two-family house for rent for next school year (available June 1st) – both two bedroom units available (two or four people). Two blocks from JCU. Modern amenities, air conditioning, free washer/dryer use, snowplowing included. Large rooms- plenty of storage. Professionally Managed!!! Call 216-292-3727. For Rent/Sale for JCU students. Clean 3 bedroom, 1.5 bathrooms, single family home, appliances with washer and dryer, 2 car garage–deck-front porch, 1 mile to JCU, max – 3 tenants, $250 each - $750 plus utilities. Jw15@uakron.edu Duplex for Rent. Spacious & WellMaintained. Each Unit has 3 Bdrms, 1½ Bath. ¼ Mile from JCU. Call JCU Alumni @ 440.336.2437. Help Wanted For Rent 2 / 3 Bedrooms, T.V. Room, Living Room, Kitchen, carpeting, appliances, washer & dryer included. Off street parking, near everything.Available April 1st 2013.$700 per month. Sec/deposit. Call to see. 440-897-7881 - 440-655-2048 New Video Dance Club Opening Valentines Day Weekend: Security Jobs Available NOW HIRING! Club Centrum, located at Coventry and Euclid Hts Blvd (next to Grog Shop). Thurs, Fri and Sat House for rent. Walk to campus. Indi- nights available. Please email your info vidual bedrooms, 2 showers. New ap- availability and contact information pliances and A/C. Clean and updated. ASAP to: MercerEmail@aol.com Call or text 216-832-3269 for complete details. Goodies BISTRO & BAKERY– 5416 Mayfield Road. 8 minute walk to campus (Warrensville Looking for Part-Time help. and Meadowbrook). Very clean well FLEXIBLE HOURS. Drivers, Cashiers, maintained 2 family houses. Each Kitchen Staff, Prepare carry-out orders. suite has 3 bedrooms, living and din- 216-225-3412 – cell ing room, kitchen, 2 baths, central air, (leave a message if no answer) alarm system, extra insulation, and all OPENING SOON appliances including dishwashers. Excellent condition… 440.821.6415 First and second floor units available for rent. Each unit is 3 bedrooms and 1 full bath. Located directly across the street from John Carroll on Warrensville Center Rd. Recently renovated. Bothunits have large living area, spacious rooms, large closets, and garage parking. Stove, refrigerator washer and dryer are included. Rent $1,000 each unit./mnth 440-542-0232. Available June 15. THE CARROLL NEWS SINCE 1925 Looking for a place to advertise? Look no further than The Carroll News.
https://issuu.com/thecarrollnews/docs/2.14.13_the_cn
CC-MAIN-2016-40
refinedweb
18,007
71.44
Downloading Files From The Server To The Local Machine In C#?Jul 24, 2010 In my application I have a requirement where the client/user needs to download video files from the server to their local machine.View 1 Replies In my application I have a requirement where the client/user needs to download video files from the server to their local machine.View 1 Replies I have had a real nightmare with Server.MapPath(). When I call Server.MapPath("~") in my application that is running in ASP.NET Development Server it returns root directory that ends in a back slash like f:projectsapp1, but I call it in published version, installed in IIS, it returns root directory without any back slash like c:inetpubwwwrootapp1. string mainRoot = HttpContext.Current.Server.MapPath("~"); DirectoryInfo di = new DirectoryInfo(mainRoot); //added to solve this problem with Server.MapPath if (!mainRoot.EndsWith(@"")) mainRoot += @""; FileInfo[] files = di.GetFiles("*.aspx"); foreach (FileInfo item in files) { string path = item.FullName.Replace(mainRoot, "~/").Replace(@"", "/"); //do more here } How do I get the smtp server address for the local machine? I want to my email address on a windows form and have the user send me an email and I need to be able to get their smtp server address programatically to do this. I tried this: System.Net.Mail. SmtpClient smtpc = new SmtpClient("127.0.0.1"); smtpc.Send(email); It caused an exception. I have a web service I need to connect to. But when trying to connect to it through visual studios, I get this error. The request failed with HTTP status 405: Method Not Allowed. I have the wsdl files on my location machine. I was told to create the proxies from these. The problem is I'm not quite sure how. This seems to be a little over my head right now. Not the best project to learn WCF or WSE on. Does anyone know how to create the proxies from wsdl files on my local machine. The services themselves are pretty simple, they just have security elements in the headers. UsernameToken. And then some custom fields.View 1 Replies i have been trying to solve this for hours with no luck. i seem to be missing something fundamental. i have a remote FTP server with a file called log.txt on it, i wish to allow web users to download this file to their local drive to a designated folder. i have a function calling this sub i found on the web with the filename to download.when trying to run this code i get this error: " Could not find a part of the path 'C: empFtpDownloadsFolderlog.txt'. " [Code].... if i replace this line: [Code].... i get no error but the file is not in the TempPath. (it shows it to be saved to "C:WindowsTEMPlog.txt" ) i have a feeling its being save on the server instead of my local drive. When I run the application using the Web Developer it works fine. However when I run it using local IIS I get the following error: The resource class for this page was not found. check if the resource file exists and try again. Description: An unhandled exception occurred during the execution of the current web request. review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: The resource class for this page was not found. heck if the resource file exists and try again. Source Error: Line 81: private void PopulateLanguageList() Line 82: { Line 83: DropDownListLanguage.Items[0].Text = (string)HttpContext.GetLocalResourceObject( Line 84: "Default.aspx", SelectLanguage, Thread.CurrentThread.CurrentCulture); Line 85: } Stack Trace: [InvalidOperationException: The resource class for this page was not found. Please check if the resource file exists and try again.] System.Web.Compilation.LocalResXResourceProvider.CreateResourceManager() +4038050 System.Web.Compilation.BaseResXResourceProvider.EnsureResourceManager() +23 System.Web.Compilation.BaseResXResourceProvider.GetObject(String resourceKey, CultureInfo culture) +24 System.Web.Compilation.ResourceExpressionBuilder.GetResourceObject(IResourceProvider resourceProvider, String resourceKey, CultureInfo culture, Type objType, String propName) +32 System.Web.HttpContext.GetLocalResourceObject(String virtualPath, String resourceKey, CultureInfo culture) +56 APPortal.Login.PopulateLanguageList() in c:inetpubwwwrootAPPortalDefault.aspx.cs:83 APPortal.Login.Page_Load(Object sender, EventArgs e) in c:inetpubwwwrootAPPortalDefault.aspx.cs:20 i made a file uploader to folder named (Books) and i saved the name and the bath of the uploaded file to my DataBase but when i wanna download the uploaded file from the server ? how i make it ? by hyperlink ?View 3 Replies? With the project I'm working right now, the team and I don't believe the network/computer policies will allow us to create and save Excel files on a local machine through the Web pages we're building. Well, let me clarify. When we run our web pages on our development machines, when we go to save information to excel through the web page, it uses our local excel executable. However, we want it to use the web server's excel executable. When we run the website, we're running individual local copies because we don't have a web server to test on, so we can't verify if it will use the Web Server's or ours. Does anyone know what it will do, or if it has to be programmatically set a specific way to use excel on the web server, and not on the local machine. Once we get the Web Server to use excel, we'd save the file to a network share that would allow the user to view the file.View 2 Replies I created a HttpHandler for downloading files from the server. It seems it is not handling anything...I put a breakpoint in the ProcessRequest, it never goes there. public class DownloadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { //download stuff and break point } } It never stops there, as mentioned. I also registered it in the web.config. <add verb="*" path="????" type="DownloadHandler" /> I am not sure about the path part of that entry. What do I have to enter there? I am downloading txt files, but the URL does not contain the filename, I somehow have to pass it to the handler. How would I do this? Session maybe? im trying to transfer my database from local machine to server, im using the publish to provider wizard in visual web developer to generate a scrip, im then using the generated script on the serever database. [Code].... I'm new to ASP.NET (only been learning 6 months at college) and have set up a login page with a loginview, login name and login status. The pages work fine on my local machine I can login logout and see the user name etc..But when I upload this to my home testing server the domain name shows up, this should read. I've set the DestinationPageUrl as both a direct link and ~/admin.aspx and /admin.aspxView 17 Replies i developed an asp.net web site and i used ModuleRewriter to rename my pages you can refer to this link [URL] and i want to add many pages programatically at run time for example i have a page named : [URL]styles/defaultstyle/Default.aspx and i want to display this page like this : [URL]Default.aspx so my code was like this : public static void confgrewriter() { try { RewriterRuleCollection rules = RewriterConfiguration.GetConfig().Rules; RewriterRule r = new RewriterRule(); r.LookFor ="~/Dfealut.aspx" ; r.SendTo ="~/styles/defaultstyle/Default.aspx"; rules.Add(r); } catch (Exception ex) { } } and this solution is working very good on iis at my local machine but when i did upload this website on shared host i recive error message: The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. review the following URL and make sure that it is spelled correctly. I am attempting to write an asp.net. In addition, the users of the application are connected Anonymously (Anonymous Authentication) For a church website I'm managing, there is a need to place audio files (sermons) on the website. There will be two categories of audio files; one will be a sample size of the audio file, around 5 minutes in length. The other will be the full-length of the sermon (30-50 +/- minutes). I have decided the best setup would be to place the audio files on the server. I would then store the audio information, as well as the path to the audio file, in a database. I had thought about placing the audio files in the database as a BLOB, but it seemed inefficient. My concern, is with tools like Mozillza plug-in "Download Helper" , it is so easy to simply grab the media files off the server. This would not be a big deal, except we want to sell the full-length audio files. I am running ASP.NET 3.5 on IIS 7. downloading multiple files from the server side through the browser (i.e. Chrome) I've debbuged it the foreach iterates fine but it only downloads the first file. Here's the code snippet: FileInfo fInfo; SQLConnection = new SqlConnection(SQLConnectionString); foreach (CartItem CartProduct in Cart.Instance.Items) { [code]..... i have a .JPG file in my local machine which has to be sent as body of SMTP mail.Path of image D://foldername//imagename.jpg The code I run is in the server mc. I want it to access my local machine's d: folder to get the image file. But it is accessing the server mc's d: folder. How can this be done?View 3 Replies my application raises security issue while saving data from server to local machine.but everything working well locally.View 2 Replies my projects image files hosts on a local server machine which name is A. another server hosts my web projects on IIS which name is B. I want to set my web projects's image file names like image1.ImageURL = "A\foldername\image.png"; but when the projects runs the image file url gets the image url adrress : [URl] I must access the image files which are another server machine on my local network area and I must get the ImageUrl properties from another server machine Clicking the save button on my webform that's on our dev server: Posts back to the same page on my local machine: How does the DevServer even know my computer exists? I haven't hardcoded any URLS in my code. I have html editor on page, ajax 3.5. I can save Editor.Content to xml file without problem, after I publish to server machine, It refused to work for me. my page directive set to ValidateRequest = false and EnableEvenValidate = false and AutoEventWireUp = false, no UpdatePanel used around Editor and update button. on code behind which is button click event. Dim docInfo.Load(Server.MapPath(xmlInfoFilePath)) docInfo As New System.Xml.XmlDocument() Dim ndInfo As System.Xml.XmlNode ndInfo = docInfo.SelectSingleNode("/info/business[@user='" & User.Identity.Name & "']") If ndInfo IsNot Nothing Then ndInfo.Attributes("description").Value = Editor.Content docInfo.Save(Server.MapPath(xmlInfoFilePath)) End If docInfo = Nothing This button click generate an error on server side. I guess the problem Editor.Content have hidden tags, the server refuse to accept, but what is real problem. 1. ASP.Net WEB server. 2. I have PC, on which file to copy to device is located, with Active Sync installed and IE running which has a page in that IE has rendered by server #1. 3. I have a DEVICE connected to desktop #2 via AS. I would like to copy file from a local machine to the device which is connected to this machine. My application is located in a webserver. On one of my pages I display a datetime (from a database) and it is formatted correctly as a UK date time (dd-mm-yyyy) on my local machine. However when I deploy it to a server it reverts to American format (mm-dd-yyyy). Does anyone have any idea of when this might be happening?This might be outside the scope of stackoverflowView 3 Replies I have a web site using Forms Authentication that downloads a PDF file specific to the user from a page. On the development server I have it working fine, on the live server it checks to see if the file exists and fails (correctly) if it doesn't, but does not load the Dialog Box to save/open/cancel if it does exist. Any ideas ? There are no events logged, the code is as follows and by the way I have tried various combos of WriteFile/TransmitFile as per other forum posts - many combos seem to work on development machine(!!) but fail on live... Dim fiPDF As New FileInfo(strReportPath) [code].... Exception message: The remote host closed the connection. The error code is 0x800703E3.?
https://asp.net.bigresource.com/Downloading-files-from-the-server-to-the-local-machine-in-c--rmIVrLUkF.html
CC-MAIN-2022-40
refinedweb
2,161
66.33
I have written this blog to address the FAQ in SDN as discussed Conversion of source XML structure to single string using PI 7.1 and in many other threads. Where there is a need to map complete input xml payload to a field of the target xml. Can this be done using the standard Graphical Mapping? The answer is YES in PI 7.1. Earlier we used to do this using Java Mapping or The specified item was not found. .. Source Structure: Target Structure Assign The Mapping: Right-click on “Source Message Type” and select “Return as XML” in the dropdown menu. This will return XML. To convert that to a string, here simply I am using trim function present in the Text function Category (you can use any text function , so that it treats input xml as string ) Source xml payload: Target xml payload: [original link is broken] [original link is broken] [original link is broken] [original link is broken] [original link is broken] [original link is broken] [original link is broken] Regards Jyothi What is new in your blog ? Thanks Saravana Here In my blog I am trying to explain How to use the copyXML feature to convert complete input xml payload to String. As I have seen in so many threads asking for how to convert input xml payload to String using standard graphical mapping.But most of the suggestions were to use Java Mapping or XSLT Mapping.But using these mappings will take bit more time to develop. This blog is to assist who want to achieve the same functionality using Standard Graphical Mapping. Hope I answered your question. Please let me know if you have further query. I will also do a search of SDN blogs as to whether this info is already documented and explain in my blog what i am doing differently. I would add the info you have blogged as a Wiki, saying i am applying copyxml feature to acheieve this specific functionality. And tell others that they could add the ways they have exploited this feature. Hope this clarifies why i made the comment. Thanks Saravana And The reference points to the same link(blog) which you have mentioned. Thanks, MNVSN. This is really helpful, If you are wroking on CLOB Data Type for an JDBC scenario. I worked for similar kind of scenario, where we used Java Mapping to get complete XML at source to target field which is of type CLOB(in SQL Server). Thanks for the information. Regards Praveen K Cheers Rajesh Keep blogging 🙂 Regards, Abid Good way to achieve one of requirements in a easier way.. Do u see any workaround possible other than a simple adapter module if we receive target file here as an input file for any case & needs to read that? Regards, Anoop How do you remove the namespace inside the string after the return xml? I have a scenario file to string. I followed the blog but the string has the namespace inside. Also is there a way of making the string back to a tab delimited file? Can I change this in the adapter
https://blogs.sap.com/2010/06/17/convert-the-input-xml-to-string-in-pi-71-using-standard-graphical-mapping/
CC-MAIN-2017-34
refinedweb
524
71.44
On Fri, Jul 18, 2014 at 11:57 AM, Andy Lutomirski <luto@amacapital.net> wrote:> On Fri, Jul 18, 2014 at 11:51 AM, Aditya Kali <adityakali@google.com> wrote:>> On Fri, Jul 18, 2014 at 9:51 AM, Andy Lutomirski <luto@amacapital.net> wrote:>>> On Jul 17, 2014 1:56 PM, "Aditya Kali" <adityakali@google.com> wrote:>>>>>>>> On Thu, Jul 17, 2014 at 12:57 PM, Andy Lutomirski <luto@amacapital.net> wrote:>>>> > What happens if someone moves a task in a cgroup namespace outside of>>>> > the namespace root cgroup?>>>> >>>>>>>>> Attempt to move a task outside of cgroupns root will fail with EPERM.>>>> This is true irrespective of the privileges of the process attempting>>>> this. Once cgroupns is created, the task will be confined to the>>>> cgroup hierarchy under its cgroupns root until it dies.>>>>>> Can a task in a non-init userns create a cgroupns? If not, that's>>> unusual. If so, is it problematic if they can prevent themselves from>>> being moved?>>>>>>> Currently, only a task with CAP_SYS_ADMIN in the init-userns can>> create cgroupns. It is stricter than for other namespaces, yes.>> I'm slightly hesitant to have unshare(CLONE_NEWUSER |> CLONE_NEWCGROUPNS | ...) start having weird side effects that are> visible outside the namespace, especially when those side effects> don't happen (because the call fails entirely) if> unshare(CLONE_NEWUSER) happens first. I don't see a real problem with> it, but it's weird.>I expect this to be only in the initial version of the patch. We canmake this consistent with other namespaces once we figure out howcgroupns can be safely enabled for non-init-userns.>>>>> I hate to say it, but it might be worth requiring explicit permission>>> from the cgroup manager for this. For example, there could be a new>>> cgroup attribute may_unshare, and any attempt to unshare the cgroup ns>>> will fail with -EPERM unless the caller is in a may_share=1 cgroup.>>> may_unshare in a parent cgroup would not give child cgroups the>>> ability to unshare.>>>>>>> What you suggest can be done. The current patch-set punts the problem>> of permission checking by only allowing unshare from a>> capable(CAP_SYS_ADMIN) process. This can be implemented as a follow-up>> improvement to cgroupns feature if we want to open it to non-init>> userns.>>>> Being said that, I would argue that even if we don't have this>> explicit permission and relax the check to non-init userns, it should>> be 'OK' to let ns_capable(current_user_ns(), CAP_SYS_ADMIN) tasks to>> unshare cgroupns (basically, if you can "create" a cgroup hierarchy,>> you should probably be allowed to unshare() it).>> But non-init-userns tasks can't create cgroup hierarchies, unless I> misunderstand the current code. And, if they can, I bet I can find> three or four serious security issues in an hour or two. :)>Task running in non-init userns can create cgroup hierarchies if youchown/chgrp their cgroup root to the task user:# while running as 'root' (uid=0)$ cd $CGROUP_MOUNT$ mkdir -p batchjobs/c_job_id1/# transfer ownership to the user (in this case 'nobody' (uid=99)).$ chown nobody batchjobs/c_job_id1/$ chgrp nobody batchjobs/c_job_id1/$ ls -ld batchjobs/c_job_id1/drwxr-xr-x 2 nobody nobody 0 2014-07-21 12:47 batchjobs/c_job_id1/# enter container cgroup$ echo 0 > batchjobs/c_job_id1/cgroup.procs# unshare both userns and cgroupns$ unshare -u -c# setup uid_map and gid_map and export user '99' in the userns# $ cat /proc/<pid>/uid_map# 0 0 1# 99 99 1# $ cat /proc/<pid>/gid_map# 0 0 1# 99 99 1# switch to user 'nobody'$ su nobody$ iduid=99(nobody) gid=99(nobody) groups=99(nobody)# Now user nobody running under non-init userns can create sub-cgroups# under "batchjobs/c_job_id1/".# PWD=$CGROUP_MOUNT/batchjobs/c_job_id1$ mkdir sub_cgroup1$ ls -ld sub_cgroup1/drwxr-xr-x 2 nobody nobody 0 2014-07-21 13:11 sub_cgroup1/$ echo 0 > sub_cgroup1/cgroup.procs$ cat /proc/self/cgroup0:cpuset,cpu,cpuacct,memory,devices,freezer,hugetlb:/sub_cgroup1$ ls -l sub_cgroup1/total 0-r--r--r-- 1 nobody nobody 0 2014-07-21 13:11 cgroup.controllers-r--r--r-- 1 nobody nobody 0 2014-07-21 13:11 cgroup.populated-rw-r--r-- 1 nobody nobody 0 2014-07-21 13:12 cgroup.procs-rw-r--r-- 1 nobody nobody 0 2014-07-21 13:11 cgroup.subtree_controlThis is a powerful feature as it allows non-root tasks to runcontainer-management tools and provision their resources properly. Butthis makes implementing your suggestion of having 'cgroup.may_unshare'file tricky as the cgroup owner (task) will be able to set it andstill unshare cgroupns. Instead, may be we could just check if thetask has appropriate (write?) permissions on the cgroup directorybefore allowing nested cgroupns creation.>> By unsharing>> cgroupns, the tasks can only confine themselves further under its>> cgroupns-root. As long as it cannot escape that hierarchy, it should>> be fine.>> But they can also *lock* their hierarchy.>But locking the tasks inside the hierarchy is really what cgroupnsfeature is trying to provide. I understand that this is a change inexpectation, but with unified hierarchy, there are alreadyrestrictions on where tasks can be moved (only to leaf cgroups). Withcgroup namespaces, this becomes: "only to leaf cgroups within task'scgroupns".>> In my experience, there is seldom a need to move tasks out of their>> cgroup. At most, we create a sub-cgroup and move the task there (which>> is allowed in their cgroupns). Even for a cgroup manager, I can't>> think of a case where it will be useful to move a task from one cgroup>> hierarchy to another. Such move seems overly complicated (even without>> cgroup namespaces). The cgroup manager can just modify the settings of>> the task's cgroup as needed or simply kill & restart the task in a new>> container.>>>> I do this all the time. Maybe my new systemd overlords will make me> stop doing it, at which point my current production setup will blow> up.>[shudder]I am surprised that this even works correctly.Either way, may be checking cgroup directory permissions will work foryou? i.e., if you "chown" a cgroup directory to the user, it should beOK if the user's task unshares cgroupns under that cgroup and youdon't care about moving tasks from under that cgroup. Withoutownership of the cgroup directory, creation of cgroupns will bedisallowed. What do you think?> --Andy-- Aditya
http://lkml.org/lkml/2014/7/21/676
CC-MAIN-2017-51
refinedweb
1,057
64.1
I have been playing with R to parse html. After reading about visualising “fantasy football” search traffic with RGoogleTrends at The Log Cabin blog I decided to write a few functions to do similar things with Wikipedia search statistics. This is what I have managed to come up with: wikiStat <- function (query, lang = 'en', monback = 12, since = Sys.Date() ) { #load packages require(mondate) require(XML) namespace <- c("a" = "") wikidata <- data.frame() #iterate "monback" number of months back for (i in 1:monback) { #get number of days in a given month and create a vector curdate <- strptime(mondate(since) - (i - 1), "%Y-%m-%d") previous <- strptime(mondate(since) - (i - 2), "%Y-%m-%d") noofdays <- round(as.numeric(previous - curdate), 0) days <- seq(from = 1, to = noofdays, by = 1) #build url if(curdate$mon + 1 < 10) { dateurl <- paste(as.character(curdate$year + 1900), "0", as.character(curdate$mon + 1), sep = "") } else { dateurl <- paste(as.character(curdate$year + 1900), as.character(curdate$mon + 1), sep = "") } url <- paste("", lang, '/', dateurl, '/', query, sep = "") #get and parse a wikipedia statistics webpage wikitree <- xmlTreeParse(url, useInternalNodes=T) #find nodes specyfying traffic traffic <- xpathSApply(wikitree,"//a:li[@class='sent bar']/a:p", xmlValue, namespaces = namespace) #edit obtained strings (sometimes its in the format # of e.g. 7.5k meaning 7500) traffic <- gsub("\\.", "", traffic) traffic <- gsub("k", "00", traffic) traffic <- as.numeric(traffic) #it seems that there is some kind of a bug in wikipedia statistics # and the results are shifted by one day in month - this is a fix if(length(traffic) > noofdays) { traffic <- traffic[2:length(traffic)] } #create daily dates relating to traffic vector #and create a dataframe days <- seq(from = 1, to = length(traffic), by = 1) yearmon <- rep(paste(curdate$year + 1900, curdate$mon + 1, sep = "-"), length(traffic)) date <- as.Date(paste(yearmon, days, sep = "-"), "%Y-%m-%d") wikidata <- rbind(wikidata, data.frame(date, traffic)) } #remove rows that are missing (due to the bug?) wikidata <- wikidata[!is.na(wikidata$date),] #return dataframe return(wikidata) } wikiPlotStat <- function(wikitraffic, title = "Wikipedia statistics") { require(ggplot2) #create a plot wikiplot <- ggplot() + geom_bar(aes(x = date, y = traffic, fill = traffic), stat = "identity", data = wikitraffic) + opts(title = title) #...with no legend and a theme that fits colours of my blog 😉 wikiplot <- wikiplot + theme_bw() + opts(legend.position = "none") return(wikiplot) } With these two functions you can take a look at search traffic for any article you wish. For instance, we can take a look at the search statistics for “Financial crisis”. The wikiStat() function returns dataframe with the necessary data: #look 40 months back from now critraffic <- wikiStat("Financial_crisis", monback = 40) To plot the data easily we can use the second function: criplot <- wikiPlotStat(critraffic, "Wikipedia search traffic for 'Financial crisis'") criplot And this is the result: You can clearly see the outbreak of the crisis in the second half of 2008, when Lehman Brothers collapsed. Since then people seem to be still willing to learn about the crisis. Do you have any...
https://www.r-bloggers.com/visualising-wikipedia-search-statistics-with-r/
CC-MAIN-2019-51
refinedweb
490
52.7
Recommendation Bar requires and increase timeline opengraph tag requires Why they haven't fixed it yet? That bar is exactly what controls the "Read" action to become published. Or anybody has other idea how you can override this? I recieve a mistake of "Outdoors Graph object has got the wrong type for that given property" however i attempted both with article and namespace:article. The Debugger is ideal. no alerts or errors. I usually attempted while using beta js call as pointed out here Difficulty posting Actions to Timeline Will we just watch for October 29th when its formally out? There's/would be a bug using the debugger associated with timeline and open graph. Make sure to search through facebook bugs here:
http://codeblow.com/questions/timeline-posting-from-wordpress/
CC-MAIN-2019-09
refinedweb
123
66.54
Debugging neural networks 02–04–2019 Debugging neural networks initially seemed like an impossible challenge to me. We had an error that kept popping up and at first I put it down to floating point errors, or library errors or just a random number that got out of hand. Thanks to a couple of my supervisors and colleagues, I stuck at the debugging and with their help, we managed to find out what was going wrong. I figured I’d write a little about this as it might help to dispel a few myths about machine learning and also provide some programming help for folks The error So this is the error we kept on getting: sys:1: RuntimeWarning: Traceback of forward call that caused the error: File "train.py", line 326, in train(args, device) File "train.py", line 227, in train output = model(target, tpoints, w_mask, sigma) File "/home/oni/.local/lib/python3.6/site-packages/torch/nn/modules/module.py", line 489, in __call__ result = self.forward(*input, **kwargs) File "/home/oni/Projects/PhD/scratch/shaper_final/net.py", line 69, in forward rot[1], rot[2], points.shape[0], sigma).reshape((1,128,128))) File "/home/oni/Projects/PhD/scratch/shaper_final/splat_torch.py", line 190, in render num_points = num_points, sigma = sigma) File "/home/oni/Projects/PhD/scratch/shaper_final/splat_torch.py", line 221, in splat torch.exp(-((ex - xs)**2 + (ey-ys)**2)/(2*sigma**2)), dim=0)Traceback (most recent call last): File "train.py", line 326, in train(args, device) File "train.py", line 230, in train loss.backward() File "/home/oni/.local/lib/python3.6/site-packages/torch/tensor.py", line 102, in backward torch.autograd.backward(self, gradient, retain_graph, create_graph) File "/home/oni/.local/lib/python3.6/site-packages/torch/autograd/__init__.py", line 90, in backward allow_unreachable=True) # allow_unreachable flag RuntimeError: Function 'ExpBackward' returned nan values in its 0th output. Folks often warn about sqrt and exp functions. I mean they can explode creating really large or small numbers that might overflow or result in a divide by zero. Indeed, we are getting a warning about nan here so it’s not a bad bet. We can try using a clamp like torch.clamp to make sure the values don’t exceed some set values: model = torch.clamp(torch.sum(\ torch.exp(-((ex - xs)**2 + (ey-ys)**2)/(2*sigma**2)), dim=0),\ min = 0.0, max = 1.0) Determinism A big topic this, determinism. It may surprise folks but it’s perfectly possible to run a machine learning system deterministically. It sounds obvious when you say it out loud, but it most certainly can be done. Same data in, same losses out. If we can get our network to run in this way, we are making progress. In pytorch, we need to set a couple of parameters: torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False Since we are using Python and Numpy as well, we need to set the same random seeds: np.random.seed(0) random.seed(0) Also, any shuffling of the datasets and batches needs to be turned off too! pytorch I use PyTorch these days. I’ve used Tensorflow in the past before now and both seem pretty good. Pytorch has a few key features that help with debugging. To get the error above, we can use the autograd anomaly detection code. with autograd.detect_anomaly(): inp = torch.rand(10, 10, requires_grad=True) out = run_fn(inp) out.backward() Pytorch has one large advantage over Tensorflow when it comes to debugging — it creates it’s graph on-the-fly. It’s more dynamic. This means we can use our favourite debugging tool, the python debugger pdb. Python’s with statement is a fun little bit of syntactic sugar. I took a look at the autograd detect anomaly class and decided I could probably write a version of it that called pdb when it failed. It looks a little like this: import colorama import torch import pdb import traceback from colorama import Fore, Back, Style from torch import autogradcolorama.init()class GuruMeditation (autograd.detect_anomaly): def __init__(self): super(GuruMeditation, self).__init__() def __enter__(self): super(GuruMeditation, self).__enter__() return self def __exit__(self, type, value, trace): super(GuruMeditation, self).__exit__() if isinstance(value, RuntimeError): traceback.print_tb(trace) halt(str(value))def halt(msg): print (Fore.RED + "┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓") print (Fore.RED + "┃ Software Failure. Press left mouse button to continue ┃") print (Fore.RED + "┃ Guru Meditation 00000004, 0000AAC0 ┃") print (Fore.RED + "┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛") print(Style.RESET_ALL) print (msg) pdb.set_trace() I had a little fun with the error message because why not! Makes a dull job a little more interesting. So when I add this to the loss.backward() call in my code, I’ll get the pdb firing up when a runtime error occurs. From here I can interrogate everything from the python commandline. With this in place I can test the tensors in memory, even if they are on the GPU and find out where the problem is. The pytorch anomaly detection uses the function torch.isnan which checks a tensor for the NaN or Inf result, setting a 1 when it finds either. You can then wrap this in a torch.sum and if any number greater than 0 appears, you know you’ve found a problem: torch.sum(torch.isnan(x)) Did we find the bug? Yep! Turns out it’s all to do with culling points that are outside our viewing frustum. It was indeed, the classic divide by zero. We can put code in place to make sure that never happens again. So thanks to PyTorch’s dynamic nature, it’s isnan function, determinism and python’s PDB we can get right down to where the bugs are. It took me far too long to get here, going down a few blind alleys, but in the end, good engineering will get you there.
https://benjamin-computer.medium.com/debugging-neural-networks-6fa65742efd
CC-MAIN-2021-10
refinedweb
984
60.31
Specialized socket using the TCP protocol. More... #include <TcpSocket.hpp> Specialized socket using the TCP protocol. TCP is a connected protocol, which means that a TCP socket can only communicate with the host it is connected to. It can't send or receive anything if it is not connected. The TCP protocol is reliable but adds a slight overhead. It ensures that your data will always be received in order and without errors (no data corrupted, lost or duplicated). When a socket is connected to a remote host, you can retrieve informations about this host with the getRemoteAddress and getRemotePort functions. You can also get the local port to which the socket is bound (which is automatically chosen when the socket is connected), with the getLocalPort function. Sending and receiving data can use either the low-level or the high-level functions. The low-level functions process a raw sequence of bytes, and cannot ensure that one call to Send will exactly match one call to Receive at the other end of the socket. The high-level interface uses packets (see sf::Packet), which are easier to use and provide more safety regarding the data that is exchanged. You can look at the sf::Packet class to get more details about how they work. The socket is automatically disconnected when it is destroyed, but if you want to explicitly close the connection while the socket instance is still alive, you can call disconnect. Usage example: Definition at line 46 of file TcpSocket. Close the socket gracefully. This function can only be accessed by derived classes. Connect the socket to a remote peer. In blocking mode, this function may take a while, especially if the remote peer is not reachable. The last parameter allows you to stop trying to connect after a given timeout. If the socket was previously connected, it is first disconnected.. Get the port to which the socket is bound locally. If the socket is not connected, this function returns 0. Get the address of the connected peer. It the socket is not connected, this function returns sf::IpAddress::None. Get the port of the connected peer to which the socket is connected. If the socket is not connected, this function returns 0. Tell whether the socket is in blocking or non-blocking mode. Send raw data to the remote peer. To be able to handle partial sends over non-blocking sockets, use the send(const void*, std::size_t, std::size_t&) overload instead. This function will fail if the socket is not connected. Send a formatted packet of data to the remote peer. In non-blocking mode, if this function returns sf::Socket::Partial, you must retry sending the same unmodified packet before sending anything else in order to guarantee the packet arrives at the remote peer uncorrupted. This function will fail if the socket is not connected..
https://www.sfml-dev.org/documentation/2.3/classsf_1_1TcpSocket.php
CC-MAIN-2018-43
refinedweb
480
57.27
17 November 2009 16:40 [Source: ICIS news] (Adds Bayer's latest share price in final paragraph) By Will Beacham LONDON (ICIS news)--International Petroleum Investment Company (IPIC) is in talks with five major petrochemical players in the ?xml:namespace> Khadem Al Qubaisi said technology from the new company would be used to develop petrochemical projects in “It’s a big deal. We’re looking to buy a very big petrochemical company in He added: “We are reviewing five opportunities. We’ve signed confidentiality agreements with most of these companies but they are well known petrochemical companies. They are global companies.” Al Qubaisi said technology from the new acquisition would be used to help develop production at the Chemaweyaat chemical city in the new Mina Khalifa Industrial Zone located in “We want to select the right player with the right technology. We want to bring this company to The first phase of the city includes a 1.45m tonne/year ethylene cracker, and is projected to begin production in 2014. Technology from the new acquisition would help develop further phases of Chemaweyaat, he added. Al Qubaisi said the next stages of construction could involve the production of aromatics and phenol. “Phase 2 and 3 depends on the market and what happens to our economy here and worldwide.” There have been market rumours for several months suggesting that IPIC was looking for a European acquisition and had been in talks with Bayer MaterialScience. In This year it acquired 100% of A Bayer spokesman said: "We generally do not comment on market rumours." Shares in the company were up 1.90% at €53.19 on Europe's Xetra exchange at 17:14 local
http://www.icis.com/Articles/2009/11/17/9264778/ipic-names-bayer-materialscience-in-list-of-possible-acquisitions.html
CC-MAIN-2014-10
refinedweb
281
54.42
Last modified: 2011-06-08 Overview This is the first in a two part series on how to set up the Visual Studio (VS) template – that is included in the DBTestUnit download. The second will show how to run tests. If you already have an existing solution/project and want to start using DBTestUnit – a section is included at the end to cover this scenario. Screencast The following short screencast can be used with the notes below to help set up and configure. (Screencast was created in Aug 2010) Steps 1. Download the latest version of the DBTestUnit 2. Extract files to where you want to place your database testing solution/project. In the example below it has been extracted to C:\Projects\ : DBTemplate default directory structure 3. Rename dirs and files with your database name. As you can see in the image above by default ‘DBTemplate’ is used as a prefix for many dirs and files. These should be replaced with the name of the database to be tested. For this I am going to use the MS sample database AdventureWorks as an example. Therefore change: C:\Projects\DBTemplate\ to C:\Projects\AdventureWorks\ Rather than renaming these manually, a bat file – C:\Project\DBTemplate\tools\DBTemplateSetUp.bat – is provided that can do this. The first section of this file is shown below. SET dirRoot=C:\Projects\ SET dirParent=%dirRoot%DBTemplate\ SET dbProjectName=AdventureWorks Before running the bat file – copy it to another directory eg C:\Projects\ and set appropriate values for ‘dirRoot’ and ‘dbProjectName’. After renaming the directory structure should be similar to the following: 4. Change the VS solution file Open – C:\Project\AdventureWorks\src\AdventureWorks.sln Replace ‘DBTemplate’ with ‘AdventureWorks’ 5. Change the the db test project file Open – C:\Projects\AdventureWorks\src\AdventureWorksDatabaseTest\ AdventureWorks.DatabaseTest.csproj Replace ‘DBTemplate’ with ‘AdventureWorks’ 6. Start VS Open the solution. The structure should look similar to the following: A number of sample unit tests and other files are including the in solution. These will all have the text ‘DBTemplate’ in their namespaces. Therefore, do a solution wide ‘find and replace’ changing ‘DBTemplate’ to ‘AdventureWorks’ 7. Set up the config file to connect to the database to test If you open up any of the sample tests provided you will see that they all have a variable – dbInstance – which by default has the value ‘AdventureWorks’. This can be seen at the bottom of the sample code provided below:"; This is used to provide connection settings to the database to be tested and should be set in the following app config file: ..\src\AdventureWorksDatabaseTest\bin\Debug\ AdventureWorks.DatabaseTest.dll.config Open this config file. Go to the connectionStrings section. The following should be included by default. <connectionStrings> <!--MS SQL dbInstances--> <add name="AdventureWorks" connectionString="Data Source=serverName;Initial Catalog=AdventureWorks;Integrated Security=True;Application Name=AdventureWorksUnitTesting" providerName="System.Data.SqlClient"/> The ‘name=”AdventureWorks”‘ should correlate with the value set in the variable ‘dbInstance’ as show in the test code above. The connectionString properties need to be changed appropriately eg Data Source=serverName Once the config file has been updated – that’s it all set up – ready to start database testing. What do I do if I have an existing project? If you an existing project and just want to start using the DBTestUnit.dll for testing then it is a bit easier to set up. Download the latest version of the DBTestUnit as per step 1. In your existing test project reference the latest version of DBTestUnit.dll. You will also need to reference the MS enterprise libraries provided in the download. Then amend your existing config file appropriately so that tests can connect to the database. Round up This blog shown how to set up DBTestUnit – the second will look at running tests.
https://dbtestunit.wordpress.com/2009/11/17/initial-set-up-and-configuration-of-dbtestunit/
CC-MAIN-2017-39
refinedweb
632
57.16
// // This code is part of GrapeCity Documents for PDF samples. // Copyright (c) GrapeCity, Inc. All rights reserved. // using System; using System.IO; using System.Drawing; using GrapeCity.Documents.Pdf; using GrapeCity.Documents.Text; namespace GcPdfWeb.Samples { // This sample demonstrates all editing features of GcPdfViewer with support API // provided by the server running GcPdf. Note that unlike the viewer in most other // samples, in this sample the File Open button is available so you can load any PDF // into the viewer and see what its editing features can do with it. //All { public void CreatePDF(Stream stream) { var doc = new GcPdfDocument(); var page = doc.NewPage(); Common.Util.AddNote("This sample provides access to all editing tools available in the GcPdfViewer when it is connected " + "to a server running GcPdf via viewer.supportApi property. " + "Use the File Open button (first in the top toolbar) to load any PDF into the viewer " + "(note that the maximum file size is limited, an error will occur if the limit is exceeded). " + "Use the first of the two buttons at the bottom of the left vertical toolbar to access the annotation editor " + "that allows to add, edit or remove annotations. " + "Use the second of the two buttons to access the AcroForm editor that allows to add, edit or remove form fields. " + "Note that clicking the active editor button toggles the visibility of the properties panel without exiting the edit mode.", page); // Save the PDF:.AllPanels, viewerTools: new string[] { "open", "save", "$navigation", "$split", "text-selection", "pan", "$zoom", "$fullscreen", "download", "print", "rotate", "view-mode", "hide-annotations", "doc-properties", "about" }); } } }
https://www.grapecity.com/documents-api-pdf/demos/view-source-cs/viewereditall
CC-MAIN-2020-45
refinedweb
261
57.77
0 Just wondering here what is a efficent way to communicate between a Windows Form project and a console application. So far im using Visual Studio 2012 and the System.IO.Pipes namespace,to send bytes between the application. In the windows form(as client) Dim pipes As NamedPipeClientStream pipes = New NamedPipeClientStream("A Digital Whirlwind Pipe") Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click pipes.Connect("5000") Try If pipes.IsConnected = True Then TextBox1.Text = "Client connected." End If Catch ex As Exception MsgBox(ex.Message, MsgBoxStyle.Critical, "A Digital Whirlwind - GUI") End Try pipes.WriteByte(1.0) thats connecting to the console application and sending a byte to trigger commands in the console application.
https://www.daniweb.com/programming/software-development/threads/446839/communicate-between-windows-form-and-console-application
CC-MAIN-2018-09
refinedweb
119
52.66
Type: Posts; User: Sabensohn70 Hi guys, I can't seem to use setprecision, right, setw, or fixed on my outFILE lines. nothing happens. I need to get all the decimals to line up and the numbers are on the right side. this is my... but now i dont know how to display the file like this.. bash-2.04$ a.out Please enter the month for this report: February Please enter the year for this report: 2005 Please enter the total... oops nevermind i forgot a ; on line 15. Hi guys, I have to write a monthly charge program where you it asks for the user to enter the month year and income, and the program will calculate it product sales tax with the equation S=T/1.06.... okay well maybe the programming world is not for me then im just a student trying to pass the class that my teacher did not teach because i asked 5/25 students in the class and the teacher did not... ..dude i am reading my textbook and it doesnt say anything about making bar charts with the for loop. if you are not going to try to help please do not answer at all okay? believe it or not there are... you weren't helping period. im reading starting out with c++ by tony gaddis in the "for statement" section and i dont see anything. Please do not reply to my thread anymore if you are not going to... im thinking for ( store1 = 0; store1 / 100; ++store1 ) ? this doesnt work the other one wasnt as descriptive... #include<iomanip> using namespace std; int main() { int store1, store2, store3, store4, store5; so far this is what i got.. #include<iomanip> using namespace std; int main() { int store1, store2, store3, store4, store5; can you please just help me out? I've never learned this material before. Im suppose to make a bar chart where store1=1000, store2= 1200, store3=1800, store4= 800, store5 =1900. and each asterisk... yeah so how would i make it so the users input each represent 100 in the chart? Hi guys, how do i make a bar chart with the for loop where each asterisk represents 100 after the user inputs the numbers? inputs store1=1000 store2=1200 store3=1800 store4=800 store5=1900 ... how would i use the for loop for this? Can somebody help me with making a bar chart in C++ ? I have to make a bar chart where each * represents 100. It should display like this after the user has inputted the cin for store sales. ... what i mean is how do i combine it to my code? while ( store1 % 100 != 0 && store1 < 0 || store1 > 4000 ) i tried that well i'ts just a simple program assignment and my teacher has already given us a set of inputs. Could you give me an example of using the modulus operator for the multiple of 100? how would the modulus operator work? isn't the function for the operator to show the remainder of a division problem I am suppose to write a code to validate that the users input is between 0-4000 and are multiples of 100. How do i write a code to ensure that the cin is multiples of 100? So far i have cin >>... can you show me how to use break and continue in my code please?? also (distance-1/500) because for one of the inputs it is weight 5.0, distance 10 and the desired out put is 2.20. oh thanks, can you help me with the program termination? because right now if the weight is out of range and the distance is out of range. it will only say "We only ship packages between 10-3000... Hi guys I am suppose to write a program that asks for the weight of the package and the distance it is to be shipped and then displays the charges. I pretty much got every down except i dont know... that is my code so far. my question is what am i suppose to do for the "when calculating the rate, drop fractions of miles and add one for each whole or partial segment of 500 miles". EDIT: Oh,... anybody? i would i write this in a code for my program?
http://forums.codeguru.com/search.php?s=776e50202e703193b01db3b378380630&searchid=6102985
CC-MAIN-2015-06
refinedweb
720
81.93
csLockedHeightData Struct Reference Locked height data. More... #include <imesh/terrain2.h> Detailed Description Locked height data. This class holds an information needed to fill/interpret height data. The elements are object-space heights (that is, they are _not_ affected by cell.GetSize ().z). Two-dimensional height array is linearized, so additional math is needed to get access to desired height values: Instead of data[y][x], use data[y * pitch + x] Definition at line 44 of file terrain2.h. Member Data Documentation height data array Definition at line 47 of file terrain2.h. array pitch Definition at line 50 of file terrain2.h. The documentation for this struct was generated from the following file: - imesh/terrain2.h Generated for Crystal Space 1.4.1 by doxygen 1.7.1
http://www.crystalspace3d.org/docs/online/api-1.4.1/structcsLockedHeightData.html
CC-MAIN-2016-30
refinedweb
129
51.75
Relay actuator sketch - auto off function I would like to control simple 12v 433 mhz remote control using relay. The thing is that relay needs to close only for half a second and then open again (just enough to send pulse out). It would be possible to create a scene in vera but due to very short response time I think it would be better to do this on node itself. There is similar functionality on Fibaro wall module (auto-off function). Not sure how to modify code - add delay and reverse previous state? void loop() { // Alway process incoming messages whenever possible gw.process(); } void incomingMessage(const MyMessage &message) { // We only expect one type of message from controller. But we better check anyway. if (message.type==V_LIGHT) { // Change relay state digitalWrite(message.sensor-1+RELAY_1, message.getBool()?RELAY_ON:RELAY_OFF); // Store state in eeprom gw.saveState(message.sensor, message.getBool()); // Write some debug info Serial.print("Incoming change for sensor:"); Serial.print(message.sensor); Serial.print(", New status: "); Serial.println(message.getBool()); } } - BulldogLowell Contest Winner last edited by BulldogLowell you want to do it like this... but I don't know how many relays you have or which is your first: initialize/define these variables: #define PULSE_TIME 500UL // half a second boolean goPulse; unsigned long pulseStartTime; and your loop() and relayPulse() functions like this: void incomingMessage(const MyMessage &message) { // We only expect one type of message from controller. But we better check anyway. if (message.type==V_LIGHT) { // Change relay state //digitalWrite(message.sensor-1+RELAY_1, message.getBool()?RELAY_ON:RELAY_OFF); goPulse = true; pulseStartTime = millis(); // Store state in eeprom gw.saveState(message.sensor, message.getBool()); // Write some debug info Serial.print("Incoming change for sensor:"); Serial.print(message.sensor); Serial.print(", New status: "); Serial.println(message.getBool()); } relayPulse(); } void relayPulse() { if (goPulse) { if (millis() - pulseStartTime < PULSE_TIME) { digitalWrite(yourRelay, HIGH);// didn't know your pin } else { digitalWrite(yourRelay, LOW); // didn't know your pin goPulse = false; } } } @BulldogLowell thanks, initially I want to use 2 relays. switched separately, yes? 1 arduino with 2 relays attached (each relay on different pin). - BulldogLowell Contest Winner last edited by BulldogLowell try like this... I can compile but not test. Note: relay Pins in array will need to be edited, of course... #include <MySensor.h> #include <SPI.h> //#define RELAY_ON 1 // GPIO value to write to turn on attached relay //#define RELAY_OFF 0 // GPIO value to write to turn off attached relay #define PULSE_TIME 500UL byte relayPin[] = {4,5}; unsigned long relayStartTime[2]; boolean pulseRelay[] = {false, false}; MySensor gw; void setup() { gw.begin(incomingMessage, AUTO, true); // Initialize library and add callback for incoming messages gw.sendSketchInfo("MyRelay", "1.0"); // Send the sketch version information to the gateway and Controller for (byte sensor = 0; sensor < 2; sensor++) // Fetch relay status { gw.present(sensor, S_LIGHT); // Register all sensors to gw (they will be created as child devices) pinMode(relayPin[sensor], OUTPUT); // Then set relay pins in output mode //digitalWrite(relayPin[sensor], gw.loadState(sensor) ? RELAY_ON : RELAY_OFF); // You probably dont want to use EEPROM store here since you are only pulsing } } // void loop() { gw.process(); updateRelays(); } void incomingMessage(const MyMessage &message) { if (message.type==V_LIGHT) { //digitalWrite(message.sensor, message.getBool() ? RELAY_ON : RELAY_OFF); // Change relay state pulseRelay[message.sensor] = true; relayStartTime[message.sensor] = millis(); //gw.saveState(message.sensor, message.getBool()); // Store state in eeprom // Again, not needed here, I believe Serial.print("Incoming change for sensor:"); // Write some debug info Serial.print(message.sensor); Serial.print(", New status: "); Serial.println(message.getBool()); } } // void updateRelays() { for (byte sensor = 0; sensor < 2; sensor++) { if (pulseRelay[sensor] == true) { if (millis() - relayStartTime[sensor] <= PULSE_TIME) { digitalWrite(relayPin[sensor], HIGH); } else { digitalWrite(relayPin[sensor], LOW); pulseRelay[sensor] = false; } } } } @BulldogLowell thanks again. great, let me know if it works for you @BulldogLowell I tested it today and it works as expected. On the hardware side do you think it would make more sense to use transistor instead of relay (since I am dealing only with 12 volts)? I would consider what I'm switching (the load) as much as the voltage and the way they are being powered. " ...simple 12v 433 mhz remote control..." what kind of remote is this? @BulldogLowell it is remote control fob similar to this one. It uses 12 volt battery (27A). @niccodemi I am curious why you chose arduino -> relay -> 433 transmitter for your project and not simpler arduino -> 433 transmitter. I ask because I have one of these key fob RF cloners lying around and have not put it to use yet. I was considering using it to trigger scenes via a 433 receiver on a yet-to-be-built node. @Dwalt initially I tried with Vera and Rfxtrx433 but only later I learned there are many different coding systems on 433 Mhz and many (including Lightning4) are not supported in Rfxtrx plugin. I wanted to try with arduino + 433 transmitter but about same time I found out about mysensors and abandoned 433+arduino altogether. That said I've still got couple 433 mhz controlled switches and I want to integrate them to Vera-Mysensors environment. Until now I thought that the only option is to use relay. I would be interested to try other solutions. @niccodemi I have several of these 433 switches and use a nano (w/mains power) with the 433 transmitter from the store to control them thru MySensors/Vera. The drawback is that these cheap outlets do not give feedback (with MySensors or RFXtrx) but Vera tracks their state by last command. The four I have on my setup work very reliably and have not failed a trigger command during the past two months of operation. The 433Mhz transmitter seems to have better distance within my house than the NRF24 and is very reliable, at least thru my limited experience. My 433 transmitter node is within line of sight of my gateway and only 3m distant. The 433 outlets are scattered throughout my house, on different floors and through multiple walls. I use them to control floor lamps and a fan. I sniffed the RF code from the included remote using the 433 receiver and then put the codes within the sketch on the nano controlling the 433transmitter. I used this blog for details on the sniffing process. I got the set of four outlets for about $18 shipped during a sale so it worked out to $4.50 each. The original sketch was posted here. It is crude (my first arduino sketch) but it worked and continued to work for the past 9 months. I sniffed the codes and then hard coded them into the sketch rather than use one of the RF libraries which I couldn't figure out. I recently updated it for it to work under MyS 1.5 but did not refine it. It is still ugly: #include <MySensor.h> #include <SPI.h> #include <EEPROM.h> #include <NewRemoteReceiver.h> #include <NewRemoteTransmitter.h> #include <MyTransportNRF24.h> #include <MyHwATMega328.h> #define TRANSMITTER_PIN 3 #define RECEIVER_INTERRUPT 1 #define RF433_CHILD_ID 0 #define NUMBER_OF_OUTLETS 4 #define DELAYSHORT 160 #define DELAYLONG 500 #define SEND_DATA 3 MySensor gw; static void ookPulse(int on, int off) { digitalWrite(SEND_DATA, HIGH); delayMicroseconds(on); digitalWrite(SEND_DATA, LOW); delayMicroseconds(off); } static void pt2262Send(uint16_t signature, uint8_t command) { byte i, k; // send 16 times for(k=0;k<16;k++) { // send signature first for(i=0;i<16;i++) { if((signature>>(15-i)) & 0x1) { ookPulse(DELAYLONG, DELAYSHORT); } else { ookPulse(DELAYSHORT, DELAYLONG); } } for(i=0;i<8;i++) { if((command>>(7-i)) & 0x1) { ookPulse(DELAYLONG, DELAYSHORT); } else { ookPulse(DELAYSHORT, DELAYLONG); } } // end with a '0' ookPulse(DELAYSHORT, DELAYLONG); // short delay gw.wait(5); } } void setup() { Serial.begin(115200); gw.begin(incomingMessage, AUTO, true); gw.sendSketchInfo("RF433", "1.1"); for (int sensor=1; sensor<=NUMBER_OF_OUTLETS; sensor++){ gw.present(sensor, S_LIGHT); } } void loop() { gw.process(); } void incomingMessage(const MyMessage &message) { if (message.type==V_LIGHT) { int incomingLightState = message.getBool(); int incomingOutlet = message.sensor; /* Serial.print("Outlet #: "); Serial.println(message.sensor); Serial.print("Command: "); Serial.println(message.getBool()); */ if (incomingOutlet==1) { if (incomingLightState==1) { // Turn on socket 1 // Serial.println("\nTurn on Socket 1"); pt2262Send(0b0101000101010101, 0b00110011); gw.wait(100); } if (incomingLightState==0) { // Turn off socket 1 // Serial.println("\nTurn off Socket 1"); pt2262Send(0b0101000101010101, 0b00111100); gw.wait(100); } } if (incomingOutlet==2) { if (incomingLightState==1) { // Turn on socket 2 // Serial.println("\nTurn on Socket 2"); pt2262Send(0b0101000101010101, 0b11000011); gw.wait(100); } if (incomingLightState==0) { // Turn off socket 2 // Serial.println("\nTurn off Socket 2"); pt2262Send(0b0101000101010101, 0b11001100); gw.wait(100); } } if (incomingOutlet==3) { if (incomingLightState==1) { // Turn on socket 3 // Serial.println("\nTurn on Socket 3"); pt2262Send(0b0101000101010111, 0b00000011); gw.wait(100); } if (incomingLightState==0) { // Turn off socket 3 // Serial.println("\nTurn off Socket 3"); pt2262Send(0b0101000101010111, 0b00001100); gw.wait(100); } } if (incomingOutlet==4) { if (incomingLightState==1) { // Turn on socket 4 // Serial.println("\nTurn on Socket 4"); pt2262Send(0b0101000101011101, 0b00000011); gw.wait(100); } if (incomingLightState==0) { // Turn off socket 4 // Serial.println("\nTurn off Socket 4"); pt2262Send(0b0101000101011101, 0b00001100); gw.wait(100); } } } gw.wait(100); } @Dwalt oh wow.. thanks so much.. i was waiting for you to get back to me but never saw this post.. and i just happened to stumble on it when i was looking to see if you had been back on the forum or not. I'm good with the hardware side of things and can shell script and do windows scripting. but still have not learned this coding yet. i have all the hardware for the 433 stuff. i even got the RF stuff to work (on my RPI2) and sniffed all my codes i could just never get it to work with my arduino stuff. likely the code, so i'm excited to give your code a go. Thanks!
https://forum.mysensors.org/topic/682/relay-actuator-sketch-auto-off-function/17
CC-MAIN-2022-05
refinedweb
1,613
50.43
pid does not have the SA_RESTART flag set. STANDARDS The wait() and waitpid() functions are defined by POSIX; wait3() and wait4() are not specified by POSIX. The WCOREDUMP() macro and the abil- ity to restart a pending wait() call are extensions to the POSIX inter- face. LEGACY SYNOPSIS #include <sys/types.h> #include <sys/wait.h> The include file <sys/types.h> is necessary. SEE ALSO sigaction(2), exit(3), compat(5) HISTORY A wait() function call appeared in Version 6 AT&T UNIX. 4th Berkeley Distribution April 19, 1994 4th Berkeley Distribution Mac OS X 10.9.1 - Generated Mon Jan 6 18:40:10 CST 2014
http://www.manpagez.com/man/2/wait/
CC-MAIN-2015-11
refinedweb
108
78.85
I was working on an application earlier today when I ran into a serious problem. I needed an info page with a scrollable TextBlock, because I had to add a lot of text. Obviously I started with something like that: <ScrollViewer> <TextBlock /> </ScrollViewer> But when I added my text, the result was like this: My TextBlock did not display the entire text. The ScrollViewer though was working fine. I could scroll further, where the text was supposed to be. The reason is quite simple actually. There is a 2048 pixel limitation for UI controls. For a TextBlock the way to work around is splitting the text into smaller TextBlocks and stacking them in a StackPanel. Alex Yakhnin created a control that does this automatically. You can find it here. In order to use that control, there are a few steps needed: - Add Alex Yakhnin’s Phone.Controls project (Phone.Controls.csproj) to your solution. - Add the Phone.Controls project to the References in your project. - Build the Phone.Controls project. - In MainPage.xaml of your project add this to the header: xmlns:my="clr-namespace:Phone.Controls;assembly=Phone.Controls" - Now you can add a ScrollableTextBlock control to your page that just works: Make sure to check out Alex Yakhnin’s Blog for more information. To be continued… Source: {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/textblock-eating-text-windows
CC-MAIN-2017-04
refinedweb
231
68.87
Difference between revisions of "Hello World" Latest revision as of 15:34, 30 May 2012 This "Hello World!" tutorial will cover the absolute minimum steps required to create a plug-in and get feedback inside the application. Contents Preparation Build Environment Setup You need to do three things to be ready to start coding a plug-in. - Include headers. The lxsdk header directory needs to be on the compiler search path. - Build common lib. The common code library archive needs to be built using your compiler and environment. You will link your plug-in to this library to get base implementations for the shared classes and objects. - Empty .cpp file ready to compile and link. You should be able to get started with this using the provided IDE projects for VC and XCode. Decide on Your Server Type A plug-in can't do anything unless it provides one of the proscribed server types for nexus to access. Is this a command, an item type, a tool? Perhaps the plug-in will have multiple servers that all work together. This is something for you to decide. For the purpose of this tutorial we'll be making an image saver, which is one of the simplest types. Writing Code Headers The first part of your plug-in source file will include the required headers. There are two types of headers you will typically want to use: - lx_<system>.hpp -- the user header for any given nexus system will have an L-X-underscore prefix and be of the hpp type. Check the documentation to see which interfaces are defined as part of a given system. - lxu_<name>.hpp -- utility headers have an L-X-U-underscore prefix, and contain helper classes of various kinds. In this case we want the io system and image system headers. I/O gives us the definitions for savers and loaders, and Image defines the interfaces for image objects. Since we're going to say hello to the world we also need the log system. #include <lx_io.hpp> #include <lx_image.hpp> #include <lx_log.hpp> The Server Class The heart of any plug-in is a C++ class that you write to implement a server interface. The interface is the set of standard methods that nexus uses to integrate your server into the application. This is done by inheriting from multiple implementation classes. In this case we're going to inherit from the Saver implementation: class CHelloWorldSaver : public CLxImpl_Saver { public: ... }; The Saver super-class defines two methods: sav_Verify() and sav_Save(). The sav prefix is unique to the Saver implementation class, and allows multiple implementations with the same or similar methods to be inherited by the same server. We're going to implement the Save() method, adding this line to our class definition above: LxResult sav_Save (ILxUnknownID source, const char *filename, ILxUnknownID monitor) LXx_OVERRIDE; The override keyword is optional but very useful. It declares to the compiler that you intend for your method to be derived from an identical method in a super-class. That means that if the method in the implementation class changes the compiler will throw an error. If you don't use the override keyword (or if your compiler doesn't support it -- it's not standard) then you get no error, but your method will never be called. Server Methods To flesh out the save method we'll declare a code body with the same arguments as above. LxResult CHelloWorldSaver::sav_Save ( ILxUnknownID source, const char *filename, ILxUnknownID monitor) { ... return LXe_OK; } The source is the object to be saved, in this case an image. This is an ILxUnknownID pointer type -- a general handle to a COM object -- and can be queried for any number of Image Object interfaces. The filename is the full path of the file to be written in platform-specific format. The monitor is another object used for tracking the progress of the save and is discussed later. The first thing we want to do is query the image object for an Image Interface that will allow us to read the size for the "hello world" message. This is done simply by declaring a localized C++ image user class and initializing it to the source object. CLxUser_Image image (source); CLxUser_ classes are wrappers that allow COM objects to be accessed through common C++ syntax, with C++-friendly APIs. Once initialized with a COM object, they can be used like any other C++ object. In our case we're going to read the size of the image. unsigned w, h; image.Size (&w, &h); Instead of writing an image file as would be expected for a plug-in of this type we're going to generate test output just to alert the world that we exist. It's possible to do this in more complex ways but we'll stick with the easiest, using the log service. CLxUser_LogService log_S; Services are the inverse of servers -- they are interfaces exported by nexus to plug-in, allowing plug-in to access and manipulate the internal state of the nexus system. In this case the state of the log system. Unlike other user classes, they don't need to be initialized. Instead they are automatically initialized as soon as they are declared. The simplest form of debug output just writes to the debug log or, inside the VC debugger, the output window. This is the same as debug output from nexus internal systems and respects the debug level specified on the command line. log_S.DebugOut (LXi_DBLOG_NORMAL, "Hello world: image %s is %d x %d\n", filename, w, h); Server Tags Server objects also support a tags interface. Server Tags are string/string pairs that define the attributes of servers. In the case of savers this is the type of object that's saved, the file extension of the format, and the user name. These can be added easily by defining a descInfo array in the server class: static LXtTagInfoDesc descInfo[]; And declaring the contents of the array statically in the module. The array is terminated with a null name: LXtTagInfoDesc CHelloWorldSaver::descInfo[] = { { LXsSAV_OUTCLASS, LXa_IMAGE }, { LXsSAV_DOSTYPE, "HEL" }, { LXsSRV_USERNAME, "Hello World" }, { 0 } }; Initialization Plug-ins need to declare the servers they export, and the interfaces those servers support. This is done with the initialize() function which is called from the common lib code as the plug-in is loaded. This is largely boilerplate, but with the classes and interfaces varying depending on the plug-in. The first interface defined is also the type of the server. Note that the name of the server is an internal name string, so it should start with lowercase and cannot contain spaces. void initialize () { CLxGenericPolymorph *srv; srv = new CLxPolymorph<CHelloWorldSaver>; srv->AddInterface (new CLxIfc_Saver <CHelloWorldSaver>); srv->AddInterface (new CLxIfc_StaticDesc<CHelloWorldSaver>); lx::AddServer ("helloWorld", srv); } Results Final Code The code above is the absolutely minimal -- and minimalistic -- plug-in code that's required. There are a number of common enhancements that make things easier to manage as your project grows larger. - Persistent service objects. There is a small but non-zero overhead associated with looking up a global service. It's better when possible to move service objects to be class members so they can persist and be reused. - Class initialize method. Rather than placing the initialization of a server into the global initialize() function, it's better to create a static method on the class itself and call that from the global function. That way the interface initialization is embodied in the class that it implements. - Namespaces. Namespaces are a good way to organize code, and allow reuse of common code without a lot of text substitution. - In-line function bodies. When possible, writing the function declaration once reduces the chance of typos or other errors in repeated declarations. Here is the final code, putting together the required elements and adding the optional enhancements. #include <lx_io.hpp> #include <lx_image.hpp> #include <lx_log.hpp> namespace HelloWorld { class CSaver : public CLxImpl_Saver { public: static LXtTagInfoDesc descInfo[]; CLxUser_LogService log_S; static void initialize () { CLxGenericPolymorph *srv; srv = new CLxPolymorph<CSaver>; srv->AddInterface (new CLxIfc_Saver <CSaver>); srv->AddInterface (new CLxIfc_StaticDesc<CSaver>); lx::AddServer ("helloWorld", srv); } LxResult sav_Save ( ILxUnknownID source, const char *filename, ILxUnknownID monitor) LXx_OVERRIDE { CLxUser_Image image (source); unsigned w, h; image.Size (&w, &h); log_S.DebugOut (LXi_DBLOG_NORMAL, "Hello world: image %s is %d x %d\n", filename, w, h); return LXe_OK; } }; LXtTagInfoDesc CSaver::descInfo[] = { { LXsSAV_OUTCLASS, LXa_IMAGE }, { LXsSAV_DOSTYPE, "HEL" }, { LXsSRV_USERNAME, "Hello World" }, { 0 } }; }; // end namespace void initialize () { HelloWorld::CSaver::initialize (); } Testing To test your new plug-in you should first go to System > Add plug-in and select the *.lx file created by the linker. You may or may not have to restart -- depends on the plug-in type. For savers you should be OK. Render, click Save Image. In the format choices pick "Hello World" and OK. Your plug-in should load and you should see its output in the debug log. Note that in release builds all debug output is normally suppressed. You have to add "-debug:normal" to the command line in order to see your debug print. NOTE: In the release 601 the output doesn't appear in the debugger. Instead it goes to stdout or the dblog you specify on the command line. That will be fixed for SP1. See Writing to the Event Log for how to use the event log viewport.
https://modosdk.foundry.com/index.php?title=Hello_World&diff=prev&oldid=8204
CC-MAIN-2020-40
refinedweb
1,560
55.13
VS C# 2010 how to downgrade project from 4.0 to 3.5 framework? - Wednesday, January 26, 2011 4:27 PM Hi! When I used CS C# 2010 option to change the target framework (Project -> Properities -> App -> Target Framework) I got some errors which I can't handle. - Warning 1 The primary reference "Microsoft.CSharp", which is a framework assembly, could not be resolved in the currently targeted framework. ".NETFramework,Version=v3.5,Profile=Client". To resolve this problem, either remove the reference "Microsoft.CSharp" or retarget your application to a framework version which contains "Microsoft.CSharp". - Warning 2 The referenced component 'Microsoft.CSharp' could not be found. Project can't be started, there is nothing really I can do with it - hopefully I have a backup. I really have to downgrade my project to target framework 3.5 because client computers are not allowed to use .NET 4.0. Is there a way to do that? OR how can I fix this problem to run my project with 3.5 framework? Moreover, my empty projects can't be downgraded also - the same warrnings, and the project is not starting. Thank you in advance! All Replies - Wednesday, January 26, 2011 4:59 PM Hi Friend, Are you using any method or class from the "Microsoft.CSharp" Assembly? Actually, there will be some references added automatically when you have specific targetted version. when you downgrade the target framework version, the assembly referance will be removed and the namespace will be used in the "using" block of the code files created in the project. if you are not using those files, you can manually remove those referances by removing the using code block of that specific namespace. It would work fine. -- Thanks Ajith R - Proposed As Answer by Raul PerezMicrosoft Employee Friday, January 28, 2011 12:50 AM - Marked As Answer by Paul ZhouModerator Wednesday, February 02, 2011 7:33 AM - - Wednesday, January 26, 2011 5:51 PMModerator Microsoft.CSharp is a new assembly for v4. You can remove this reference if you are targeting previous versions. Michael Taylor - 1/26/2011 - Proposed As Answer by Shabi Bloch Sunday, March 06, 2011 1:51 AM -
http://social.msdn.microsoft.com/Forums/en-US/csharpide/thread/897cb6d0-5d19-4692-9669-905e154b107f
CC-MAIN-2013-20
refinedweb
363
66.84
Mandatory Access Control (MAC) Framework is one of the less known FreeBSD features. Let’s take a look on how to use it. Discretionary Access Control is the most popular access control model. It’s used by the standard UNIX tools like chmod and chown or file access control lists. This model is very simple and, as the name suggests, depends on permissions granted by the owner of particular resource (file, etc…). If you need to enforce some specific rules DAC isn’t enough. There is where Mandatory Access Control comes into play. It allows you to create a set of policies that enforce certain rules, overwriting DAC permissions when required. The implementation of MAC model in FreeBSD is the MAC Framework. Primary work was done as part of TrustedBSD project. You can use it with well known models like MLS and Biba or create your very own policy. The framework exposes about 250 operations that can be hooked to allow very flexible and strict policy creations. There can be multiple policies connected to any of the entry points. Let’s create very simple (and primitive) policy that limits the socket operations based on group membership. We’ll hook mpo_socket_check_create operation and decide whether to allow or deny the operation based on credentials of process calling socket(2) syscall. One group will have socket operations denied completely, the second one will be allowed only to access local sockets ( AF_UNIX). static struct mac_policy_ops nonet_ops = { .mpo_socket_check_create = nonet_socket_check_create, }; MAC_POLICY_SET(&nonet_ops, mac_nonet, "MAC/NONET", MPC_LOADTIME_FLAG_UNLOADOK, NULL); Now we want to check if the calling process if a member of one of our groups and decide whether to allow the call or deny it. if (nonet_gid >= 0) { for (int i = 0; i < cred->cr_ngroups; i++) { if (nonet_gid == cred->cr_groups[i]) { return (1); // DENY } } } nonet_gid can be embedded in the module code or can be set via sysctl(3). The full code can be found here.
https://mysteriouscode.io/blog/simple-mac-policy-in-freebsd/
CC-MAIN-2020-29
refinedweb
320
64.3
Hi Kim, The zookeeper api does not provide an api to get the znode that was added or deleted. You will have to compare the last set of children and new set of children to see which one was added or deleted. Thanks mahadev On 2/16/10 5:47 AM, "neptune" <opennept...@gmail.com> wrote: > Hi all, I'm kimhj. > > I have a question. I registered a Watcher on a parent znode("/foo"). > I create child znode("/foo/bar1") using a zookeeper console. > Test program received Children changed event. But there is no API getting > added znode. > ZooKeeper.getChildren() method returns all children in a parent node. > > public class ZkTest implements Watcher { > ZooKeeper zk; > public void test() { > zk = new ZooKeeper("127.0.0.1:2181", 10 * 1000, this); > zk.create("/foo", false); > zk.getChild("/foo", this); > } > > public void process(WatchedEvent event) { > if(event.getType() == Event.EventType.NodeChildrenChanged) { > *List<String> children = zk.getChildren(event.getPath(), this);* > } > } > } > > Thanks.
https://www.mail-archive.com/zookeeper-user@hadoop.apache.org/msg01279.html
CC-MAIN-2018-47
refinedweb
157
71.71
Opened 10 years ago Closed 10 years ago Last modified 7 years ago #10516 closed (fixed) Admin search doesn't work when having multiple search_fields to the same base model. Description Searching in admin site does not work when search_fields has multiple elements from the same base class. This is best described by an example: admin.py: from testi.searchTest.models import * from django.contrib import admin class TitleInline(admin.TabularInline): model = TitleTranslation extra = 2 class RecommenderAdmin(admin.ModelAdmin): inlines = [TitleInline] class RecommendationAdmin(admin.ModelAdmin): inlines = [TitleInline] # This works search_fields = ('recommender__titletranslation__text', ) # But this doesn't # search_fields = ('titletranslation__text', 'recommender__titletranslation__text',) admin.site.register(Recommendation, RecommendationAdmin) admin.site.register(Recommender, RecommenderAdmin) models.py: from django.db import models class Title(models.Model): def __unicode__(self): try: return self.titletranslation_set.filter(lang="FI")[0].text except: return "No finnish name defined!" LANG_CHOICES = (('FI', 'Finnish'), ('EN', 'English'),) class TitleTranslation(models.Model): title = models.ForeignKey(Title) text = models.CharField(max_length = 100) lang = models.CharField(max_length = 2, choices = LANG_CHOICES) class Recommender(Title): pass class Recommendation(Title): recommender = models.ForeignKey(Recommender) Assume we have saved a recommendation with a title of 'Foo' and a recommender with a title of 'Bar'. The foreign key is set from 'Foo' to 'Bar'. In the example above, when searching for 'ar' nothing is found when using the second version of search_fields. When using the first version, The 'Foo' recommendation is found correctly. In the second version, searching works correctly through titletranslationtext. Attachments (2) Change History (13) comment:1 Changed 10 years ago by comment:2 Changed 10 years ago by comment:3 Changed 10 years ago by comment:4 Changed 10 years ago by Changed 10 years ago by Failing testcase comment:5 Changed 10 years ago by It looks like this might be caused by an ORM bug. Given two querysets q1 and q2, with list(q1) = [foo] and list(q2) = [foo], there's a case when q1 & q2 = []. I created a quick test to demonstrate the case. It's using the models from your example verbatim, but I'll clean it up once I've fixed the bug. comment:6 Changed 10 years ago by We really should be able to reproduce this without poking at internals(which is really want dupe select related is, lack of leading underscore be damned). comment:7 Changed 10 years ago by I'll bring up the (possible) ORM bug on the mailing list as a separate bug. It's actually pretty easy fix this bug without hitting the other one. Fix incoming. comment:8 Changed 10 years ago by Changed 10 years ago by fix + tests comment:9 Changed 10 years ago by comment:10 Changed 10 years ago by comment:11 Changed 7 years ago by Milestone 1.1 deleted won't have time to finish
https://code.djangoproject.com/ticket/10516
CC-MAIN-2018-47
refinedweb
464
51.04
RESTful APIs With the Play Framework - Part 1 RESTful APIs With the Play Framework - Part 1 In this article, we look at how to set up your development environment using the Play framework, and how to get Play going on your machine. Join the DZone community and get the full member experience.Join For Free The Future of Enterprise Integration: Learn how organizations are re-architecting their integration strategy with data-driven app integration for true digital transformation. During the last year, I was in many conferences talking about "RESTful Services with Play Framework, and a Security Level with JWT," an amazing experience that makes me want to share that with more people. I am writing a series of articles touching the aspects of my talk. We will start talking about the main Play Framework characteristics, how to develop RESTful services, and finally how to add a security level using JWT. Play Framework "Play is based on a lightweight, stateless, web-friendly architecture. Built on Akka, Play provides predictable and minimal resource consumption (CPU, memory, threads) for highly-scalable applications." - Play Framework Documentation Programming Language One of the things that makes Java a powerful programming language is the JVM (Java Virtual Machine). This has led to developing programming languages more modern that run over it, like Kotlin, JRuby, Jython, Apache Groovy, Clojure, Scala, etc. Play is developed on Scala, which allows us the versatility of using Java, Scala, or both. Resources Consumption Something impressive about Play is the low resources consumption. The previous image shows the performance of the server's CPU during stress tests. Those tests were conducted over a period of 3 hours, where up to 50 requests were sent simultaneously. The graphic shows us that it was not used more than 17.5% of the CPU during the tests. Now, answer this question. How many resources do you believe that have this server for can handle those tests?, well the server is an Amazon EC2 Instance, with OpenSuse, 1 CPU and 1GB of RAM. Really impressive. Reactive Framework Fewer Configurations Play has come preconfigured with Akka since version 2.6.x, and, in the lastest versions, with Netty. That means that we don't need to configure an App Server in our development environments, and production, QA, and development servers. JRebel Behavior When we develop with Java, one of the more unpleasant things can be redeploying everything when we want to test something. That process can be annoying, indeed, when we make it with an IDE's help, especially because that consumes time. With Play, we only need to save our job and refresh to see our changes. I like to call that "More Code, and Less Deploys." Start and Structure For developing with the Play Framework, we need SBT, a build tool for Scala and Java. You can download it and see the configuration instructions on the official website. You also need to have installed the Java JDK. Creating a New Project Once SBT is installed, we can start. To create a new project, you can use one of the follwoing commands: Command to start a Java-based project: $ sbt new playframework/play-java-seed.g8 Next, Play will request some basic information for the creation of the project, such as the name, the package, the version of Scala, Play, and SBT being used. If you do not enter anything and only press return, it will use the default values. This template generates a Play Java Project name [play-java-seed]: PlayJava organization [com.example]: com.auth0 scala_version [2.12.4]: play_version [2.6.10]: sbt_version [1.0.4]: Template applied in ./PlayJava Command to start a Scala-based project: $ sbt new playframework/play-scala-seed.g8 Next, Play will request \ basic information for the creation of the project, such as the name, the package, the version of Scala, Play, and SBT being used. If you do not enter anything and only press return, it will use the default values. This template generates a Play Scala Project name [play-java-seed]: PlayScala organization [com.example]: com.auth0 play_version [2.6.10]: sbt_version [1.0.4]: scalatestplusplay_version [2.12.4]: Template applied in ./PlayScala Building Your Deploy For the purposes of this article, we will use the Java project, nevertheless, you can find the code for both Java and Scala in the GitHub repo. To make our deploy, we need to go inside the project's directory, in this case PlayJava/ $ cd PlayJava/ Once inside the folder, we execute the command sbt run: $ sbt run [info] Loading settings from plugins.sbt,scaffold.sbt ... [info] Loading project definition from C:\Users\itrjwyss\Documents\PlayJava\project [info] Loading settings from build.sbt ... [info] Set current project to java (in build file:/C:/Users/itrjwyss/Documents/PlayJava/) --- (Running the application, auto-reloading is enabled) --- [info] p.c.s.AkkaHttpServer - Listening for HTTP on /0:0:0:0:0:0:0:0:9000 (Server started, use Enter to stop and go back to the console...) Now we can go to our browser or client to test RESTful services like Insomnia, and load Voilà, we have running our Play application! If you go to the console you will see the following: (Server started, use Enter to stop and go back to the console...) [info] p.a.h.EnabledFilters - Enabled Filters (see <>): play.filters.csrf.CSRFFilter play.filters.headers.SecurityHeadersFilter play.filters.hosts.AllowedHostsFilter [info] play.api.Play - Application started (Dev) Everything you see in the console is recorded in the Play logs file. Basic Structure - app: In this directory will have all our source code (controllers/) and our HTML templates (views/). - conf: In this directory are the configuration files for our Play application. - logs: In this directory, you will find Play's log files. - project: In this directory, you will find SBT's configuration files. - public: A static assets directory, like images, CSS style files, and javascript files. - test: Sources to carry out unit tests. Play is based on JUnit to perform this functionality. Now let's see a bit of the general syntax that Play handles. The first files that we will visit will be those located in the app/views/ directory, there we have two files: main.scala.html and index.scala.html. First, let's look at main.scala.html: @* * This template is called from the `index` template. This template *> And now, index.scala.html: @() @main("Welcome to Play") { <h1>Welcome to Play!</h1> } One of the virtues of Play in terms of front-end development that is worth mentioning, although that is not the objective of this article, is the inheritance between templates. In this case, index.scala.html inherits from main.scala.html. Much of the magic of its HTML syntax occurs with @, we can notice that it uses it for comments, insert blocks of code, define receive parameters, and even inheritance as can be seen with @main() in index.scala.html, this indicates that index inherits from the main template. In main.scala.html we can see @content, which indicates that what will be inserted into the HTML code, in this case, it's an index. Let's continue to see the structure of a Controller, the place where all the magic happens. Play is based on the MVC model, the Models are DB's admin structures, the Views are HTML templates, and the controllers, well, are Play Controllers. Another important aspect of Play is that RESTful is a first-class citizen, so everything is RESTful, the controllers are in the app/controllers/ directory. HomeController.java package controllers; import play.mvc.Controller; import play.mvc.Result; /** * This controller contains an action to handle HTTP requests * to the application’s home page. */ public class HomeController extends Controller { /** *()); } } Play works through Actions - an action is just a method in charge of processing Request Parameters and producing a Result that will be sent to the client. Therefore, it is the implementation of a WS RESTful action. On the other hand, a Controller is nothing more than a class that inherits from play.mvc.Controller and is responsible for managing a set of actions. To finish with the structure of a Play project, we will talk about how the routes are handled, and, for this, we will explore the routes file in the conf/ directory. # Routes # This file defines all application routes (Higher priority routes first) # ~~~~ # An example controller showing a sample home page GET / controllers.HomeController.index # Map static resources from the /public folder to the /assets URL path GET /assets/*file controllers.Assets.versioned(path=”/public”, file: Asset) The syntax of the routes file is in Scala, so here we can include comments with #. The next is the structure of the routes. The first thing we must indicate is the HTTP method that we will use (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS) or we can use * to indicate that it can be consumed by any of the methods. The next thing to indicate is what the action will be called. This name will be added to our domain. For example, if our domain were example.com and we had a definition like the following: GET /pathExample This action would be call: example.com /pathExample Finally, we must indicate to which action this route will redirect us. For this example, assume that within our Controller (HomeController) we have the pathExample action, so the final route would look like this: GET /pathExample controllers.HomeController.pathExample In this article, we have covered basic aspects of Play. In the next article of this series, we will talk about developing RESTful Services. }}
https://dzone.com/articles/restful-apis-with-play-framework-part-1
CC-MAIN-2018-43
refinedweb
1,600
65.01
...This is a preview just for Perlmonks of the continuing work I'm doing with my BackPAN indexer.... MyCPAN can now create CPAN-like directories out of a directory of distributions. Run a script then point CPAN.pm at your directory to use it as your CPAN source. This worked was sponsored by a customer at the day job (and talk to me if you can convince your boss that this might be something worthwhile to sponsor too). Previously, you could do this task with a minicpan and CPAN::Mini::Inject. You kept two repositories. You updated minicpan, which undid all of your private stuff, then you re-injected everything. CPAN::Mini::Inject then updated the modules/02package.details.txt.gz and CHECKSUMS files. That's fine if you're injecting a few things. My task is to create a CPAN-like structure of stuff that is mostly not on CPAN, or when nothing in the private CPAN comes from the real CPAN. We've been calling this "DPAN", for DarkPAN. You don't have to worry about what's in a distro or which author it should belong too, and you don't have parallel directories. Just dump a bunch of distros in a directory. Those might be private modules, CPAN modules, forked modules, vendor modules, and so on. DPAN doesn't care. Just dump them in a directory. MyCPAN::Indexer pulls out all of the information and turns the source directory into something that the CPAN tools can understand. You start with MyCPAN::Indexer. It's still in development, so some things are a little rough. Install it or get it from Github. Install the dependencies. Inside MyCPAN::Indexer is an examples/ directory with a bunch of junk in it. You want the dpan script. % perl examples/dpan my_modules_dir/ [download] With the defaults, this looks for all distributions under my_modules_dir, collects information about each and puts it in the indexer_reports/ directory. It then goes through all of the reports and collects the information it needs for the CPAN index files. Finally, in my_modules_dir/ it creates the modules/ directory with the index files the CPAN tools need and puts a CHECKSUMS file in each directory that has distributions in it. You can now point CPAN.pm to this directory and install directly from it. There are a couple of things to watch out for: The lastest version of my cpan script might help you. You can dump and load configs without fooling with the shell. The -J (capital J) will dump the current config to STDOUT. It's the same format as CPAN::Config: % cpan -J > MyCPANConfig.pm [download] Edit that file how you like. I change the urllist. I have several versions for testing different things. If I want to install Foo::Bar with my DPAN config pointing to my DarkPAN, I load the right configuration with -j (lowercase j): % cpan -j DPANConfig.pm Foo::Bar [download] Now, I've said that DPAN is for DarkPAN, but it's also for another thing I want to do: DistributedPAN. If you look in 02packages.details.txt, you'll see lines like: Foo::Bar 1.23 B/BD/BDFOY/Foo-Bar-1.23.tgz [download] When I created CPAN::PackageDetails to play with this, we discovered that CPAN.pm will happily deal with absolute paths there. The distributions files could be anywhere: Foo::Bar 1.23 /usr/local/dpan/Foo-Bar-1.23.tgz Bar::Baz 2.45 /home/brian/dists/Bar-Baz-2.45 [download] Once I started thinking about that, I wanted to make it so the files don't even have to be local: Foo::Bar 1.23 /usr/local/dpan/Foo-Bar-1.23.tgz Bar::Baz 2.45 Quux 2.45 +.45 [download] Once that third column handling is refactored into a general URl or file fetcher, things get more interesting. I haven't looked at what that might take in CPAN.pm though. And, since I was writing CPAN::PackageDetails, I wanted to support another possible format. This one has a column for the author and might list the same namespace several times Foo::Bar BDFOY 1.23 B/BD/BDFOY/Foo-Bar-1.23.tgz Foo::Bar BDFOY 2.01 /home/brian/dists/Foo-Bar-2.01.tgz Foo::Bar SNUFFY 1.24 [download] Remember Synopsis 11? Perl 6 supports not only version restrictions on loading a module, but loading the same module from different authors: use Dog:ver(Any):auth(Any); use Dog:ver(Any):auth<cpan:BDFOY>; use Dog:ver<1.2.1>:auth(Any); use Dog:ver(1.2.1..1.2.3); [download] With a change to 02packages.details.txt, the CPAN tools can support this too. Not to worry though. That's just something fun to think about right now. Once the rest of DPAN seems stable, I can start adding cool features like that. This one has a column for the author and might list the same namespace several
http://www.perlmonks.org/index.pl?node_id=722831
CC-MAIN-2013-48
refinedweb
832
68.57
Jupyter Notebooks Contents Jupyter Notebooks# The py5 library is designed to work well with Jupyter tools, including Jupyter notebook. There are included IPython magics that are useful for supporting your development and documentation efforts as well as your creative endeavors. Used well, they can greatly enhance your programming workflow. To use py5 in a notebook, first import the library: import time import py5_tools import py5 You should never need to import the py5jupyter library directly. Getting Help# Before continuing, it is worth pointing out that you can access the docstrings for any py5 functions by appending a ? to the end of the function, or with the builtin help function. Using the ? which something like py5.rect? temporarily displays the documentation at the bottom of the notebook window. The builtin help function puts the result in the notebook cell. help(py5.rect) Help on function rect in module py5: rect(*args) Draws a rectangle to the screen. Underlying Processing method: PApplet.rect Methods ------- You can use any of the following signatures: * rect(a: float, b: float, c: float, d: float, /) -> None * rect(a: float, b: float, c: float, d: float, r: float, /) -> None * rect(a: float, b: float, c: float, d: float, tl: float, tr: float, br: float, bl: float, /) -> None Parameters ---------- a: float x-coordinate of the rectangle by default b: float y-coordinate of the rectangle by default bl: float radius for bottom-left corner br: float radius for bottom-right corner c: float width of the rectangle by default d: float height of the rectangle by default r: float radii for all four corners tl: float radius for top-left corner tr: float radius for top-right corner Notes -----_mode()``. Pause to take a moment to appreciate that documentation, with its proper type signatures and explicit variable types. You’ll also notice the content is analogous what is in py5’s rect() reference documentation. Producing thorough and coordinated py5 docstrings and reference documentation like this took an enormous amount of work. You’ll notice that all the usual Jupyter niceties such as tab completion work for py5. There are also Python typehints for all py5 objects. Load IPython Magics# Next, load the py5 magics: %load_ext py5 These “magic” commands are like extra functionality added to what Python and Jupyter notebooks can already do. The py5 magics all start with “py5”. The cell magics are: As before, documentation for each is available by appending a ?, such as when you type %%py5draw? in an empty cell. The builtin help function does not work with IPython magics. See below for demonstrations of what each does. Running py5 on Mac Computers# There are several known issues running py5 on OSX computers. If you use a Mac, you should read about the Mac issues before continuing. Bottom line, the %gui osx Jupyter magic is necessary to use py5 on OSX computers. Static Sketches# The below example creates a static image with some simple shapes. The first line in the cell, %%py5draw 300 200, is not Python code. Instead, it is a command to Jupyter itself, instructing it to send the rest of the cell’s contents to a special py5 draw function. Observe that there are no defined setup or draw functions. %%py5draw 300 200 # make the background light gray py5.background(240) # draw a red square py5.fill(255, 0, 0) py5.rect_mode(py5.CENTER) py5.rect(170, 80, 100, 100) # add a thick green line py5.stroke(0, 255, 0) py5.stroke_weight(15) py5.line(40, 30, 220, 180) The code can access variables and functions defined in other non-magic notebook cells. This is especially useful when the code leverages py5 functionality. For example, the below function sets the fill color to a random color. def pick_random_fill(): py5.fill(py5.random(255), py5.random(255), py5.random(255)) The below example uses pick_random_fill to draw randomly colored rectangles. This example is a bit contrived, but you do see how the code below can call a function defined elsewhere. %%py5draw 300 200 py5.background(240) py5.rect_mode(py5.CENTER) for i in range(100): pick_random_fill() py5.rect(py5.random(py5.width), py5.random(py5.height), 10, 10) The pick_random_fill function can be reused again elsewhere in this notebook. By default, any new functions and variables defined in that %%py5draw cell are not available outside of the cell. However, you can explicitly change this. See below for further discussion. Saving to a File# If you like you can save the generated image to a file with the -f parameter, like so: %%py5draw 300 200 -f images/jupyter_notebooks/simple_example.png py5.background(240) py5.rect_mode(py5.CENTER) for i in range(100): pick_random_fill() py5.rect(py5.random(py5.width), py5.random(py5.height), 10, 10) PNG file written to images/jupyter_notebooks/simple_example.png Now there’s an image on my computer located at images/jupyter_notebooks/simple_example.png. I can embed that in this notebook using markdown. OpenGL Renderers# You can also use the OpenGL renderers with the -r parameter, like so. %%py5draw 300 200 -r P2D py5.background(240) py5.rect_mode(py5.CENTER) for i in range(100): pick_random_fill() py5.rect(py5.random(py5.width), py5.random(py5.height), 10, 10) When that cell runs, a py5 window is quickly opened and closed. For whatever reason, the Processing’s OpenGL renderers cannot draw to an invisible window (but I would be delighted to be proven wrong about that). The previous %%py5draw examples in this notebook used a special HIDDEN renderer based on the default JAVA2D renderer that does not need to open a window. That HIDDEN renderer was created just for this purpose. Despite my best efforts, I couldn’t create similar renderers based on the OpenGL renderers P2D and P3D. The 3D renderer also works: %%py5draw 300 300 -r P3D py5.background(240) N = 10 for i in range(N): py5.push_matrix() pick_random_fill() py5.translate(i * py5.width / N, i * py5.width / N, i * 20 - 200) py5.box(40) py5.pop_matrix() SVG Renderer# To create SVG images, use the %%py5drawsvg magic. As before, the result can be saved to a file with the -f parameter. %%py5drawsvg 300 200 -f /tmp/test.svg py5.background(240) py5.rect_mode(py5.CENTER) for i in range(100): pick_random_fill() py5.rect(py5.random(py5.width), py5.random(py5.height), 10, 10) SVG drawing written to /tmp/test.svg PDF Renderer# Write to PDF files using %%py5drawpdf. Since Jupyter notebook does not support embedded PDF files, writing the output to a file is not optional. %%py5drawpdf 300 200 /tmp/simple_example.pdf py5.background(240) py5.rect_mode(py5.CENTER) for i in range(100): pick_random_fill() py5.rect(py5.random(py5.width), py5.random(py5.height), 10, 10) PDF written to /tmp/simple_example.pdf DXF Renderer# Write 3D objects to DXF files with %%py5drawdxf. This probably won’t be a popular choice, but maybe somebody will appreciate it. %%py5drawdxf 200 200 /tmp/test.dxf py5.translate(py5.width / 2, py5.height / 2) py5.rotate_x(0.4) py5.rotate_y(0.8) py5.box(80) DXF written to /tmp/test.dxf !head /tmp/test.dxf 0 SECTION 2 ENTITIES 0 3DFACE 8 0 10 -56.562515 Variable Scope# By default, new variables defined inside cell magics such as %%py5draw cannot be accessed elsewhere in the notebook. Consider the below example. It creates new variables random_x and random_y to store the location of the square. %%py5draw 300 200 py5.background(240) py5.rect_mode(py5.CENTER) random_x = py5.random(py5.width) random_y = py5.random(py5.height) py5.rect(random_x, random_y, 50, 50) The variables random_x and random_y are not accessible outside of that cell: random_x, random_y --------------------------------------------------------------------------- NameError Traceback (most recent call last) Input In [15], in <cell line: 1>() ----> 1 random_x, random_y NameError: name 'random_x' is not defined This behavior is by design. Consider that the py5 library is using the Processing library to create these graphics. Builtin Processing objects such as PImage or PGraphics are designed to be associated with one and only one Processing Sketch. Py5 can let users write code to that subverts these assumptions, and as a result use Processing in a way that is completely different from how it was designed to be used. Sometimes this can be beneficial, but other times it will cause unexpected errors. If you understand the risks, or if you are working with non-Processing objects (as is the case for random_x and random_y in the above example), you can use the --unsafe parameter. This lets the cell magic add new variables and functions to the notebook namespace. As the name implies, you can cause problems for yourself by using this. %%py5draw 300 200 --unsafe py5.background(240) py5.rect_mode(py5.CENTER) random_x = py5.random(py5.width) random_y = py5.random(py5.height) py5.rect(random_x, random_y, 50, 50) random_x, random_y (256.6723633050369, 67.38466313744004) Animated Sketches# Of course, there’s more to py5 than static Sketches. The py5 magics will support animated Sketches as well. Note that starting your development process with static Sketches is a great way to write py5 code. For example, you can quickly develop functions for parts of your creation and test them out with static Sketches, and later use those same functions in your final animation. Let’s create a simple example. The below setup function will tell py5 to create a 500 by 400 Sketch window. It will set the background color and set the rect mode. def setup(): py5.size(500, 400, py5.P2D) py5.background(240) py5.rect_mode(py5.CENTER) Next, the draw function to draw random squares. def draw(): random_x = py5.random(py5.width) random_y = py5.random(py5.height) py5.rect(random_x, random_y, 10, 10) Finally, let’s define a mouse_clicked function to change the fill color when the Sketch is clicked. def mouse_clicked(): pick_random_fill() To run the Sketch, use the run_sketch() method. It will pull out the setup and draw functions from the notebook’s namespace and put them together in a Sketch. py5.run_sketch() print('the sketch is running!') the sketch is running! If you are runnning this notebook locally, you will see a new window open for the running Sketch. If you are running this through Binder, or possibly using the documentation website’s Live Code feature (see the rocket ship icon at the top of the page), the Sketch is running on a server somewhere in the cloud. In that case, to see the Sketch you will need to create a Sketch Portal using py5tools.sketch_portal(). This will create what is effectively a view into what is being displayed on that Sketch window running in the cloud. To be clear, although you will see a live animation in the Sketch Portal, the Sketch is not actually running in your browser. It’s kind of like when you watch a live television program on your TV. The live events are taking place somewhere else, but images of the events are being broadcast to your television. py5_tools.sketch_portal() Click on the Sketch Portal to make the fill color change. The Sketch Portal will respond to all of py5’s keyboard and mouse events. It is fully interactive! By default, the run_sketch() method returns right away, as illustrated by the Screenshots# The Sketch window cannot be embedded into the notebook, but the py5_tools.screenshot() function can grab a single snapshot of the window. time.sleep(3) sketch_snapshot = py5_tools.screenshot() sketch_snapshot Observe that this function returns a frame of the Sketch as a PIL Image object. print(type(sketch_snapshot)) <class 'PIL.PngImagePlugin.PngImageFile'> The py5_tools.save_frames() function will save multiple frames to a directory. Of course you can also call save_frame() from the draw method, but that would require you to redefine the draw method with a few extra lines of code. This is more convenient. frames = py5_tools.save_frames('/tmp/testframes/', start=0, limit=10) frames Those frames can be assembled into a video file. The py5_tools.capture_frames() function is similar to py5_tools.save_frames() except it returns the frames as a list of PIL Image objects. frames = py5_tools.capture_frames(10, period=1, block=True) frames[0] frames[-1] Animated GIFs# The last magic creates animated GIFs from your Sketch. Everybody loves animated GIFs. py5_tools.animated_gif('images/jupyter_notebooks/simple_example.gif', 10, 1, 0.5) The animated GIF can then be embedded in a notebook markdown cell. Print Statements# Question: if the user’s draw method contains This would be a simple question if the run_sketch() method did not return right away (which you could achieve by passing the parameter block=False). The print statements would always go into the output of the cell with the call to that method. When the Sketch exits, the output for that cell would be complete. By default, the run_sketch() method does return right away when called from a Jupyter notebook. The print statements will still go to the output of the cell with the call to that method, but when you move on to the next cell, the print statements will start to appear there instead. Why? This has to do with the inner workings of Jupyter notebooks. It gets weirder if you delete the cell that is currently receiving the output. If that happens, the print output will disappear completely. This is less than perfect, and might frustrate users who like to debug their code with print statements. Instead, use the println() method. It will route all print statements to the output of the cell that made the call to run_sketch(). The functionality of println() can be customized with set_println_stream(). If instead you want to send messages to the Jupyter notebook log, you can always do so like this: shell = get_ipython() shell.log.critical('test message') In the terminal I used to run jupyter notebook, I see this message: [IPKernelApp] CRITICAL | test message This is a more reliable debugging technique.
https://py5.ixora.io/tutorials/jupyter_notebooks.html
CC-MAIN-2022-40
refinedweb
2,302
66.74
So I have these 2 line in my xaml (at appropriate locations) to add a custom control to my pages. xmlns:local="clr-namespace:AProject;assembly=AProject" <local:Nested.AControl/> Sometimes it works fine, but other times I get an error "Type Nested not found in xmlns clr-namespace:AProject;assembly=AProject" and I have to change it to xmlns:nested="clr-namespace:AProject.Nested;assembly=AProject" <nested:AControl/> I can't figure out what causes the namespace to not be found. In fact, in one particular XAML I use two nested namespaces and one works with"local" but the other has to used "nested". Can someone shed any light on the reason this is happening? Answers No one replied. Bump.
https://forums.xamarin.com/discussion/comment/256009
CC-MAIN-2021-04
refinedweb
121
63.19
In today’s Programming Praxis exercise, our task is to see if Benford’s law (lower digits are more likely to be the first digit of numbers found i large collections of data) holds for the littoral areas of lakes in Minnesota. Let’s get started, shall we? Some imports: import Data.List import Text.Printf The algorithm for calculating the distribution of leading digits given a group of numbers is virtually identical to the Scheme version, despite the fact that I didn’t look at the solution beforehand. It’s not too surprising though, since it’s simply the most obvious method. Note that the function argument is a list of floats. Initially I assumed all areas were integers, which resulted in incorrect results until I found that there were 10 floats hidden in the input (thank god for regular expressions). firstDigits :: [Float] -> [(Char, Double)] firstDigits xs = map (\ds -> (head ds, 100 * toEnum (length ds) / toEnum (length xs))) . group . sort $ map (head . show) xs With that function out of the way, the problem becomes trivial: just call firstDigits on all the appropriate numbers. shriram :: [[String]] -> [(Char, Double)] shriram xs = firstDigits [n | [(n,_)] <- map (reads . (!! 3)) xs] Of course we need to run the algorithm over the given data, using the parser from two exercises ago: main :: IO () main = either print (mapM_ (uncurry $ printf "%c %f\n") . shriram) =<< readDB csv "csv.txt" This produces the same list of percentages as the Scheme version. Looks like Benford’s Law holds in this case as well. Tags: benford, bonsai, code, Haskell, kata, law, praxis, programming
http://bonsaicode.wordpress.com/2010/10/26/programming-praxis-benford%E2%80%99s-law/
CC-MAIN-2014-35
refinedweb
264
64.91
Integrating Cassandra, Prometheus, & Grafana with AWS-EKS! This blog will explain the integration of Cassandra deployment on AWS-EKS with cluster monitoring by Prometheus, & cluster metrics visualization by Grafana! An ultimate integration is explained in this blog which can be used also for the huge deployments. In this world, we all know the machines might fail, but what if we are providing a very critical service to our customers, & then there is a failure. This scenario will definitely create a bad impact on the customers who are willing to avail of our services, not only that how much it takes to bring the services back online is also a very important factor. In this Agile world, the minimum time it takes to handle the failover for any machine, is the key to keep any business running, or any other service running. We can achieve it manually, but it will be a very slow process. There exists a better alternative to this problem, & it is to use container technology with container orchestration tools. Some of the examples of container technology are Docker, PodMan, CRI-O, Rocker, etc. Some of the examples of container management tool are Kubernetes, Opneshift, etc. In this article, I will explain the deployment of an amazing database Cassandra on the AWS-EKS which is a managed Kubernetes service. If we are using this service, then we have to just only take care of our product, the master node of Kubernetes will be automatically managed by the AWS-EKS service. Note: Anybody willing to the same practical should keep in mind that this service is not supported by AWS educate account & it is chargeable service. Pre-requisite Softwares for doing this practical - AWS CLI - kubectl package - eksctl package Flow of the complete Integration - EKS Cluster creation. - Updating the kubectl config file with the EKS cluster information. - Creating a Cassandra deployment. - Installing “Helm” software which acts as a package manager for the Kubernetes. - Installing “Prometheus” using Helm. - Installing “Grafana” using Helm. EKS Cluster Creation! In order to run the above script, run the command “eksctl create cluster -f <filename in which this script is stored>”. Updating kubectl config File! To update the kubectl config file, first of all, configure your AWS CLI, then run the command given below! aws eks update-kubeconfig --name <eks cluster name> --region <region name in which the cluster is running>For example: aws eks update-kubeconfig --name eks-tw-cluster --region ap-south-1 Creating a Cassandra deployment This is a long process as we have to do multiple things in it because EFS is used in this part to provide storage with the capability of multiple mounting support. The very first step in this part is to first of all support of EFS storage for shared storage and efficient network storage. In order to proceed for the support of the same, we have to install one package into the worker Kubernetes nodes. To do the same, login to the worker nodes one by one using ssh or any other methods, and run the command given below to install the efs support software in them. sudo yum install amazon-efs-utils Now, we have to create the EFS provisioner to use the EFS storage because by default it is not available in the EFS service. Now, we have to bind a cluster-admin role to perform all the operations with the EFS. Now, in the last step, we have to create the EFS Storage. At last, we can create a Cassandra deployment. Installing Helm software! To install this software, visit the link given below, & install it according to the OS you are using. After installing Helm, first of all we have to initialize it, for that run the command “helm init”, then we have to add an address where the packages (known as charts in Kubernetes World) are available to download & install. Run the command given below for the same. helm repo add stable To use Helm properly, we have to configure some settings of “Tiller” software which is a server-side software of Helm. To configure the server properly run the below commands: kubectl -n kube-system create serviceaccount tillerkubectl create clusterrolebinding tiller --clusterrole cluster-admin --serviceaccount=kube-system:tillerhelm init --service-account tiller Installing Prometheus using Helm! For better management, create a different namespace for Prometheus by running the command “kubectl create ns prometheus”. Now, to install the Prometheus software which is used for monitoring, run the command given below. helm install prometheus stable/prometheus --namespace prometheus To access Prometheus from the local machine, run the following command. kubectl -n prometheus port-forward svc/prometheus-server 8888:80 Installing Grafana using Helm For better management, create a different namespace for Prometheus by running the command “kubectl create ns grafana”. Now, to install the Grafana software which is used for monitoring, run the command given below. In the below command, we have set the admin password to “123456” and created 1 LoadBalancer for the Grafana. helm install grafana stable/grafana --namespace=grafana --set adminPassword=123456 --set service.type=LoadBalancer From this command, in the present scenario, the Load Balancer will be created in AWS using AWS-ELB service, once it is created and connected, one IP will be provided use that, to connect to the Grafana tool which will help to visualize the information of Prometheus in a visual way. After accessing Grafana through the ELS IP, you will be landed on the login page, now login using the username as admin & password as 123456 which we have initialized above. Now, set the data source as Prometheus and use the IP of the prometheus server obtained by running the command “kubectl get svc -n promethues”. Then import any available dashboard. Finally, you will see the output of your cluster usage in real time. Code used in this blog, is present in my Organization Repository, if anybody wants to use the code, click on the link given below. I hope my article explains each and everything related to the integration of the multiple Softwares along with the explanation & execution of code. Thank you so much for investing your time in reading my blog & boosting your knowledge!
https://harshitdawar.medium.com/integrating-cassandra-prometheus-grafana-with-aws-eks-ec8072bdf7a6
CC-MAIN-2021-04
refinedweb
1,032
60.45
How to Convert Video Using FFmpeg in Node.js December 17th, 2021 What You Will Learn in This Tutorial How to build a command line interface in Node.js to convert videos using the FFmpeg command line tool. Master Websockets — Learn how to build a scalable websockets implementation and interactive UI. Getting started For this tutorial, we're going to build a Node.js project from scratch. Make sure that you have the latest LTS version of Node.js installed on your machine. If you don't have Node.js installed, read this tutorial first before continuing. If you have Node.js installed, next, we want to create a new folder for our project. This should be placed wherever you keep projects on your computer (e.g., ~/projects where ~is the home folder or root on your computer). Terminal mkdir video-converter cd into that folder and run npm init -f: Terminal cd video-converter && npm init -f This will automatically initialize a package.json file inside of your project folder. The -f stands for "force" and skips the automated wizard for generating this file (we skip it here for the sake of speed but feel free to omit the -f and follow the prompts). Next, we're going to modify the package.json that was created to set the project type to be module: Terminal { "name": "video-converter", "type": "module", "version": "1.0.0", ... } Doing this enables ESModules support in Node.js allowing us to use import and export in our code (as opposed to require() and modules.export. Next, we need to install one dependency via NPM, inquirer: Terminal npm i inquirer We'll use this package to create a command line prompt for gathering information about the video we're going to convert, the format we're going to output, and the location of the output file. To complete our setup, the last thing we need to do is download a binary of the ffmpeg command line tool which will be the centerpiece of our work. This can be downloaded here (the version used for this tutorial is 4.2.1—make sure to select the binary for your operating system). When you download this, it will be as a zip file. Unzip this and take the ffmpeg file (this is the binary script) and put it at the root of your project folder (e.g., ~/video-converter/ffmpeg). That's all we need to get started building the video converter. Optionally, you can download a test video to convert here (make sure to place this in the root of the project folder for easy access). Adding a command line prompt To make our conversion script more user friendly, we're going to implement a command line prompt that asks the user questions and then collects and structures their input for easy use in our code. To get started, let's create a file called index.js inside of our project: /index.js import inquirer from 'inquirer' try { // We'll write the code for our script here... } catch (exception) { console.warn(exception.message); } First, we want to set up a boilerplate for our script. Because we'll be running our code in the command line via Node.js directly, here, instead of exporting a function, we're just writing our code directly in the file. To guard against any errors we're using a try/catch block. This will allow us to write our code inside of the try part of the block and if it fails, "catch" any errors and redirect them to the catch block of the statement (where we're logging out the message of the error/ exception). Preemptively, up at the top of our file, we're importing the inquirer package we installed earlier. Next, we're going to use this to kick off our script and implement the questions we will ask a user before running FFmpeg to convert our video. /index.js import inquirer from 'inquirer';; // We'll call to FFmpeg here... }); } catch (exception) { console.warn(exception.message); } Here, we're making use of the .prompt() method on the inquirer we imported from the inquirer package. To it, we pass an array of objects, each describing a question we want to ask our user. We have two types of questions for our users: input and list. The input questions are questions where we want the user to type in (or paste) text in response while the list question asks the user to select from pre-defined list of options (like a multiple choice test question) that we control. Here is what each option is doing: typecommunicates the question type to Inquirer. namedefines the property on the answers object we get back from Inquirer where the answer to the question will be stored. messagedefines the question text displayed to the user. - For the listtype question, choicesdefines the list of choices the user will be able to select from to answer the question. That's all we need to do to define our questions—Inquirer will take care of the rest from here. Once a user has completed all of the questions, we expect the inquirer.prompt() method to return a JavaScript Promise, so here, we chain on a call to .then() to say "after the questions are answered, call the function we're passing to .then()." To that function, we expect inqurier.prompt() to pass us an object containing the answers the user gave us. To make these values easier to access and understand when we start to integrate FFmpeg, we break the answers object into individual variables, with each variable name being identical to the property name we expect on the answers object (remember, these will be the name property that we set on each of our question objects). With this, before we move on to implementing FFmpeg, let's add a little bit of validation for our variables in case the user skips a question or leaves it blank. /index.js import inquirer from 'inquirer'; import fs from 'fs';); } // We'll implement FFmpeg here... }); } catch (exception) { console.warn(exception.message); } Up at the top of the file, first, we've added fs (the built-in Node.js file system package). Back in the .then() callback for our call to inquirer.prompt(), we can see an if statement being defined just below our variables. Here, the one variable we're concerned about is the fileToConvert. This is the original video file that we want to convert to one of our three different formats ( mp4, mov, or mkv). To avoid breaking FFmpeg we need to verify two things: first, that the user has typed in a file path (or what we assume is a file path) and that a file actually exists at that path. Here, that's exactly what we're verifying. First, does the fileToConvert variable contain a truthy value and second, if we pass the path that was input to fs.existsSync() can Node.js see a file at that location. If either of those return a falsey value, we want to return an error to the user and immediately exit our script. To do it, we call to the .exit() method on the Node.js process passing 0 as the exit code (this tells Node.js to exit without any output). With this, we're ready to pull FFmpeg into play. Wiring up FFmpeg Recall that earlier when setting up our project, we downloaded what's known as a binary of FFmpeg and placed it at the root of our project as ffmpeg. A binary is a file which contains the entirety of a program in a single file (as opposed to a group of files linked together via imports like we may be used to when working with JavaScript and Node.js). In order to run the code in that file, we need to call to it. In Node.js, we can do this by using the exec and execSync functions available on the child_process object exported from the child_process package (built into Node.js). Let's import child_process now and see how we're calling to FFmpeg (it's surprisingly simple): /index.js import child_process from 'child_process'; import inquirer from 'inquirer'; import fs from 'fs'; try { inquirer.prompt([ ... ])); } child_process.execSync(`./ffmpeg -i ${fileToConvert} ${outputName ? `${outputPath}/${outputName}.${outputFormat}` : `${outputPath}/video.${outputFormat}`}`, { stdio: Object.values({ stdin: 'inherit', stdout: 'inherit', stderr: 'inherit', }) }); }); } catch (exception) { console.warn(exception.message); } Here, just beneath our if check to ensure our fileToConvert exists, we make a call to child_process.execSync() passing a string using backticks (this allows us to make use of JavaScript's string interpolation, or, embedding the values of variables into a string dynamically). Inside of that string, we begin by writing ./ffmpeg. This is telling the execSync function to say "locate the file ffmpeg in the current directory and run it." Immediately after this, because we expect ffmpeg to exist, we start to pass the arguments (also known as "flags" when working with command line tools) to tell FFmpeg what we want to do. In this case, we begin by saying that we want FFmpeg to convert an input file -i which is the fileToConvert we received from our user. Immediately after this—separated by a space—we pass the name of the output file with the format we want to convert our original file to as that file's extension (e.g., if we input homer-ice-cream.webm we might pass this output file as homer.mkv assuming we selected the "mkv" format in our prompt). Because we're not 100% certain what inputs we'll get from the user, we make the output value we're passing to ffmpeg more resilient. To do it, we use a JavaScript ternary operator (a condensed if/else statement) to say "if the user gave us an outputName for the file, we want to concatenate that together with the outputPath and outputFormat as a a single string like ${outputPath}/${outputName}.${outputFormat}. If they did not pass us an outputName, in the "else" portion of our ternary operator, we concatenate the outputPath with a hardcoded replacement for outputName "video" along with the outputFormat like ${outputPath}/video.${outputFormat}. With all of this passed to child_process.execSync() before we consider our work complete, our last step is to pass an option to execSync() which is to tell the function how to handle the stdio or "standard input and output" from our call to ffmpeg. stdio is the name used to refer to the input, output, or errors logged out in a shell (the environment our code is running in when we use execSync). Here, we need to pass the stdio option to execSync which takes an array of three strings, each string describing how to handle one of three of the types of stdio: stdin (standard input), stdout (standard output), stderr (standard error). For our needs, we don't want to do anything special for these and instead, prefer any output is logged directly to the terminal where we execute our Node script. To do that, we need to pass an array that looks like ['inherit', 'inherit', 'inherit']. While we can certainly do that directly, frankly: it doesn't make any sense. So, to add context, here we take an object with key names equal to the type of stdio we want to configure the output setting for and values equal to the means for which we want to handle the output (in this case 'inherit' or "just hand the stdio to the parent running this code."). Next, we pass that object to Object.values() to tell JavaScript to give us back an array containing only the values for each property in the object (the 'inherit' strings). In other words, we fulfill the expectations of execSync while also adding some context for us in the code so we don't get confused later. That's it! As a final step, before we run our code, let's add an NPM script to our package.json file for quickly running our converter: package.json { "name": "video-converter", "type": "module", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "node index.js", "test": "echo \"Error: no test specified\" && exit 1", "convert": "" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "inquirer": "^8.2.0" } } This one is a tiny addition. Here, we've added a new property "start" in the "scripts" object set to a string containing node index.js. This says "when we run npm start in our terminal, we want you to use Node.js to run the index.js file at the root of our project." That's it! Let's give this all a test and see our converter in action: Wrapping up In this tutorial, we learned how to write a command line script using Node.js to run FFmpeg. As part of that process, we learned how to set up a prompt to collect data from a user and then hand that information off to FFmpeg when running it using the Node.js child_process.execSync() function. Get the latest free JavaScript and Node.js tutorials, course announcements, and updates from CheatCode in your inbox. No spam. Just new tutorials, course announcements, and updates from CheatCode.
https://cheatcode.co/tutorials/how-to-convert-video-using-ffmpeg-in-node-js
CC-MAIN-2022-21
refinedweb
2,212
63.7
There are different situations, when you may want to process email messages automatically. I will give some examples related to Vulnerability Management: - Send a message to your colleagues that you are going to start a network vulnerability scan or WAS scan. It is much better than investigating performance problems in a hurry. - Send the results of vulnerability scanning to colleagues or a responsible employee. Many patch management and configuration issues can be delegated to the end user directly without bothering IT department. - Process the response (if any) on your message. If it is not, you can send another message or escalate the problem. - Send a report with the current security status in the organization to your colleagues and boss. - Some systems you can integrate by email only. They will send messages to some email address and you will process them automatically. - Maybe you do not like existing email clients and you want to write your own? 😉 In any case, the ability to send e-mails can be very useful. How to do this in python? Let’s assume that your IT team has granted you access to smtp and imap servers. Sending messages SMTP is a good and clear protocol for sending messages. Without SSL Before making any scripting it may be useful to test sending manually using Telnet. You need to connect to the server and perform some commands. Note that after AUTH LOGIN the server will suddenly start to speak with you in base64, asking username (“VXNlcm5hbWU6”) and password (“UGFzc3dvcmQ6”), and you will need to answer in base64 also. So, prepare login and passport in base64 form using: $ echo -n my_email_account | base64 bXlfZW1haWxfYWNjb3VudA== $ echo -n my_secure_password | base64 bXlfc2VjdXJlX3Bhc3N3b3Jk If your server works without SSL, you can try to send a message this way: $ telnet smtp.corporation.com 25 EHLO AUTH LOGIN <Server shows VXNlcm5hbWU6 - Username> bXlfZW1haWxfYWNjb3VudA== <Server shows UGFzc3dvcmQ6 - Password> bXlfc2VjdXJlX3Bhc3N3b3Jk <Server shows "Authentication successful"> MAIL FROM: my_email_account@corporation.com RCPT TO: user1@corporation.com DATA [Place your message][ENTER] .[ENTER] With SSL Ok, but what if smtp server uses ssl? Let’s try to send a message using Google mail account. First of all go to and choose Enable IMAP: Enable “less secure apps” at: Addresses of Gmail IMAP and SMTP servers:  Making username and password in base64: $ echo -n my_account@gmail.com | base64 bXlfYWNjb3VudEBnbWFpbC5jb20= $ echo -n my_password | base64 bXlfcGFzc3dvcmQ= For manual connecting to the Gmail smtp server use openssl tool: openssl s_client -starttls smtp -connect smtp.gmail.com:587 -crlf -ign_eof EHLO localhost AUTH LOGIN bXlfYWNjb3VudEBnbWFpbC5jb20= bXlfcGFzc3dvcmQ= MAIL FROM: <my_account@gmail.com> RCPT TO: <my_account@gmail.com> DATA [Place your message, e.g. "123123"][ENTER] .[ENTER] quit Message received: Sending with smtplib Trying to do the the same with smtplib (if your server doesn’t use SSL connection, comment part in is in bold): import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email.encoders import encode_base64 import os login = 'my_account@gmail.com' password = 'my_password' sender = 'my_account@gmail.com' receivers = ['my_account@gmail.com'] msg = MIMEMultipart() msg['From'] = sender msg['To'] = ", ".join(receivers) msg['Subject'] = "Test Message" # Simple text message or HTML TEXT = "Hello everyone,\n" TEXT = TEXT + "\n" TEXT = TEXT + "Important message.\n" TEXT = TEXT + "\n" TEXT = TEXT + "Thanks,\n" TEXT = TEXT + "SMTP Robot" msg.attach(MIMEText(TEXT)) filenames = ["test.txt", "test.jpg"] for file in filenames: part = MIMEBase('application', 'octet-stream') part.set_payload(open(file, 'rb').read()) encode_base64(part) part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file)) msg.attach(part) smtpObj = smtplib.SMTP('smtp.gmail.com:587') smtpObj.ehlo() smtpObj.starttls() smtpObj.login(login, password) smtpObj.sendmail(sender, receivers, msg.as_string()) Note attached files test.jpg and test.txt. Message was received successfully: Receiving messages with easyimap IMAP protocol is much trickier. But you can easily get access to the messages with easyimap library. Iterating by messages: import easyimap login = 'my_account@gmail.com' password = 'my_password' imapper = easyimap.connect('imap.gmail.com', login, password) for mail_id in imapper.listids(limit=100): mail = imapper.mail(mail_id) print(mail.from_addr) print(mail.to) print(mail.cc) print(mail.title) print(mail.body) print(mail.attachments) Output: ... my_account@gmail.com my_account@gmail.com None Test Message Hello everyone, Important message. Thanks, SMTP Robot [('test.txt', '1\n2\n3\n4\n5\n6\n7\n8\n9\n10', 'application/octet-stream'), ('test.jpg', '\xff\xd8\xff\xe0\x00\x10...ff\xd9', 'application/octet-stream')] ... You can save simply save attached data in directory “attachments” this way: for attachment in mail.attachments: f = open("attachments/" + attachment[0], "wb") f.write(attachment[1]) f.close() I hope, that It will be enough for you to start working with email messages in python. >. The best comment i that it shows deeply hidden features that take long time to be discovered. Very helpful. Hi Alexander, I would like to talk to you regarding this personal email project. can we get in touch via Skype. I am from India Please do drop me a mail if interested. i Got this error “imaplib.error: [ALERT] Please log in via your web browser: (Failure) ” As above Description i already Enable IMAP and On allow less secure app but still i got this error. i want to reply to every mail according to subjects with an zip attachment ? now i am able to read mails with an attachment by using IMAP in PYTHOn. HI, I would like to read mails one by one and have to store it in a .txt file. And i also want to search a word from subject or body along with that the mail should be forwarded to specified user. plz try to help me to do this. Pingback: How to make Email Bot service in Python | Alexander V. Leonov hello i tried the above code but the output was in html format ,anyone can tell me how to parse them to plane string Highly appreciated post / article. Much thx
https://avleonov.com/2017/09/14/sending-and-receiving-emails-automatically-in-python/
CC-MAIN-2022-40
refinedweb
990
51.14
Is this thread covering the same ground as ? I don't know DAV well enough to tell. On Sun, Apr 8, 2018, at 10:53 AM, Ken Murchison wrote: > I originally wrote the code to handle public calendars in the "shared" > namespace, but I focused on user calendars first, and public calendar > support got tossed on the back burner. It appears that the code for > public calendars partly works.> > My first thought to get auto-discovery of public calendars is to add > /dav/calendars as a second calendar-home-set for users and see what > the Apple clients do with that. I don't know if they can handle > multiple home-sets. If that doesn't work, then we could map public > calendars into the user's home-set via the same subscription > mechanism that we use for CalDAV sharing.> > To answer the original question, calendars are enumerated by > meth_propfind() and propfind_by_collection() in http_dav.c> > > On 4/7/18 8:25 PM, Bron Gondwana wrote: >> Ken knows this code best. I bet there's something which is requiring >> that there's a user on the mboxname because we implement the same >> behaviour at FastMail by having a separate user on which shared >> resources are kept. The DAV resources are stored per-user, and >> without a place to keep them for "shared calendars" that code might >> just not be accessible. I'm sure it would be possible to create a >> shared DAV database as well for this case, but it just needs some >> programming effort.>> >> Bron. >> >> >> On Sun, 8 Apr 2018, at 07:30, Anatoli wrote: >>> Hi All, >>> >>> I'm trying to understand the code responsible for enumerating user >>> calendars (and xDAV resources in general) to try to make the >>> discovery work for shared resources too (currently there's no way to >>> access shared resources with Apple xDAV client implementation, yes >>> with Thunderbird as it doesn't use the discovery mechanism, but >>> instead should be pointed to the exact URL for each calendar). If I >>> understand it correctly, the functionality is in imap/http_caldav.c.>>> >>> Could you please point me to the place where the enumeration occurs >>> and briefly mention how the general workflow looks like?>>> >>> The client asks for: >>> >>> PROPFIND /dav/calendars/user/<user@domain>/ >>> >>> <A:propfind xmlns: ...>>> >>> The server responds with: >>> >>> HTTP/1.1 207 Multi-Status >>> >>> <A:multistatus>>> Email had 1 attachment: >>> * telemetry.log 36k (text/x-log)>> >> -- >> Bron Gondwana, CEO, FastMail Pty Ltd >> br...@fastmailteam.com >> >> > > > -- Kenneth Murchison Cyrus Development Team FastMail Pty Ltd
https://www.mail-archive.com/cyrus-devel@lists.andrew.cmu.edu/msg04066.html
CC-MAIN-2018-43
refinedweb
417
60.75
Binary behaviors and XML schema As of Windows Internet Explorer 9, XML schemas no longer allow binary behaviors to be imported using namespaces. This affects IE9 standards mode and later document modes. Instead of using HTML markup, use Cascading Style Sheets (CSS)-based registration through the behavior property. You can use CSS-based registration through elements other than the class attribute. A behavior can be specified at the top of a webpage by using HTML markup, as the following code example shows. However, the code above does not work in XML mode. Instead, use the code below inXML mode Related topics Show:
https://msdn.microsoft.com/library/ff986086(v=vs.85)
CC-MAIN-2015-32
refinedweb
102
56.96
Rate. A rate map for a particular grid cell shows the firing rate of the cell as a mapping onto field the animal moves in. Some locations on the field will be preferred by the cell - it is more active whenever the animal is moving within that spatial location. A rate map shows this concept efficiently: The data I'm using to plot is provided freely by the research group of Edvard Moser. Please see their website which has all the information and the data for available for download. Here we use two files, 10704-07070407_POS.mat and 10704-07070407_T2C3.mat from a single trial of their experiment. The first file gives us the locations of the animal at every time point and the second file gives the spike timings for a single cell: from scipy import io as io # from pos = io.loadmat('10704-07070407_POS.mat') spk = io.loadmat('10704-07070407_T2C3.mat') ''' pos["post"]: times at which positions were recorded pos["posx"]: x positions pos["posy"]: y positions --- spk["cellTS"]: spike times ''' With this data we have everything we need to create the rate map. Numpy's histogram2d becomes incredibly useful in this task; we use it twice, first to compute the time spent at every location (occupancy) and then to compute the amount of spikes (activity) recorded at the locations. The rate map is the quotient of the number of spikes by the occupancy. import numpy as np def find_k(array,value): k = (np.abs(array-value)).argmin() return k def rate_map(pos,spk,k=10): bin_edges = np.linspace(-50,50,k) posx = pos["posx"].flatten() posy = pos["posy"].flatten() spkt = spk["cellTS"].flatten() indx = [find_k(pos["post"],t) for t in spkt] indy = [find_k(pos["post"],t) for t in spkt] occup_m = np.histogram2d(posx, posy, bins=(bin_edges,bin_edges))[0] activ_m = np.histogram2d(posx[indx],posy[indy], bins=(bin_edges,bin_edges))[0] # every sampling point accounts for 0.02s spent at loc. rate_map = activ_m/(occup_m*0.02) return rate_map To plot I used the following code - feel free to remove the LaTeX parts if you're missing any of the packages. import pylab as pl def plot_rate_map(im, nlabels=5): from matplotlib import rc rc('text', usetex=True) pl.rcParams['text.latex.preamble'] = [ r'\usepackage{tgheros}', r'\usepackage{sansmath}', r'\sansmath' r'\usepackage{siunitx}', r'\sisetup{detect-all}', ] fig = pl.figure(figsize=(6,4)) pl.imshow(im, interpolation='none') pl.colorbar(label="Hz") pl.xticks(np.linspace(0,len(im),nlabels)-0.5, np.linspace(-50,50,nlabels).astype('int')) pl.yticks(np.linspace(0,len(im),nlabels)-0.5, np.linspace(-50,50,nlabels).astype('int')) return fig Altogether this will give the rate map above. I've put all of this together in a GitHub repository. Happy rate map plotting!
http://felix11h.github.io/blog/grid-cell-rate-maps
CC-MAIN-2018-09
refinedweb
464
50.53
Post your Comment Getting Dom Tree Elements and their Corresponding XML Fragments Getting Dom Tree Elements and their Corresponding XML Fragments... the DOM tree elements and their corresponding XML fragments are displayed... will learn to get the elements of a DOM tree and their corresponding XML Creating DOM Child Elements Creating DOM Child Elements This lesson shows you how to create root and child elements in the DOM tree. We will first create a blank DOM document and add the root element Java DOM Tutorial Tree Elements and their Corresponding XML Fragments In this section, you will learn to get the elements of a DOM tree and their corresponding XML fragments. ... to create root and child elements in the DOM tree. Getting The XML Root Getting all XML Elements elements of the XML file using the DOM APIs. This APIs provides some constructors and methods which helps us to parse the XML file and retrieve all elements... Getting all XML Elements   Creates a New DOM Parse Tree Creates a New DOM Parse Tree This Example describes a method to create a new DOM tree .Methods which are used for making a new DOM parse tree are described below :- Element DOM DOM package name for Document class? Hi Friend, The package is known as dom api. For more information, visit the following links: Thanks DOM Parser Tutorial ; It represents XML document in the form of tree, and it also represent relationship between tree elements. With the help of Dom api, user can add, delete... ). But it is not a part of DOM tree. It is like properties of element. CDATASection XML DOM error - Java Beginners XML DOM error import org.w3c.dom.*; import javax.xml.parsers....("xml Document Contains " + nodes.getLength() + " elements."); } else...); } } } the above program "To Count XML Element" was copied from this website (roseindia.net Dom in java Create XML using DOM import java.io.*; import org.w3c.dom.*; import... elements in your XML file: "); String str = bf.readLine(); int...Dom in java Exception in thread "main" org.w3c.dom.DOMException Creating Blank DOM Document document. Saving the DOM tree to the disk file is also discussed in the next secion... Creating Blank DOM Document This tutorial shows you how to create blank DOM document. JAXP (Java DOM to SAX and SAX to DOM - XML Java DOM to SAX and SAX to DOM Simple API for XML and Document Object Model DOM to SAX and SAX to DOM - XML DOM SAX Parser Java What is the Difference between SAX and DOM parsers Regenerating XML file a xml file and regenerates it at the console using the DOM APIs. This program takes... object and creates a Document object. Through this object you create DOM tree nodes...; In this section, you will learn to get the elements Example of getDocType method in DOM API. parse the xml file using parse() method and create a DOM Tree. Invoke the object...-formed xml file along with a DTD file. This DTD file defines all elements to keep...getDocType() Example in DOM API In this section, we will discuss about To Count The Elements in a XML File To Count The Elements in a XML File  ... in XML document using DOM APIs defined...; and xml-apis.jar files to run this program. You can download it from Java dom from string Java dom from string Hi, How to create dom tree from string data? I am trying to search the example for java dom from string. Thanks  ...://"; String strData = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n dom to xml string dom to xml string Hi, I am writing a program in java that reads... have save the dom document into xml file. How to convert dom to xml string... for converting DOM object into string data. Please check the thread dom to xml again with xml - XML ().removeChild(element); // Normalize the DOM tree to combine all adjacent.../xml/dom/DOMCloneElements.shtml Thanks & Regards Amardeep...again with xml hi all i am a beginner in xml so pls give me DOM importnode, Example of importnode method of document interface. node are recursively imported and the resulting nodes make the corresponding sub tree. The default attributes are not copied from the source document... importNodeExample.java C:\>java importNodeExample <?xml DOM Parser Example to Parse A DOM Document about how to parse(retrieve data) DOM Document. The XML DOM views an XML document as a tree-structure. In this program, we read the XML file and print... to create a DOM object.Get a list of Employee elements from the DOM and count Creating XML Tree Creating XML Tree This Example shows you how to Create an XMLTree in a DOM document. JAXP (Java... an XML Tree:- Element root = doc.createElement("Company" XSD Simple Elements ; XML Schemas define the elements of XML files. XML simple...:boolean xs:date xs:time Example: Few of XML elements... Element? It is an XML element that contains other elements and/or attributes XML Interviews Question page19 XML Interviews Question page19 Why are special attributes used to declare XML... is that the hope that they would simplify the process of moving fragments from one XML Validate DTD file . This DTD file defines all elements to keep in the xml file. After... XML Validate DTD In this section, you will learn to validate a xml file against Tree traversal through the ancestors of these elements in the DOM tree and construct a new jQuery... Tree traversal Tree traversal Tree traversal have following method : .children read xml elements read xml elements i want read xml data using sax parser in java. but is there any classes or methods to read xml elements Post your Comment
http://www.roseindia.net/discussion/18769-Getting-Dom-Tree-Elements-and-their-Corresponding-XML-Fragments.html
CC-MAIN-2015-22
refinedweb
952
65.22
ldap - OpenLDAP Lightweight Directory Access Protocol API OpenLDAP LDAP (libldap, -lldap) #include <ldap.h>) as well as a number of protocol extensions. This API is loosely based upon IETF/LDAPEXT C LDAP API draft specification, a (orphaned) work in progress. The OpenLDAP Software package includes a stand-alone server in slapd(8), various LDAP clients, and an LDAP client library used to provide programmatic access to the LDAP protocol. This man page gives an overview of the LDAP library routines. Both synchronous and asynchronous APIs are provided. Also included are various routines to parse the results returned from these routines. These routines are found in the -lldap library. The basic interaction is as follows. A session handle is created using ldap_initialize(3) and set the protocol version to 3 by calling ldap_set_option(3). The underlying session is established first operation is issued. This would generally be a Start TLS or Bind operation, or a Search operation to read attributes of the Root DSE. A Start TLS operation is performed by calling ldap_start_tls_s(3). A LDAP bind operation connection is terminated by calling ldap_unbind_ext(3). Errors can be interpreted by calling ldap_err2string(3). constructed. displayable. Also provided are various utility routines. The ldap_sort(3) routines are used to sort the entries and values returned via the ldap search routines. A number of interfaces are now considered deprecated. For instance, ldap_add(3) is deprecated in favor of ldap_add. an entry ldap_rename_s(3) synchronously rename ldap.conf(5), slapd(8), draft-ietf-ldapext-ldap-c-api- xx.txt <>.
http://huge-man-linux.net/man3/ldap.html
CC-MAIN-2017-13
refinedweb
255
51.75
Dear to get live market data. Yahoo offers extensive market data through a SQL based interface, which they call YQL (Yahoo Query Language). UPDATE: Unfortunately Yahoo stopped the service after 9 years in late 2017 claiming it is violating their terms of services. I am currently migrating my code examples to iextrading instead. Fig.1: Example usage of YQL with my custom tiles in combination with UI5 NumberContent MicroCharts and others Generally speaking my custom tile type extends the standard Fiori dynamic tile exposing its content to the tile configuration screen. In order to be able to consume web services which are not within your domain I configured the AJAX calls to use jsonp. You can add any UI5 content that fits the tile’s space. Just browse SAPUI5 explored and check the underlying XML-View code. Wrap that XML-snippet in a UI5 fragment-tag defining the necessary namespaces (e.g xmlns=”sap.suite.ui.microchart”) and you are good to go. The service callback is added to a JSONModel so that you can use UI5 templates to feed the values into your custom tile dynamically during runtime. All examples used on the website use the yahoo finance API but you are not limited to that. The custom tile ships with two shapes. The standard tile, which is a square (1×1) and the second option, which is a wide rectangle (2×1). For the latter you also get to choose if you want two columns for your visuals or one wide one. The tiles adapt slightly on mobile devices in total size to save space. Fig.1: Another two by one tile example with YQL showing a wide chart To finally use my component in your system, you need to register it as a “chip”. Directions on how to do this can be found on my GitHub page or on the link mentioned before. According to the SAP Fiori community you can achieve a similar solution as of HANA SP09 with the standard Custom App Launcher tile type. However my solution does not involve programming object deployment or a HANA platform at all. Reading from external source due to the lack of jsonp would also be a problem with the custom app launcher. So if you want to keep it simple, be as flexible on how you visualize web service data as possible and read data from where ever you want to, my tile type is the way to go. Check out my GitHub page for installation hints and further documentation especially regarding the possible configurations. Also I would like to thank David Garcia for lending me one of his many hands to get this up and running in no time. You are the best David! As usual feel free to leave comments and ask lots of follow up questions. Yours Martin The following links could also be of interest to you: - - - My custom tile was inspired by this GitHub project. Hi Martin, thank you for sharing, great post! regards Gunter Really cool. Helped me a lot in developing nice tiles. Thanks for your effort, Klaus You are very welcome Klaus. I am trying to use On-Premise-oData-Services. But the path-binding that I am using does not work. http://<host>:<port>/sap/opu/odata/sap/ZUSERINFO_SRV/UserCollection/?$format=json “d” : { “results” : [ { “__metadata” : { “id” : “http://<host>:<port>/sap/opu/odata/sap/ZUSERINFO_SRV/UserCollection(‘Klaus’)”, “uri” : “http://<host>:<port>/sap/opu/odata/sap/ZUSERINFO_SRV/UserCollection(‘Klaus’)”, “type” : “ZUSERINFO_SRV.User” }, “UserID” : “Klaus”, “FirstName” : “REINER”, “LastName” : “KLAUS”, “Percentage” : “12”, “Country” : “FR” } ] } } <RadialMicroChart percentage=”{path:’/d/results/0/Percentage’, formatter:’.formatValueShortNumber’}” valueColor=”#0080ff” /> </core:FragmentDefinition> What would be the correct path information from your point of view? Regards, Klaus Hi Klaus, I updated the component in January regarding on-premise OData calls. Are you on the latest version already? In order to update please run /UI2/INVALIDATE_CLIENT_CACHES on SE38 to refresh after chip deployment. Your model path looks correct. Apart from that the formatter function in your example will not do anything for percentages due to its inherent number range (-100 / +100). You might want to think about applying a formatter for the valueColor though. My standard function formatIntValueColor follows the most straighforward approach for most cases by coloring negative in red, zero in grey and positive numbers in green. Feel free to add a function of your own by copying mine. Let me know how it goes. Kind regards Martin Hi Martin, to ensure that I am using the newest version, I just copied your GIT-Repository again into my WebIDE after deleting the old ones and then deployed them into a completely new BSP-Application with separate CHIP. Additionally I have executed the ABAP report you mentioned. However I still can not see any results. As long as I do not set the path for binding, everything looks good. Is the way the oData-WebService-URL has been defined, look good from your point of view? If not can you maybe provide an example with a generic service, e. g. the GWDEMO Service of SAP, available on every On-Premise-System? Thanks in advance. Kind regards, Klaus Hi Klaus, So you are on the current version. Let’s rule out some more potential problems. I checked your example xml and got encoding errors while pasting the copied content. But since you say the radial chart shows up without the service I believe this happens only on my end. Another problem could be your URL. Browser prohibit calling data from other servers than the one hosting the calling website. There are a lot of ways to implement this nevertheless. You need to be calling an OData service on the gateway, which also hosts the app. If not you need to take that into account. Maybe even apply a relative url to be absolutely sure (e.g. /sap/opu/odata/sap/ZUSERINFO_SRV/UserCollection/?$format=json). Also make sure the model path leads to a number and the formatter creates output as expected by the chart. I tested your example with one of my custom odata services successfully. Let me know how it goes. Kind regards Martin Hi Martin, that just worked perfectly 🙂 I have now used a relative path and not an absolute one (full-qualified with host and port). Additionally I have created a second oData-Service with an additional INT4-field instead of trying to format strings to a numeric value. After integrating both into my custom tile definition I was able to use the data of my service in footer/subtitle as well as in the microchart as data series. Thanks you so much for your great support and this really cool development! Klaus You are welcome Klaus. It is nice to hear you like it. Hi Martin, I am trying to get rid of the namespace. This is because with the namespaces the files paths seem to be too long, so that if you are deploying the application to a Netweaver system as BSP, the file paths that are too long are getting mapped in the file UI5RepositoryPathMapping.xml. Within that xml, the files that have a too long file path are getting a technical ID mapped to the correct filename. I want to get rid of that to not always have to lookup, which file is which one, because this is laborious when working on the application. To achieve this, I have exported the application and then replaced all occurrences of convista.com.demo. and convista/com/demo/ in all files with ”(nothing) and reimported (download and upload both with report /UI5/UI5_REPOSITORY_LOAD) the application under a new BSP-ID. After doing the CHIP-Customizing and creating the new tile, I am able to do the generic tile customizing. But when adding the tile to the Fiori-Launchpad, no data is getting displayed at all, so something seems to be wrong, although I have doublechecked all occurences of the namespace in all files. So what needs to be done in addition, to have a shorter path / no namespace at all? Thanks, Klaus Hi Klaus, The namespace is tied to the whole project structure, so you need to check also the configuration files in addition to the ui5 stuff. It is possible that there is a namespace validation in place that requires at least three parts like sap.demo.com etc. I couldn’t find the reference to back up my claim, though. Let me add that I never had any path problems using relative urls. Kind regards Martin Hi Martin, thanks for that hint. I have tried the following: Downloaded the application and Uploaded it again with a new BSP-ID. Just to test and to ensure that a downloaded and uploaded application still works. And it did. Then I have changed the downloaded BSP: – renamed the folder “convista” to “p” (to get it as short as possible) – replaced “convista” in all files with “p” wherever this string occurred Then uploaded the application again under a new BSP-ID. Unfortunately this does not work, although I have made a minimum adjustment for namespace. Any idea? Kind regards, Klaus Not specifically no. I can only suspect that there is still some file looking for another name. Did you check your browser’s developer tools? All browsers show network calls as well as Javascript errors on the console tab. Have a look in there to pinpoint the problem better. Maybe consider creating a new project with your desired namespace on WebIDE and copying the relevent code pieces to avoid nameing mistakes. Kind regards Martin
https://blogs.sap.com/2017/04/03/get-yourself-some-live-market-data-with-ui5-visuals-on-your-fiori-tiles/
CC-MAIN-2018-43
refinedweb
1,597
64.3
ok so i got a question... again lol big suprise ok so heres the code i got so far ok... the next part i have NO idea how to go about....ok... the next part i have NO idea how to go about....Code://Written By : Andrew Bomstad //"Day6" #include<iostream> #include<ctype.h> #define cls system("cls"); #define pause system("pause"); using namespace std; int main() { int input; cout << "enter a digit" << endl; cin>>input; cout<<cin; pause; if(cin){ cls; cout << "You Entered The Number: " << input<<endl; pause; cls; main(); } else{ cls; cout << "Error! Must Enter A Number" << endl; pause; main();} pause; main(); } i want a way to send a error message out, if the user inputs more than one input... like say if they type "3hgh" or somthing i want an error message so im thinkin... do i need to check the keyboard buffer to see how much input was enterd and then do somthing bout that? i dont know really im confused with it all lol anyhelp would be great guys o yeah... im also looking for a way to get out of the Infinite loop you'll get if you hit a "Char" in my program. lol i tried clearing the buffer before sending it back to main.. but it just keeps erroring
https://cboard.cprogramming.com/cplusplus-programming/64291-checking-input-buffer.html
CC-MAIN-2017-09
refinedweb
218
80.82
- Author: - ekellner - Posted: - August 28, 2008 - Language: - Python - Version: - .96 - admin field widget readonly modelchoicefield - Score: - 6 (after 6 ratings) This replaces the html select box for a foreign key field with a link to that object's own admin page. The foreign key field (obviously) is readonly. This is shamelessly based upon the Readonly admin fields snippet. However, that snippet didn't work for me with ForeignKey fields. from foo.bar import ModelLinkAdminFields class MyModelAdmin(ModelLinkAdminFields, admin.ModelAdmin): modellink = ('field1', 'field2',) More like this - autocompleter with database query by bbolli 7 years, 7 months ago - Javascript Chain Select Widget by ogo 6 years, 9 months ago - Select or Create widget by Naster 12 months ago - Querying on existence of a relationship by ubernostrum 7 years, 6 months ago - Readonly Select Widget Replacement by colinkingswood 2 months, 2 weeks ago I'd put "self.original_object.pk" instead of "self.original_object.id" as sometimes you have primary key named differently than "id" # This worked for me, except when I wanted to add a new item in the admin containing the field in question (I was using it to show ID fields). The fix (for me) was to modify line 13 to read: now it no longer throws the error for me. # I was getting errors when there was a null value in a foreign key (pointing to User). Changing some lines in ModelLinkAdminFields fixed it: I am not sure this is the best only way, and only fields that had been filled in by django-evolution caused problems, so this probably will not affect everyone. # Please login first before commenting.
https://djangosnippets.org/snippets/1008/
CC-MAIN-2015-11
refinedweb
269
59.84
On Tue, May 20, 2014 at 1:37 PM, Ronnie Sahlberg <sahlb...@google.com> wrote: > On Tue, May 20, 2014 at 12:42 PM, Jonathan Nieder <jrnie...@gmail.com> wrote: >> Ronnie Sahlberg wrote: >> >>> Wrap all the ref updates inside a transaction to make the update atomic. >> >> Interesting. >> >> [...] >>> --- a/builtin/receive-pack.c >>> +++ b/builtin/receive-pack.c >>> @@ -46,6 +46,8 @@ static void *head_name_to_free; >>> static int sent_capabilities; >>> static int shallow_update; >>> static const char *alt_shallow_file; >>> +static struct strbuf err = STRBUF_INIT; >> >> I think it would be cleaner for err to be local. It isn't used for >> communication between functions. > > Done. > >> >> [...] >>> @@ -580,15 +581,9 @@ static const char *update(struct command *cmd, struct >>> shallow_info *si) >>> update_shallow_ref(cmd, si)) >>> return "shallow error"; >>> >>> - lock = lock_any_ref_for_update(namespaced_name, old_sha1, >>> - 0, NULL); >>> - if (!lock) { >>> - rp_error("failed to lock %s", name); >>> - return "failed to lock"; >>> - } >>> - if (write_ref_sha1(lock, new_sha1, "push")) { >>> - return "failed to write"; /* error() already called */ >>> - } >>> + if (ref_transaction_update(transaction, namespaced_name, >>> + new_sha1, old_sha1, 0, 1, &err)) >>> + return "failed to update"; >> >> The original used rp_error to send an error message immediately via >> sideband. This drops that --- intended? > > Oops. I misread it as a normal error() > >> >> The old error string shown on the push status line was was "failed to >> lock" or "failed to write" which makes it clear that the cause is >> contention or database problems or filesystem problems, respectively. >> After this change it would say "failed to update" which is about as >> clear as "failed". > > I changed it to return xstrdup(err.buf) which should be as detailed as > we can get. > >> >> Would it be safe to send err.buf as-is over the wire, or does it >> contain information or formatting that wouldn't be suitable for the >> client? (I haven't thought this through completely yet.) Is there >> some easy way to distinguish between failure to lock and failure to >> write? Or is there some one-size-fits-all error for this case? > > I think err.buf is what we want. > >> >> When the transaction fails, we need to make sure that all ref updates >> emit 'ng' and not 'ok' in receive-pack.c::report (see the example at >> the end of Documentation/technical/pack-protocol.txt for what this >> means). What error string should they use? Is there some way to make >> it clear to the user which ref was the culprit? >> >> What should happen when checks outside the ref transaction system >> cause a ref update to fail? I'm thinking of >> >> * per-ref 'update' hook (see githooks(5)) >> * fast-forward check >> * ref creation/deletion checks >> * attempt to push to the currently checked out branch >> >> I think the natural thing to do would be to put each ref update in its >> own transaction to start so the semantics do not change right away. >> If there are obvious answers to all these questions, then a separate >> patch could combine all these into a single transaction; or if there >> are no obvious answers, we could make the single-transaction-per-push >> semantics optional (using a configuration variable or protocol >> capability or something) to make it possible to experiment. > > I changed it to use one transaction per ref for now. > > Please see the update ref-transactions branch. I have added support for atomic pushes towards the end of the -next series. It is activated by a new --atomic-push argument to send-pack and is then negotiated by a new option in the wire protocol. > > Thanks! -- To unsubscribe from this list: send the line "unsubscribe git" in the body of a message to majord...@vger.kernel.org More majordomo info at
https://www.mail-archive.com/git@vger.kernel.org/msg51401.html
CC-MAIN-2017-43
refinedweb
592
63.49
Red Hat Bugzilla – Bug 11349 Building rpm-3.0.4 with Berkeley db-3.0.55 from sleepycat.com Last modified: 2008-05-01 11:37:55 EDT I foolishly thought that I could compile Berkeley db-3.0.55 from sleepycat.com with db-185 compatibility under Solaris 2.7 for use with rpm-3.0.4. In order to do this, I had to patch configure.in to look for a new function name and patch lib/dbindex.h to define a macro to enable the db-185 feature for db-3.0.55. With the following patch, rpm-3.0.4 builds and links against db-3.0.55 using gcc-2.95.2. Unforutnately, a bug in db-3.0.55 (which I did not care to track down) prevented me from using it, so I switched back to db-2.7.7. I hope this patch will be useful. diff -u rpm-3.0.4/configure.in.orig rpm-3.0.4/configure.in --- rpm-3.0.4/configure.in.orig Wed Mar 15 06:29:09 2000 +++ rpm-3.0.4/configure.in Thu Apr 13 11:40:55 2000 @@ -311,7 +311,8 @@ AC_CHECK_FUNC(dbopen, [], AC_CHECK_LIB(db1, dbopen, [LIBS="$LIBS -ldb1"], AC_CHECK_LIB(db, dbopen, [LIBS="$LIBS -ldb"], - AC_MSG_ERROR([sorry rpm requires a db-1.85 API]))) + AC_CHECK_LIB(db, __db185_open, [LIBS="$LIBS -ldb"], + AC_MSG_ERROR([sorry rpm requires a db-1.85 API])))) ) AC_CHECK_FUNC(fork, [], [echo "using vfork() instead of fork()"; diff -u rpm-3.0.4/lib/dbindex.h.orig rpm-3.0.4/lib/dbindex.h --- rpm-3.0.4/lib/dbindex.h.orig Wed Oct 20 16:40:10 1999 +++ rpm-3.0.4/lib/dbindex.h Thu Apr 13 15:25:26 2000 @@ -5,6 +5,7 @@ #include <db1/db.h> #else #ifdef HAVE_DB_185_H +#define DB_LIBRARY_COMPATIBILITY_API #include <db_185.h> #else #include <db.h> There's an alignment patch from sleepycat that you will need as well. That patch is also in the db3-3.0.55-xx package, available from Raw Hide, but you will almost certainly have to dink with paths etc, as we (Red Hat) are currently betwixt and between db2 and db3 (and glibc-2.1.x glibc-2.2, and ...) There's also a portability problem with solaris bsearch that you will need to apply to rpm-3.0.4 sources. The patch is in lib/depends.c alFileSatisfiesDepend(struct availableList * al, const char * keyType, const char * fileName) { int i; const char * dirName; const char * baseName; struct dirInfo dirNeedle; struct dirInfo * dirMatch; if (al->numDirs == 0) /* Solaris 2.6 bsearch sucks down on this. */ return NULL; Hope this helps. Send mail to <jbj@redhat.com> if you have questions.
https://bugzilla.redhat.com/show_bug.cgi?id=11349
CC-MAIN-2017-39
refinedweb
452
70.9
SeeBorg project is a C++ IRC chatbot.SeeBorg is a C++ version of PyBorg, the IRC chatbot. It was written completely from scratch and uses the botnet library for IRC interaction.SeeBorg is a random phrase bot that will sit on IRC channel, learning the talk, and periodically replying with something that is generated from the talk learned before. It doesn't make much sense at all, but sometimes it's at least funny. There are some configuration options that will make you able to tweak some of the bot's behaviour. Also if you set yourself as an owner, you will have access to IRC trigger commands (beginning with '!'). At the first stages of development, I was porting PyBorg's learn and reply algorithm. When I finally finished it, I did the first launch to test it by talking. Here's the log of my first launch of the bot (I was using my old PyBorg's dictionary, which is quite huge):What's New in This Release:· Version 0.51 is a bugfix re-release of 0.5 - irc module was incorrectly forcing locale to be "ru_RU.CP1251".· Catch duplicate channels in config· Makefile works now on mingw32 w/msys (and should on cygwin)· Added Dev-C++ projects (visual-mingw will follow)· Cleanup of source code, std namespace is now default· Bugfix: Extra whitespace in front of realname (botnet's bug)· New IRC trigger: !save - saves the dictionary and settings· Configuration settings are now with commented descriptions· If there are no owners, don't react to IRC triggers at allProduct's homepage
http://linux.softpedia.com/get/Communications/Chat/SeeBorg-20117.shtml
crawl-003
refinedweb
264
62.27
Content-type: text/html #include <sys/stream.h> void freemsg(mblk_t *mp); Architecture independent level 1 (DDI/DKI). mp Pointer to the message blocks to be deallocated. mblk_t is an instance of the msgb(9S) structure. If mp is NULL, freemsg() immediately returns. The freemsg() function calls freeb(9F) to free all message and data blocks associated with the message pointed to by mp. The freemsg() function can be called from user, interrupt, or kernel context. Example 1: Using freemsg() See copymsg(9F). copymsg(9F), freeb(9F), msgb(9S) Writing Device Drivers STREAMS Programming Guide The behavior of freemsg() when passed a NULL pointer is Solaris-specific.
http://backdrift.org/man/SunOS-5.10/man9f/freemsg.9f.html
CC-MAIN-2017-04
refinedweb
107
52.46
To my surprise and disappointment, popular scientific libraries like Boost or GSL provide no native support for parallel random number generation. Recently I came across TRNG, an excellent random number generation library for C++ built specifically with parallel architectures in mind. Over the last few days I’ve been trawling internet forums and reading discussions about the best parallel random number generation libraries. Given the trend in CPU architectures whereby each contains an ever increasing number of cores, it makes sense to start a project by considering what libraries are available to best make use of this technology. The first libraries I came across were RngStream and SPRNG. It seems SPRNG was built specifically with MPI, i.e. for distributed memory architectures, in mind and there are some excellent examples and resources of how to get started with parallel MCMC on Darren Wilkinson’s blog. As a result, it seems a bit contrived to get SPRNG to work with OpenMP, i.e. for shared memory architectures. Moreover, I specifically wanted to use OpenMP because I wanted to write an extension for R for use on personal computers. RngStream is written by the man himself, Pierre L’Ecuyer, and is much more OpenMP amenable. Both of these, however, only generate uniform pseudo random numbers. This isn’t a fault, but it means you need to code up transformations and samplers to generate non-uniform pseudo random numbers. While this would be a good exercise, life is short, and I’d rather leave this sort of thing to the professionals (I don’t want to code up my own Ziggurat algorithm). Also, the generators or engines are of defined types and I found it hard to convert them into the corresponding types of other libraries like Boost or GSL so that I could use their non-uniform generation code. That probably says more about my ability rather than the actual difficulty of the problem and Darren Wilkinson provides some of his own code for getting the RNG engine of SPRNG into the correct datatype to be compatible with GSL. TRNG At this point I was quite discouraged but then I came across TRNG, written by Heiko Bauke. At first glance TRNG is an excellently documented C++ PRNG (which stands for pseudo random number generator, not parallel, that would be PPRNG) library built specifically with parallel architectures in mind. Not only does it provide non-uniform distributions, but it can be used easily with MPI, OpenMP, CUDA and TBB, for which many examples are supplied. The documentation is excellent and the many examples of the same problem coded with each of the aforementioned parallelization methods are enlightening. If that weren’t enough, TRNG can be used in combination and interchangeably with the Boost random as well as the C++11 TR1 random libraries, that is, the engines/generators from TRNG can be used with the distribution functions of Boost and C++11 TR1, which was a problem I encountered with RngStream and SPRNG. The way TRNG and RngStream work are slightly different. Whereas RngStream generates multiple independent streams, TRNG uses a single stream and either divides it into blocks, or interleaves it between different processors by a leap-frog type scheme, much like dealing out cards round a table. The point of all this is that the streams of different processors never overlap, otherwise one would get the same draws on processor A as processor B. While purists might argue that L’Ecuyer’s method is more rigorous, I’m happy enough with the way Heiko has done it, especially given TRNG’s out-of-box easy of use and compatibility. Installation of TRNG Clone the repository off Github. trng4]# the “–prefix=” argument just sets where I want the files to be installed and is not necessary. If omitted the default case is /usr/local. After make install, run ldconfig as root in order to update the dynamic linker/loader with the presence of the new library. Basically there exists a cache /etc/ld.so.cache which is used by the dynamic linker/loader at run-time as a cross-reference for a library’s soname with its full file path. ldconfig is normally run during booting but can also be run anytime to update the cache with the locations of new libraries. Here is what happens if you don’t run ldconfig, as I did the first time. > int main() { int max=omp_get_max_threads(); omp_set_num_threads(max); int rank; trng::yarn2 gen[max]; trng::uniform01_dist<> u; std::cout << max << " =max num of threads" << std::endl; for (int i = 0; i < max; i++) { gen[i].split(max,i); } #pragma omp parallel for private(rank) for (int i = 0; i < max; ++i) { rank=omp_get_thread_num(); #pragma omp critical std::cout << u(gen[rank]) << " from thread " << rank << std::endl; } return EXIT_SUCCESS; } which returns ~]$ The salient feature of this code is the leapfrog process by calling split. There exists a sequence of random uniforms and “.split(max,i)” divides it into max subsequences, leap-frogging each other, and grab the i’th subsequence. You can think of this as max players sitting around a poker table and the .split() as continuously dealing out random uniforms to each of the players. The code says let processor i be “player” i and use the sequence of random uniforms dealt to it. Parallel Random Number Generation in R using Rcpp Thanks to Rcpp the above C++ code can be trivially changed so that it can be used from R. Just include the Rcpp header and change the function return type. #include <cstdlib> #include <iostream> #include <omp.h> #include <trng/yarn2.hpp> #include <trng/uniform01_dist.hpp> #include <Rcpp.h> // [[Rcpp::export]] Rcpp::NumericVector prunif(int n) { int max=omp_get_max_threads(); omp_set_num_threads(max); int rank; trng::yarn2 gen[max]; trng::uniform01_dist<> u; Rcpp::NumericVector draws(n); for (int i = 0; i < max; i++) { gen[i].split(max,i); } #pragma omp parallel for private(rank) for (int i = 0; i < n; ++i) { rank=omp_get_thread_num(); draws[i]=u(gen[rank]); } return draws; } This code can be compiled and loaded into R on the fly, so lets test it. Speedup Performance > library(Rcpp) > library(rbenchmark) > Sys.setenv("PKG_CXXFLAGS"="-fopenmp") > Sys.setenv("PKG_LIBS"="-ltrng4") > sourceCpp("prunif.cpp") > benchmark(replications=rep(100,0,1),runif(1000000),prunif(1000000)) test replications elapsed relative user.self sys.self user.child 2 prunif(1e+06) 100 0.611 1.00 2.227 0.114 0 1 runif(1e+06) 100 3.837 6.28 3.745 0.086 0 There are a few things to note. Spawning threads incurs its own overhead, so it will obviously be slower for very few draws. As the number of draws becomes larger the time taken to spawn new threads is dwarfed by the time taken to create the draws and so it is worthwhile to do it in parallel. One caveat is that prunif and runif did not in this case use the same generating algorithm. R’s algorithm can be changed with RNG.kind and the TRNG algorithm can be changed by using an alternative to yarn in “trng::yarn2″. Even if they were the same though I would expect the same qualitative behaviour. Discussion Generating large samples of random numbers in one hit quickly is not the reason why I started looking for a good parallel random number generator. Rarely is it important to me to generate large amount of draws in one go but it certainly is important to me to have independent streams. Generally I will port expensive parts of my R code, usually for loops, to C++ and inevitably I will somewhere within these for loops or other expensive parts of code need to draw some random numbers. Since these expensive pieces of code are self-evidently expensive, I will want to compute them in parallel in C++ if I can and so it is very important to me to have independent streams from which to draw random numbers. The post Parallel Random Number Generation using TRNG appeared first on Lindons...
http://www.r-bloggers.com/parallel-random-number-generation-using-trng/
CC-MAIN-2014-42
refinedweb
1,340
60.55
CKS Exam Prep: Setting up Audit Policy in Kubeadm The second part of my CKS series will cover how to enable Audit policy logging for a Kubernetes cluster deployed with Kubeadm. The reference article is here Audit logging (also known as audit trail) refers to the practice of recording events and changes to a system; in the context of Kubernetes security, it’s a security feature of the API server that will record every (or a subset of your choice) actions and interactions of users with the cluster. As the API server is the only way to interact with the cluster, that makes it a primary target for attackers and naturally the most important service to monitor and secure. You can configure what you’re going to log by creating an object of type Policy: cat > /etc/kubernetes/audit-policy.yaml <<EOF # Log all requests at the Metadata level. apiVersion: audit.k8s.io/v1 kind: Policy rules: - level: Metadata EOF There are four available levels to log every single event/resource granular. It’s easier to refer to the docs to understand how to specify the level per resource audited; during the CKS exam, you’ll be able to access this document (just search for “Audit” in). The file in itself is not going to do much until we instruct the API server to use it. In most clusters the API server is configured as a static pod whose configuration lives in /etc/kubernetes/manifests/kube-apiserver.yaml ; not only we will need to modify the flags of the actual command that starts the API server, but we need to make sure that the server itself can find the policy file we just created, using the pair volumes/volumeMounts: Note also the options to configure the audit log file, retention (in days) and the maximum size of the audit log (in Mb). Bonus: troubleshoot misconfigured API-server static pod It might happen that due to a typo in editing the static pod definition the api-server won’t come and you’ll be cut off the cluster. Don’t panic! It happens and it’s not difficult to recover. First: make a backup of the file before editing. This is really important! Second: since it’s the kubelet process that monitors the folder /etc/kubernetes/manifests for changes, look into its logs: journalctl -u kubelet -f I often restart the kubelet process before looking at the logs to avoid syphoning thru thousands of lines: systemctl restart kubelet Remember that since 1.19 containerd is the standard container runtime for Kubernetes, so you won’t have your familiar docker command line, instead, you can use ctr : ctr -n k8s.io c list | grep api where k8s.io is the namespace where all the Kubernetes containers are running. I hope it helps! Check out other articles in the CKS series here
https://medium.com/cooking-with-azure/cks-exam-prep-setting-up-audit-policy-in-kubeadm-3f1b76bf4bd7?source=collection_home---6------1-----------------------
CC-MAIN-2021-43
refinedweb
479
57.2
I often check in Start()-method, if all needed references are set in inspector. So i wrote a utility method, for this like this: public static void WarnIfNull(object o, string name) { if (o == null) { Debug.LogWarning(name + " is NULL"); ... so i can use it in component init code like this: public class MyComponent : MonoBehavior { public AudioClip sound; void Start() { MyLogUtils.WarnIfNull(sound, "sound"); ... Nothing special, interesting so far... But it does not work. Assuming i forgot to assign reference in inspector. If i null-check inside of MyComponent.Start(), null check works correct. But if doing exact same null-check inside of MyLogUtils.WarnIfNull(), null check is FALSE. I can not explain this, it is really weird. So i tryied to debug it, if object is not null, then what is it? (it was never assigned). I can cast it to AudioClip like this if (o is AudioClip) { AudioClip a = (AudioClip) o; // this works } but if i call any method/property from this object like this: var a_name = a.name; a_name.ToString(); i am getting UnassignedReferenceException. I know, it sounds strange, that null-check of same object in call-stack behaves not same. But is looks like this. I do not really understand what is the reason for that. Docs for UnassignedReferenceException somehow do not explain it. So my missing-reference method looks like this now: public static void WarnIfNull(object o, string name) { bool unassigned = false; if (o is AudioClip) { try { AudioClip a = (AudioClip) o; var a_name = a.name; a_name.ToString(); } catch (UnassignedReferenceException e) { unassigned = true; } } if (o == null || unassigned) { Warn(name + " is NULL (unassigned in inspector, but somehow can be not null)"); } } Any suggestions explanations are welcome. So, my question: Why the same reference is null in one methode and not null in another. I just pass it by reference but, null-check result ist different. Is this some special UnityEditor stuff i should know? Have you tried changing the signature of your utility function to: public static void WarnIfNull(UnityEngine.Object o, string name) Answer by Vencarii · Feb 27, 2018 at 01:45 PM So you don't get any error when you use MyLogUtils.WarnIfNull(sound, "sound"); in Start()? My guess would be that MyLogUtils isn't there in your Start() method, maybe? So you don't get any error when So you don't get any error when Answer by maltakereuz · Feb 28, 2018 at 04:52 AM. Animation Error "Null reference exception"? 2 Answers c# 2D array error: need Help! 1 Answer Resources.Load texture problem 1 Answer Fresh installed , with problems 0 Answers Passing information error 0 Answers
https://answers.unity.com/questions/1474141/unassignedreferenceexception-and-null-check.html
CC-MAIN-2020-05
refinedweb
436
67.86
Welcome to part 8 of my C Video Tutorial. In this video I cover a topic I have received many requests for. This is basically a C Malloc Tutorial. Malloc() ( Memory Allocator ) is used to dynamically set aside memory at run time. Because malloc() returns a pointer to that location in memory it can be a bit confusing. I’ll cover how to store both regular data types as well as structs using malloc(). If you like videos like this, it helps to tell Google+ with a click here [googleplusone] Code From the Video CTutorial8_1.c #include <stdio.h> #include <stdlib.h> // When you define an int, float, or array, you define exactly how // much memory you need and that is all you can get at run time // using traditional data types. // If you need to allocate memory as a program runs you need // malloc() // When malloc() is called you pass it the amount of memory required and // it returns the address to that memory that you can refer to using // a pointer. If the space couldn't be found null is returned. int main(){ int amtOfNumbersToStore; printf("How many numbers do you want to store: "); scanf("%d", &amtOfNumbersToStore); // Create an int pointer and set aside enough space to hold the ints // required. // pRandomNumbers points to just the first element, but it can // access the others. // The typecast (int *) isn't required in C, but is in C++ int * pRandomNumbers; pRandomNumbers = (int *) malloc(amtOfNumbersToStore * sizeof(int)); // Check if memory was located by malloc if(pRandomNumbers != NULL){ int i = 0; printf("Enter a Number or Quit: "); // Receives ints until the memory allocated is full, or // until a non int is entered // You store values by referring to the pointer using // array notation while(i < amtOfNumbersToStore && scanf("%d", &pRandomNumbers[i]) == 1){ printf("Enter a Number or Quit: "); i++; } printf("\nYou entered the following numbers\n"); // for(int j = 0; j < i; j++){ printf("%d\n", pRandomNumbers[j]); } } // Make sure you give back the memory allocated by malloc // when you are finished with it. free(pRandomNumbers); // In this program free() isn't required because all allocated // memory is returned to the system when the program terminates. // free() would be required though if you were allocating large // blocks of memory over and over without returning it. // Let's say you store 10k of data using malloc, use it and have // no further use for it but don't use free. // Then you grab another 10k over and over. Eventually you'll // run out of memory and get a memory leak. return 0; } CTutorial8_2.c #include <stdio.h> #include <stdlib.h> // struct that holds product information struct product { float price; char productName[30]; }; int main(){ // Pointer to a struct struct product *pProducts; int i, j; int numberOfProducts; printf("Enter the Number of Products to Store: "); // Dynamically we are defining how much space we need at run time scanf("%d",&numberOfProducts); // Allocates the memory required to store the structs // Type casting isn't needed for C, but is required for C++ pProducts = (struct product *) malloc(numberOfProducts * sizeof(struct product)); for(i=0; i < numberOfProducts; ++i){ printf("Enter Product Name: "); // This time I use pointer arithmetic to cycle through the data // and print it out scanf("%s", &(pProducts+i)->productName); printf("Enter Product Price: "); scanf("%f", &(pProducts+i)->price); } printf("Products Stored\n"); for(j=0; j < numberOfProducts; ++j){ printf("%s\t%.2f\n", (pProducts+j)->productName, (pProducts+j)->price); } free(pProducts); return 0; } Pretty sweet videos, brother. My favourite text editor is Sublime Text 2. I know hardcore people that have dropped Emacs or Vim for Sublime so it’s definitely worth taking a look at! Keep up the good work! Many thanks from South Africa! Thank you 🙂 I’m amazed by how popular I am in South Africa. That is very cool! I’ll have to check out Sublime Text. It looks very nice. derek, your tutorial is a bit fast for starter but they are great! Thank you 🙂 Yes I like to make videos unlike what else is out there. I’m the fast tutorial guy I guess.
http://www.newthinktank.com/2013/08/c-video-tutorial-8/?replytocom=20867
CC-MAIN-2021-04
refinedweb
684
62.88