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
|
|---|---|---|---|---|---|
Activities/Pilas
This page is based on documents translated from Spanish. Your help improving the translation would be very welcome :)
Go to Pilas Activity page in Spanish.
Contents
About the Pilas.xo Project
Pilas is an engine for making videogames in an easy way. It's oriented to people that are learning to code videogames and that want to achive interesting and fun result very quickly.
This project brings the Pilas game development engine to Sugar, adapting it to the needs of the Sugar platform and adding elements to your learning curve. We seek to facilitate a teaching tool for Python and game development.
This project was developed during Sugar Day Junin 2011
Links to the project
- Pilas: [1]
- Activity.xo [2]
- Code [3]
- Issues tracker [4]
- Name of branch 'pilasqt'. Command to take to the branch:
hg clone cd pilas/ hg update pilasqt
Getting Started
The Activity starts with the game engine initialised and a monkey (mono) preloaded. The monkey is displayed in the upper pane and the lower pane executes Python code in immediate mode
The following Pilas commands can be entered :
mono.sonreir() //monkey smile mono.gritar() //monkey shout mono.decir("Hello World!") mono.x = 100 mono.y = 100 mono.z = 1 //depth or drawing order mono.escala = 2 //set scale mono.rotacion = 40 //rotate 40 degrees mono.rotacion = [360] // the [] means animate mono.x = [-200, 200] //animate horizontally mono.x = [-200, 200] * 5 //go side to side 5 times mono.x = [-200, 200], 10 //animate over 10 seconds help(mono) pilas.ver(mono) //view source mono.eliminar() //delete monkey mono = pilas.actores.Mono() //create a monkey instance pilas.iniciar() //initialise the game engine pilas.iniciar(gravedad=(0, 0)) //initialise and set gravity //with pilas.actores you can create: //Mono Bomba Pingu Pelota Banana Monkey Bomb Penguin Ball Banana //Caja Tortuga Moneda Estrella Box Turtle Money Star //Nave Piedra Plane Rock pilas.ejemplos.Piezas () //starts a demonstration game
There is much more, read the Spanish documentation. [5]
Status
What has been done:
- Packaging the pilas-engine [6] to run on Sugar.
- Incorporation of PyQt libraries [7] into the activity
- Adding widget ninja-ide [8] , to have the interactive shell on the same screen.
- Generation of file dependencies needed for the project with PyInstaller [9]
- Creating the pilas.xo activity
To-do immediately:
- Bug: resize widgets
- Bug: set focus
- Documentation of how it is packaged with Qt activity [10] for Sugar
- define user guidelines and make mockups
- typical Pippy examples [11]
- interpreter and code editor tabs
- option to run in fullscreen or box
- list of Pilas actions and behaviors
- help tab
- persistent options
- Document examples / startup guide
Future Work
We must turn this into a roadmap ...
To-do:
- Trim list of dependencies created PyInstaller, to include only what is needed
- Incorporating autocomplete and inline help for the ninja-ide
- Use dbus [12] to communicate with the menu of others
- Incorporate Sugar persistence [persistence options or code to be developed]
- Integrate code for the pilas-engine [13] and pilas.xo
Wish list
- Refactoring to PyCairo [14]
- Incorporate into the activity the possibility of Sugar sharing
- Add interactive options on objects (such as in eToys [15] )
Running Pilas from Pippy or Terminal
This is not working, help please!
Pippy:
import sys sys.path.append('/home/olpc/Activities/Pilas.activity') import pilas pilas.iniciar()
Terminal:
Create a file myprogram.py in ~/Pilas.activity containing
import pilas pilas.iniciar()
In Terminal type
python myprogram.py
|
https://wiki.sugarlabs.org/go/Activities/Pilas
|
CC-MAIN-2017-39
|
refinedweb
| 573
| 50.02
|
Application Programming Interface
PvPToggle includes several functions for enabling developers to hook into it's features and toggle players, worlds or global PvP status. These functions, and some explanation are listed below.
The first step is to hook into PvPToggle. To do this, in your code, you must put the following line of code in your imports section:
import com.sleelin.pvptoggle.PvPToggle;
This will provide you with the interface to toggle and check PvP status. The next step is to check if PvPToggle is loaded on the target system (if it is not loaded, errors will occur). You can do this with the following code, which you can use anywhere:
Plugin PvPTogglePlugin = this.getServer().getPluginManager().getPlugin("PvPToggle"); if (PvPTogglePlugin != null){ PvPToggle pvptoggle = ((PvPToggle) PvPTogglePlugin).getHandler(); }
Interface Functions
From here, there are a range of functions at your disposal which can be used to toggle PvP status. These are:
boolean pvptoggle.checkPlayerStatus(Player player, String world)
- Checks whether or not PvP is enabled for a specified player in the specified world, and returns their status as a Boolean. Takes arguments player, of type Player, and world, of type String.
boolean pvptoggle.checkWorldStatus(String world)
- Checks whether or not PvP is enabled world-wide for a specified world, and returns the result as a boolean. Takes argument world, of type String.
boolean pvptoggle.checkGlobalStatus()
- Checks whether server-wide PvP is enabled, and returns the result as a boolean.
void pvptoggle.setPlayerStatus(Player player, String world, boolean newval)
- Sets PvP to "newval" for a specified player in the specified world. Takes arguments player, of type Player, world, of type String, and newval, of type boolean.
Posts Quoted:
How can this be fixed?
@bPrepared
Huh, looks like Bukkit might have changed the way the plugin handler retrieves plugin instances. This will be fixed in v2.0 coming soon!
Please could you update your API? I'm trying to use your plugin with mine and its incredibly difficult with an out of date API
|
https://dev.bukkit.org/projects/pvptoggle/pages/api
|
CC-MAIN-2022-40
|
refinedweb
| 330
| 58.38
|
The simplest way to share your customers' experiences.
The overall rating reflects the current state of the app. It accounts for all app reviews but prioritizes the most recent ones.
All reviews
Maison 15
Can I add this line
{% if customer.email != nil %}{{ customer.email }}{% else %}john.smith@example.com {% endif %}
inside email text of form reviews?
Shoreline 2
Decent app.
PROS:
It's free. Shopify should have a built-in review engine, anyway, but it's hard to argue with free.
Easy to use.
Easy to install.
Looks great—better, actually—on mobile.
CONS
Slow loading. This is not unique to this app—most Shopify apps, even the really good ones, take a few extra seconds to load. I just figure if it's Shopify native, it should load a little more quickly. We keep it at the bottom of the page so it doesn't hurt user experience too much.
MISSING FEATURES
Display Limits + Pagination for reviews. This is an obvious feature. We should be able to set how many reviews display at once, such that users can scroll or click to the next bunch of reviews.
"Verified Buyer" badges. Most modern review engines have these. If Shopify is also the order processor, this should be the easiest thing in the world to implement.
Conditional tag displays. Another easy one—if the product has no reviews, why clutter up the Collection or Product page with empty stars and a "no reviews yet" notice?
Easy CSS overrides. There are already a few built into the engine (star color, border and padding, etc), but things like font sizes would be great to have at least some control over.
Hoa Cam
Love this apps. We recently added this apps to our store and customers are pouring in their reviews. Thank you. Very easy to use.
Genius Pipe
I have found a solution for "taking forever to load in Google Chrome", etc:
Disclaimer: The following is based on Brooklyn Theme and have only been tested for my store. I hope it helps you guys too!
Problem:
Product Reviews is loading its own jQuery, which is fine, however, if you have Product Sharing turned on, i.e. share a product on Facebook, Twitter, Pinterest, etc - Twitter API is taking forever to load the "count of tweets" and blocking Product Reviews App from loading jQuery.
Solution A:
In theme customization -> Social Media -> Under "Sharing": turn OFF 'Tweet on Twitter' option.
Solution B:
If you want to keep twitter to allow customers to share, you’ll have to disable twitter's counter code: comment this entire block in assets/social-buttons.js.liquid:
if ( $twitLink.length ) { … }
I have also reached out to Shopify's team with detailed explanation of the problem and proposed solutions on their end, hopefully they can update the plug-in to either not load a jQuery second time if it already exists, or bypass twitter loading problem.
Otherwise, I think it’s awesome!!!
Lexi Butler Designs
It takes forever to load in Google Chrome! The app itself is wonderful love it. I have more then 20 reviews on my site and are afraid to uninstall the app and the re install. So I did it with Google Chrome...I uninstalled it all of it and re installed it. It's the same. It takes forever to load, or it does not load at all.
I contacted Shopify twice about this matter and and there suggestion to clean my computer and my cache. I did that, my computer is as clean as a whistle.
Fact is the Google Chrome is the most used browser.in any statistics ...therefore the app should me working with it. If at all the customer will not contact the store to leave a review.....if it does not load fast enough, they won't leave a review or even visit the site again. I am expected this app to work with my store when I download it.
Please fix this awesome app!!! Thank you
GENIOUS PIPE>>>your awesome IT FIXED IT!!!!!
Volto Nero Costumes
Emigrated from etsy to shopify and wanted to import the reviews I had been collecting for years. It does not work particularly well and took me days to finally import my reviews. Thanks to the friendly support <3
Mezuzah One
I installed this app on my shop after having some trouble with Yotpo that they weren't able to resolve. So far I am very happy with this app and it's free. My one complaint is that there is no system for sending customers an email to remind them to leave a review. That was the best advantage of Yotpo, because without such a feature, getting people to actually leave reviews can be very tedious.
Bettes
It looks really great on the site, as they costumize it to the look of your website, very happy with it!
Cool Kids Rooms
This is a great product - simple to install and easy for customers to use.
St Augustine Lions
Great app and great customer support - thank you for this wonderful free app!
|
https://apps.shopify.com/product-reviews/reviews?auth=1&page=132
|
CC-MAIN-2021-43
|
refinedweb
| 848
| 75.5
|
1) Barcode scanner library project
2) Barcode scanner example project
Import both of these projects into Eclipse and you should be all set to go. Hopefully seeing the full projects will help people get up and running.
If this works for you and you don't already have Dropbox sign up for the free service via my referral link so I can have more space to host future example projects. Thanks!.
89 comments:
Thank you Sir, It really help. But I had a problem with customized scanner plugin. BarcodeScanner works fine but if I need to make SCAN on button click or any other event. For that purpose I have made few changes in capture.xml and capture activity class. I have created new button name 'close' and created new function 'myFuction' that should be triggered on button click.
here is code of xml
here is code of java
which runs perfect, but guide me how to execute myFunction() on Button Click (on 'close' button Click event).
@ayesha
Move line 174 to 169 and when you click the close button myFunction() will be called.
HI SIMON ,
i am sangeeth , when i try to upgrade my barcode Plugin to PHONEGAP2.0 using the LIbrary avilable in GITHUB. it is showing me an error like
Conversion to Dalvik format failed with error 1
do i need to use a seperate Library for Phonegap 2.0.i think there is a huge update made in cordova2.0 in the coding part . they have Removed IPlugin.java as far as i looked in to it GITHUB incubator of cordova class files .
java.lang.IllegalArgumentException: already added: Lcom/phonegap/api/IPlugin;
thanks in advance
Sangeeth
@sangeeth_LVS
It looks like you are including cordova.jar twice in your build path. You don't need it in your library project libs directory, you only need it in your applications libs folder.
Thank You it helped me !!
Hi simon,
PHONEGAP QR encoder :
while Encoding the QRcode it is encoding and showing it in the new window . is it possible to store the Encoded QRcode in the PhoneStorage ? i think it is useful only in that way .
Thanks
Sangeeth Kumar V
Hi Simon
I´m trying to make this work but Eclipse complains about this line in BarcodeScanner.java:
getMenuInflater().inflate(R.menu.activity_barcode_scanner, menu);
"R cannot be resolved to a variable"
So i uncomment that line and then i can build, but get a new error from the APP it self "Scanning failed: Class not found"
Problem seems to be that in barcodescanner.js this:
BarcodeScanner.prototype.scan
should be
BarcodeScanner.scan
Now i don´t get the error but no scanner is startet up (i do have CAMERA and FLASHLIGHT permissions in AndroidManifest.xml)
What seems to be the problem?
Eclipse 3.7.2
Android: 4.0.3
Kind regards
Kim
@sangeeth_LVS
That functionality is currently not implemented. It wouldn't be too hard to do but I don't have time to work on it right now.
@Kim Stegenborg Madsen
I have no idea what is going on. In my two example projects the code:
getMenuInflater().inflate(R.menu.activity_barcode_scanner, menu);
is never used so I'm not sure about your starting point.
Also, BarcodeScanner.prototype.scan is correct in the JS. Based on that error you are seeing I'd guess you didn't add the correct lines into your manifest so it can find the capture activity. But again, I'm not sure of your starting point so it is hard to say.
Hi Simon
I´ve apparently used a different BarcodeScanner.java (from phonegap), which contains a bit more than yours:
public class BarcodeScanner extends DroidGap {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.loadUrl("");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//getMenuInflater().inflate(R.menu.activity_barcode_scanner, menu);
return true;
}
}
So removing the onCreateOptionsMenu method got rid of the "R cannot be resolved to a variable"
However i still get the "class not found" error.
I´m gonna download your files once more and start from scratch again. Do i need anything besides these files? I mean, no additional phoneGap/Cordova etc.?
Kind regards
Kim
@Kim Stegenborg Madsen
If you use the two projects I have linked to in my post you'll just need to import them into Eclipse. Nothing else is needed.
Okay, so i´ve downloaded the two projects again, importing them from scratch (library first).
The BarcodeLibrary has several errors in src (client.android, client.android.(book|encode|history|result) and many more)
The BarcodeScanner has 4 errors in the AndroidManifest:
So i don´t know, do i have a sick setup or is this expected?
After outcommenting the above i can build and get the Cordova icon and "device is ready", but i need to test the scanning function. I´m using the index.html file from your previous tutorial:
and then i get "class not found" again?
Kind regards
Kim
@Kim Stegenborg Madsen
As you can see from the above, the error you posted did not get into Blogger. Don't post HTML as it can only handle very basic tags. Can you post the error up on gist or pastebin?
Simon
if u could give me a spark for saving the Encoded QR in to device storage . i think i could catch up and complete the Task . i was blank for 2 days trying this one .
Thanks
Sangeeth Kumar V
@sangeeth_LVS
Sorry, I don't have time to go poking around the library project code. It shouldn't be too bad to save a view as a jpg though. You may wan to check out the screen shot plugin for example.
Simon,
When i try to share the QRcode Generated it is showing an alert box . "saying SD Card isnot Accessible ".
Hi Simon.
Here´s the AndroidManifest.xml in pastebin:
Kind regards
Kim
@sangeeth_LVS
Did you make sure to add the write external storage privilege to your android manifest.xml?
@Kim Stegenborg Madsen
You need to go over the README again. You haven't added the bits to request the Camera & Flashlight nor have you added the necessary activities to call the scanner/encoder.
Hi Simon
That´s why i earlier asked if i needed anything besides your two examples to import.
The camera section was there, the flashlight missing in your example has been added, and i´ve followed the README.md from start to end, but i still get the same error: "Class not found" when i press scan in the app.
I get some warnings from com.phonegap.plugins.barcodescanner/BarcodeScanner.java:
"The method success(PluginResult, String) from the type Plugin is deprecated" in method onActivityResult():
this.success(new PluginResult(PluginResult.Status.OK, obj), this.callback);
Tested on:
HTC Sensation: 4.0.3
Virtual device: 4.1.2
barcodescanner.js: 2.0
cordova: 2.1
The project is using Android 2.1, cout that be the problem?
Tell me what files do you need to see and i´ll pastebin them.
Kind regards
Kim
simon
why does all the Phonegap Application crashes on change in orientation . is there any fix for it .
thanks
sangeeth kumar
Hi Simon
FYI, i tried to use Android 4.0.3 against the phone with same Android sw, same result, class not found
Kind regards
Kim
More FYI
"Update (2012/08/09): As of PhoneGap 2.0 the plugins.xml file has been deprecated. It has been replaced with config.xml. So if you are starting a brand new project that has config.xml in the res/xml directory you will need to add your plugin declarations to this file. If you are using an older version of PhoneGap or upgrading an older project to PhoneGap 2.0 you can still use the plugins.xml file as we've got backwards compatibility (sort of). Please note though config.xml will take precedence over plugins.xml so you should not have both files in one of your projects as you'll end up tearing your hair out."
Exactly what i do :-) I did as the README told me to do, added the plugins.xml file from another project and added the barcodescanner line, but there was a bunch of other plugins aswell in that file, that might have conflicted with config.xml. Now i don´t get the class not found error anymore, but when pressing scan in the app it ask which program to execute the action (it´s in danish), and then dies when i select my app with this error:
threadid=1: thread exiting with uncaught exception (group=0x40aaf228)
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.simonmacdonald.scan/com.google.zxing.client.android.CaptureActivity}: java.lang.ClassNotFoundException: com.google.zxing.client.android.CaptureActivity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2229)
at android.app.ActivityThread.access$600(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1261)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:4945))
Caused by: java.lang.ClassNotFoundException: com.google.zxing.client.android.CaptureActivity
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
at android.app.Instrumentation.newActivity(Instrumentation.java:1039)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2101)
Any idea how to solve this?
Kind regards.
Kim
@sangeeth_LVS
First off, not all PhoneGap applications crash on orientation change. That would make the framework pretty useless. If your app is crashing on orientation change you are probably missing the orientation attribute from your configChanges in the manifest.
Make sure you have the following line in your config:
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale"
Follow the instructions at:
Look at the end of point number 3.
.
Hi Simon.
I´m importing the example projects, it´s just not clear to me which way to do it (maybe cause it´s new to me to work in Eclipse, i´m a VIm man?):
Should i create a project and import them into that?
Should i import it directly (file-import), if so choose general->existing project into workspace or android->existing android code into workspace?
So i tried different approaches and probably messed up previous versions i guess. (how do i save a project in a safe place, so i don´t mess it up, trying new things? by copy project? or is there a smarter way to do it? For now i´m zipping the whole project in windows explorer once in a while...)
I´d like to figure out how it works and what i´ve done wrong
zipped file of the project is here:, this is the barcodescanner project - Do you need the library project aswell?
Kind regards
Kim
Hi Simon
Okay, i tried once more from scratch, this time i made it work, but not without certain challenges :-)
I Tried to import BarcodeLibraryProject and BarcodeScanner from scratch with file->import->General->Existing projects into workspace. Both says "no project found to import".
Imported them instead with file->import->Android->Existing Android code into workspace
BarcodeScanner:
"project.properties is out of sync with local file", wierd error... Editing the file with the eclipse text editor just showed a press F5 to reload, then it worked
100 errors (R cannot be resolved to a variable, and in AndroidManifest.xml "hardwareAccelerated", "XlargeScreens", "installLocation, 'configChanges' value 'orientation|keyboardHidden|keyboard|screenSize|locale').
I tried to debug that... Apparently "installLocation" was added in API level 8, but changing to api 8 or 16 doesn´t remove the error :-(
The Library was even worse, a bunch of errors in the /src dir, i couldn´t get rid of.
So i put it aside, looked at it an hour later and decided to make copies of both projects to "filename"+"01". Suddenly the errors on the Library dissapeared. Any idea why this happend?
Adding the library didn´t work for the BarcodeScanner01 project, but adding library01 did. Then all i did was to follow the - I changed the bit about adding to res/xml/plugins.xml, instead i added it to res/xml/config.xml since i use phonegap2.0 (add that to the guide?)
other than that, i replaced your index.html with the one you´ve written here: (maybe add that to your example as with-barcode-js.index.html?)
Thanks for your help and patience.
Kind regards.
Kim
Hello Simon,
sorry for my english, because i'm french.
I want to create a custom barcode scanner with phonegap. I have read a lot of tutorial on internet to integrate the barcode scanner plugin in my project, but this plugin never work...(always this error : Class not found)
I'm not a specialist on java or eclipse environement...
Maybe you can send me a full code source work perfect for help me for this project...
I hope you can help me for that.
please please please.
my email adress is sebastien.capron(at)gmail.com
Thank for all.
Sébastien.
@Kim Stegenborg Madsen
I'm glad it is finally working for you. Yes, when you import these examples they should be done as Android projects. One other thing I need to change is after you import you should change it so it is built with the latest version of Android. That would make a lot of those errors go away.
Hi again.
I triede to import it at home to (Linux), still got the errors in AndroidManifest.xml, so how did i get rid of those? Added a space somewhere in the file, so it´s changed compared to your version, then saved it and then... errors is gone.
So wierd, but i thought I´ll share this so the next person who experience this doesn´t spend countless hours figuring out what Eclipse is complaining about...
Kind regards
Kim Stegenborg Madsen
@Cebbz
The full source code for both the library and example project are available at the links in my post. Do this to get the projects in your workspace:
File -> Import -> Android -> Existing Android Code into Workspace
Hi Simon.
Sorry, i'm sure missing some important point.
I'm trying to run that application.
When i launch the application I have only the "Device Ready" window of PhoneGap.
But how i launch a scan ?
I'm afraid that the "Example project" is like the "Hello World" of PhoneGap.
Thanks for a reply.
@vincuo
It wasn't you it was me. The project got clobbered on Dropbox somehow. I just put the correct version back so download it again.
I have to ask, Does this plugin even support the cordova 2.2.0 or android sdk 4.x?
For two days now I have tried with both your sample projects and my own and I cannot get this to compile.
@mistik1
Yeah, it works on my phone running Android 4.1 without any issues. What is your compile issue?
Hi!
Found this great plugin last week and have been trying to get it work for me. I get it to scan and it kind of works. After scanning it peeps and says "Product Found" but does not show this UPC code. How can I get this code to some variable for example? I would need it to be in url like
How can I achieve this? I have used your example projects. Thanks!
@Thomas Berg
The success callback should be invoked with the UPC in result.text. Possibly you need the updated plugin that I just pushed for version 2.2.0.
I'm still getting a ton of errors. Since this is my first time with Eclipse, I'm guessing it's something fundamental (e.g. Ant? Working directory?). Is it apparent what's missing by looking at this screenshot of my Eclipse session.
@roy whitburg rwhitburg
Well it is hard to tell but the first thing you need to do is to switch what API level you are building CaptureActivity with. Right click on the project folder, select Properties, Android and select the highest level API version you have. The problem is you are building with an API level that doesn't support xlargescreens.
After that I'd try closing an opening the project as it seems like your gen folder is not getting updated. That is where all the R errors come from.
Thanks for responding. I have the latest API level checked (17) in both the library and application.
I right clicked and "closed project" then "opened project" for both as well, which did make some of the red alerts go away in the navigator view. But I'm still having the same problems (see image).
Most of the problems refer to a CaptureActivity Path. I noticed that I have no such physical directory. Was that supposed to have been (automatically or manually) created at some point?
I'm using the latest API. Closing and opening the project did get rid of some of the problems, but most remain, as you can see below. Not sure where else to turn, as this is my first phonegap project.
Thanks.
Disregard my previous posts. I "Cleaned" it and, other than a bunch of warnings, it's working well now.
Thanks for the app!
hello mrs. Mac donald, i try used your app, but barcode scanner doesn`t show me a alert, why?
@ALMORA DEV
Didn't give me much to go on. What do you see in "adb logcat"?
this is my log
D/CordovaLog(31978): *********** start scan *********
D/CordovaLog(31978):: Line 39 : *********** start scan *********
I/Web Console(31978): *********** start scan ********* at
D/CordovaLog(31978): *********** finish scan *********
D/CordovaLog(31978):: Line 50 : *********** termina funcion scan *********
I/Web Console(31978): *********** finish ********* at
D/DroidGap(31978): Paused the application!
D/CordovaWebView(31978): Handle the pause
D/OpenGLRenderer(31978): Flushing caches (mode 0)
D/OpenGLRenderer(31978): Flushing caches (mode 1)
D/DroidGap(31978): onDestroy()
D/CordovaWebView(31978): >>> loadUrlNow()
W/IInputConnectionWrapper(31978): showStatusIcon on inactive InputConnection
D/DroidGap(31978): DroidGap.onCreate()
D/CordovaWebView(31978): Origin to allow:*
D/CordovaWebView(31978): Origin to allow: .*
I/CordovaLog(31978): Found log level DEBUG
I/CordovaLog(31978): Changing log level to DEBUG(3)
I/CordovaLog(31978): Found preference for useBrowserHistory=false
D/CordovaLog(31978): Found preference for useBrowserHistory=false
I/CordovaLog(31978): Found preference for exit-on-suspend=false
D/CordovaLog(31978): Found preference for exit-on-suspend=false
D/JsMessageQueue(31978): Set native->JS mode to 2
D/DroidGap(31978): DroidGap.init()
D/CordovaWebView(31978): >>> loadUrl()
D/PluginManager(31978): init()
D/CordovaWebView(31978): >>> loadUrlNow()
D/DroidGap(31978): Resuming the App
D/SoftKeyboardDetect(31978): Ignore this event
W/webcore(31978): java.lang.Throwable: EventHub.removeMessages(int what = 107) is not supported before the WebViewCore is set up.
W/webcore(31978): at android.webkit.WebViewCore$EventHub.removeMessages(WebViewCore.java:1691)
W/webcore(31978): at android.webkit.WebViewCore$EventHub.access$7900(WebViewCore.java:926)
W/webcore(31978): at android.webkit.WebViewCore.removeMessages(WebViewCore.java:1803)
W/webcore(31978): at android.webkit.WebView.sendOurVisibleRect(WebView.java:2924)
W/webcore(31978): at android.webkit.ZoomManager.setZoomScale(ZoomManager.java:593)
W/webcore(31978): at android.webkit.ZoomManager.access$1700(ZoomManager.java:49)
W/webcore(31978): at android.webkit.ZoomManager$PostScale.run(ZoomManager.java:984)
W/webcore(31978): at android.os.Handler.handleCallback(Handler.java:605)
W/webcore(31978): at android.os.Handler.dispatchMessage(Handler.java:92)
W/webcore(31978): at android.os.Looper.loop(Looper.java:137)
W/webcore(31978): at android.app.ActivityThread.main(ActivityThread.java:4441)
W/webcore(31978): at java.lang.reflect.Method.invokeNative(Native Method)
W/webcore(31978): at java.lang.reflect.Method.invoke(Method.java:511)
W/webcore(31978): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
W/webcore(31978): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
W/webcore(31978): at dalvik.system.NativeStart.main(Native Method)
D/SoftKeyboardDetect(31978): Ignore this event
D/DroidGap(31978): onMessage(onPageStarted,)
D/Cordova(31978): onPageFinished()
D/DroidGap(31978): onMessage(onNativeReady,null)
D/DroidGap(31978): onMessage(onPageFinished,)
D/DroidGap(31978): onMessage(networkconnection,wifi)
D/DroidGap(31978): onMessage(spinner,stop)
D/DroidGap(31978): onMessage(spinner,stop)
D/DroidGap(31978): Paused the application!
D/CordovaWebView(31978): Handle the pause
D/OpenGLRenderer(31978): Flushing caches (mode 0)
W/IInputConnectionWrapper(31978): showStatusIcon on inactive InputConnection
thanks and regard
@ALMORA DEV
What are your configChanges set to in the manifest.xml? Put it up on gist or pastebin.
sorry, thanks in advance, you are helping me a lot
@ALMORA DEV
I rejected your last comment as you can't post xml in blogger it doesn't show up. Put it up on gist or pastebin like I said.
sorry for the delay. This is the two manifiest.
the config
thanks.
@ALMORA DEV
Nothing is jumping out at me here.
Hi Simon,
For the past 3 months we don't have the problem on barcode scan, but just today. When I click the button scan on our app which is installed in Nexus 7 (android 4.2). It shows
"Sorry,the Android camera encountered a problem.You may need to restart the device."
@Jeoffrey Galbizo
Have you tried the latest version of the plugin? A lot of folks have had problems with the barcode scanner and the Nexus 7 but I don't have one to test.
opps sorry for late reply.
i figured it out by installing the zxing barcode scanner app, it won't work the scanner if you scan on front camera. nexus 7 has no camera on back.
thanks.
hey simon, the library is perfectly working in emulator and few devices, but in few device like samsung GT-1900 the app is being hanged after the scan, and nothing can be done except force exit :(. please help me with this asap!
@Shiva Acharjee
What are you seeing in "adb logcat" when you hang the app?
Hi @simon,
I imported your com.simonmacdonald.scan.BarcodeScanner prject to my work space and i got
[2013-04-11 18:27:10 - com.simonmacdonald.scan.BarcodeScanner] Unable to resolve target 'android-16' as error can you please help me. Thank u in advance
@SAVIOUR
Start your Android SDK Manager and download API level 16.
Hi, Simon
your Barcode_scanner project working fine on my android device(2.3),but it is not scanning any barcode.
i m just find a rectangular view to scan barcode but it is not working.
plz reply asap.
@sapna rai
Some older devices had pretty bad cameras that can't possibly focus on the barcode. What are you seeing in "adb logcat"?
@Simon MacDonald : thanks for reply..actually it is not scanning any barcode.On focussing the rectangular view over any barcode, I don't get any result and any message..Do I need to write some additional codes?...Do help me..
Hi Simon;I got error in com.simonmacdonald.scan.BarcodeScanner android manifest
""
error: Error: No resource found that matches the given name (at 'label' with value '@string/
share_name').
@sapna rai
See previous reply.
@SAVIOUR
It sounds like you haven't added the library project to your project.
Hi Simon,
How can I redirect to another html page after scanning a QR?
Right now it is just showing "Found URL" and redirect itself back to the main index.html.
Which part of code I should look into?
I'm using the LibraryProject vers 2.2.0 and your current example project from this post, with updated barcodescanner.js and BarcodeScanner.java from 2.2.0.
Thanks in advance!
Karen
@Karen Wong
In the success callback for the scan you can take the url returned and open the web page.
Sir, your barcode scanner is absolutely perfectly working, we've used the app for almost a year but today, I compile eclipse project with the latest version cordova 2.7.0. All of a sudden BarcodeScanner.java got an error "cordova cannot resolved or is not a field" and "Plugin cannot be resolve to a type". I configured build path, search google but still got the error.
@Jeoffrey Galbizo
The Plugin class was deprecated in favour of CordovaPlugin. You'll need to update your BarcodeScanner plugin to the 2.2 version.
Hi Simon, I hope you can help me. I just started using PhoneGap and have installed the latest Phonegap version and BarcodeScanner, I can get the app running, but it crashes as soon as it recognizes the bar code with the following error:
java.lang.RuntimeException: Unable to resume activity {com.csmcommunication.MediaLib/com.csmcommunication.MediaLib.MediaLib}: java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=195543262, result=-1, data=Intent { act=com.phonegap.plugins.barcodescanner.SCAN flg=0x80000 (has extras) }} to activity {com.csmcommunication.MediaLib/com.csmcommunication.MediaLib.MediaLib}: java.lang.NullPointerException. I tried downloading your sample projects, but am looking through the code and everything seems to the same. Any thoughts? Please let me know if you need me to send anything.. Thanks in advance for your help.
- Chris
Hi Simon, Um. Yeah, you must be magic - I got it working. Thanks! - Chris
Hey Simon. Looks like a great project!
I am struggling with one problem though: When I am exporting the whole thing to Android apk I get this error :"conversation to dalvik format failed with error 1".
I checked your recent solution for this error and that's not working for me(I don't have jar conflict). Also checked if there any conflicting class and couldn't figure it out. any ideas?
Is there any chance you could let us know how to set the barcode scanner up in Android Studio im struggling to figure out how to import the project thanks
@Lee Doel
Sorry I haven't had the chance to upgrade them for Android Studio.
@Yonatan Wolowelsky
Without seeing your project I can only point to the most likely cause which would be two jars that include the same classes.
Hi Simon -
I've imported both zip files into Eclipse and I can do a Run As to my tablet, but I get "Unfortunately, BarcodeScanner has stopped." I don't know what to do next.
Thanks,
Jeff
@Jeff
What do you see in "adb logcat"?
Hi Simon,
I have imported second zip file into Eclipse and when I run it on my phone or emulator, But I get "Unfortunately,I get Barcode Scanner stopped".
Logcat error message shows " Class NOT FOUND EXCEPTION" unable to instantiate the activity.
@Shraddha Pandey
What class is missing? Did you remember to add the library project to your app in the properties->android section of Eclipse?
sir , i am new to phone gap and hybrid applications,i have implemented this natively,now i want to this in a hybrid way, so i download and imported this code to eclipse but i am getting error in manifest file as :
Description Resource Path Location Type
error: Error: No resource found that matches the given name (at 'label' with value '@string/share_name'). AndroidManifest.xml /com.simonmacdonald.scan.BarcodeScanner line 74 Android AAPT Problem
Demo app seems doesn't build with API 18. I must use API 16?
Tried on a real device I got this:
08-30 18:01:14.329: D/dalvikvm(7082): Late-enabling CheckJNI
08-30 18:01:15.639: E/Trace(7082): error opening trace file: No such file or directory (2)
08-30 18:01:15.699: V/ActivityThread(7082): com.simonmacdonald.scan white listed for hwui
08-30 18:01:16.109: W/dalvikvm(7082): Unable to resolve superclass of Lcom/simonmacdonald/scan/BarcodeScanner; (534)
08-30 18:01:16.109: W/dalvikvm(7082): Link of class 'Lcom/simonmacdonald/scan/BarcodeScanner;' failed
08-30 18:01:16.109: D/AndroidRuntime(7082): Shutting down VM
08-30 18:01:16.109: W/dalvikvm(7082): threadid=1: thread exiting with uncaught exception (group=0x40b43930)
08-30 18:01:16.229: E/AndroidRuntime(7082): FATAL EXCEPTION: main
08-30 18:01:16.229: E/AndroidRuntime(7082): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.simonmacdonald.scan/com.simonmacdonald.scan.BarcodeScanner}: java.lang.ClassNotFoundException: Didn't find class "com.simonmacdonald.scan.BarcodeScanner" on path: /data/app/com.simonmacdonald.scan-1.apk
08-30 18:01:16.229: E/AndroidRuntime(7082): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2224)
08-30 18:01:16.229: E/AndroidRuntime(7082): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
08-30 18:01:16.229: E/AndroidRuntime(7082): at android.app.ActivityThread.access$600(ActivityThread.java:153)
08-30 18:01:16.229: E/AndroidRuntime(7082): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
08-30 18:01:16.229: E/AndroidRuntime(7082): at android.os.Handler.dispatchMessage(Handler.java:99)
08-30 18:01:16.229: E/AndroidRuntime(7082): at android.os.Looper.loop(Looper.java:137)
08-30 18:01:16.229: E/AndroidRuntime(7082): at android.app.ActivityThread.main(ActivityThread.java:5260)
08-30 18:01:16.229: E/AndroidRuntime(7082): at java.lang.reflect.Method.invokeNative(Native Method)
08-30 18:01:16.229: E/AndroidRuntime(7082): at java.lang.reflect.Method.invoke(Method.java:511)
08-30 18:01:16.229: E/AndroidRuntime(7082): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
08-30 18:01:16.229: E/AndroidRuntime(7082): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
08-30 18:01:16.229: E/AndroidRuntime(7082): at dalvik.system.NativeStart.main(Native Method)
08-30 18:01:16.229: E/AndroidRuntime(7082): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.simonmacdonald.scan.BarcodeScanner" on path: /data/app/com.simonmacdonald.scan-1.apk
08-30 18:01:16.229: E/AndroidRuntime(7082): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:65)
08-30 18:01:16.229: E/AndroidRuntime(7082): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
08-30 18:01:16.229: E/AndroidRuntime(7082): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
08-30 18:01:16.229: E/AndroidRuntime(7082): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
08-30 18:01:16.229: E/AndroidRuntime(7082): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
08-30 18:01:16.229: E/AndroidRuntime(7082): ... 11 more
08-30 18:01:20.279: I/Process(7082): Sending signal. PID: 7082 SIG: 9
What's wrong?
Thanks.
@nutella
I built against sdk 18 and ran it on my Nexus 4 running Androd 4.3 (sdk 18) without any problems.
@omkar kulkarni
Right click on the project, select properties, select Android then look down the bottom at the Library section. It is either missing the library project or has the wrong name.
Hey Simon! Great blog! It sure has been useful for me since I started working with phonegap.
Is there any chance you could help me using the BarcodeScanner Plugin? I installed it and the scan seems to work fine (camera launching and QRCode detected). But when I try to obtain the result using the classic success function, it's empty and the result code is return_cancelled.
I am using phonegap 3.0. Would you have any idea to where I should look?
Thanks in advance,
Yoann
@Yoann Estepa
What do you see in "adb logcat"?
I tried the barcode scanner example but the LogCat shows a reference error in index.html:: Line 31: Uncaught Reference error: app is not defined
Thanks, Jos
@Jos Hendriks
Something has gone wrong before this point as it does not appear that the linked in JS files got loaded. That should be the only way app is not setup.
hi simon,
thanks for this best tutorial and other examples.
well i have android phone with both kind of camera (front and back) n
now i want to use only front camera to scan QR code using barcode scanner but its not working, it alwasys uses back camera.
can you plz, give me some advice ?
Thanks buddy
@Jayesh Vadgama
You'd have to dig into the ZXing library code in order to enable front camera support.
|
http://simonmacdonald.blogspot.com/2012/10/barcode-scanner-example-projects.html
|
CC-MAIN-2014-15
|
refinedweb
| 5,350
| 60.11
|
A simple schematic file reader for nbtlib
Project description
nbtschematic
A simple nbtlib Schema for reading or writing Schematic files for MCEdit and other world editors.
Installation
Python 3.6 or higher is required.
pip3 install nbtschematic
Examples
To load an existing MCEdit or other schematic file from disk, run:
from nbtschematic import SchematicFile sf = SchematicFile.load('tests/test_schematic/simple.schematic') print("The block at Y=%d, Z=%d, X=%d has block ID %d" % (2, 3, 0, sf.blocks[2, 3, 0]))
To generate a schematic file in python, run:
from nbtschematic import SchematicFile sf = SchematicFile(shape=(10, 8, 4)) assert sf.blocks.shape == (10, 8, 4) sf.blocks[2, 3, 0] = 42 sf.save('example.schematic')
The size of the schematic should be defined at construction time. Resizing it will clear the blocks and block data.
Other fields of interest include:
data: Block data for each and every block
entities: Everything that is not a block
blockentities: Extended metadata for blocks
Further Reading
For more information about the underlying objects, see
nbtlib's excellent
examples
page.
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/nbtschematic/
|
CC-MAIN-2021-04
|
refinedweb
| 207
| 57.06
|
Our existing examples of using API calls in groovy focus on SOAP style web services, therefore this article provides a basic example of working with the recently added support for REST. This illustrative example queries internal custom object records. The basic features of groovy REST support is well covered by the Application Composer documentation, and we will articles with examples of creating, updating, and deleting records.
Defining web services is similar for both SOAP and REST, done using the Common Setup - Web Services feature in Application Composer. Before this a decision needs to be made in the way in which you can pass a criteria to your RESTful service.
The first option is by defining the URL Resource parameters inside the Web Service definition. For example the following definition which signifies that we will pass the CustomerName parameter in the adf.webservices.myWSName(getParams) GET call script. As you can see below the Resource URL definition includes the returned fields list and a limit on rows returned. Note the notation of parameter with the double hashtags.
https://[crm-host]/salesApi/resources/latest/Invoice_c/?q=Customer_Id_c=##CustomerId##&limit=5&fields=RecordName,Customer_c,TotalAmountUSD_c
The second - and the one recommended in most cases - is to define the generic service resource endpoint and then pass query (q=) parameters as a map in the GET request call. This means fewer web service definitions and scripts that contain specific use-cases. As such below example service definition can be used by multiple scripts to query the Invoice_c custom object using its RESTful service.
Note: In addition pre-built queries - known as finders - are available on selected standard objects.
In this example a custom Formula Field exists on the Account standard object which will lookup custom object records (Invoices) for the matching Account.
Below queries the Invoice object using the Customer (Account) field, which is a Dynamic Choice List. Because of this field type we need to use the associated foreign key field Customer_id_c for our query (as the display value is not queryable). The script passes the run-time value (PartyId) taken from the users current Account object record.
def conn = adf.webServices.Invoices def custName = PartyId def myMAP = ['q':'Customer_Id_c='+custName] conn.dynamicQueryParams = myMAP def rslt = conn.GET() def val = rslt.items[0].RecordName return val
This very simple illustrative script returns just the RecordName field from the first matching Invoice record in the response Map object. This is shown on the screen as below:
Clearly a more meaningful script would iterate through the records and process them according to business logic. For more on using the response data see articles using Regex and ArrayLists.
If you get generic HTTP errors when testing, attempt the same request using a REST client (like POSTMAN) and investigate the raw response for more detailed error messages.
You may notice the Groovy Palette shows yellow warning messages from the type checking process, but these can be ignored as the API's used are valid.
For more details on RESTful groovy features review the excellent related documentation.
Pls add me in the discussion ,as i want to know we can query record by http for the different API or database in oracle fusion.
|
https://blogs.oracle.com/fadevrel/querying-custom-object-records-using-restful-web-service-calls-in-groovy-scripts
|
CC-MAIN-2020-29
|
refinedweb
| 534
| 53.92
|
Problem Description
Nim is a two-player mathematic game of strategy in which players take turns removing objects from distinct heaps. On each turn, a player must remove at least one object, and may remove any number of objects provided they all come from the same heap.. Alice and Bob is tired of playing Nim under the standard rule, so they make a difference by also allowing the player to separate one of the heaps into two smaller ones. That is, each turn the player may either remove any number of objects from a heap or separate a heap into two smaller ones, and the one who takes the last object wins.
Input
Input contains multiple test cases. The first line is an integer 1 ≤ T ≤ 100, the number of test cases. Each case begins with an integer N, indicating the number of the heaps, the next line contains N integers s[0], s[1], ...., s[N-1], representing heaps with s[0], s[1], ..., s[N-1] objects respectively.(1 ≤ N ≤ 10^6, 1 ≤ S[i] ≤ 2^31 - 1)
Output
For each test case, output a line which contains either "Alice" or "Bob", which is the winner of this game. Alice will play first. You may asume they never make mistakes.
Sample Input
2 3 2 2 3 2 3 3
Sample Output
Alice Bob
Source
2009 Multi-University Training Contest 13 - Host by HIT
Recommend
gaojie | We have carefully selected several similar problems for you: 3031 3033 3038 3035 3034
Multi-SG游戏的裸题
$sg(x) = \begin{cases} x-1, & \text{$x\%4=0$}\\ x, & \text{$x\%4=1\lor x\%4=2$ }\\ x+1, & \text{$x\%4=3$} \end{cases}$
#include<cstdio> #include<cstring> using namespace std; const int MAXN=1001; int read() { char c=getchar();int x=0,f=1; while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();} while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();} return x*f; } int a[MAXN],SG[MAXN]; int main() { #ifdef WIN32 freopen("a.in","r",stdin); #else #endif int QWQ=read(); while(QWQ--) { int N=read(); for(int i=1;i<=N;i++) a[i]=read(); for(int i=1;i<=N;i++) if(a[i] % 4 == 0) SG[i] = a[i]-1; else if(a[i]%4==1||a[i]%4==2) SG[i] = a[i]; else SG[i] = a[i]+1; int ans=0; for(int i=1;i<=N;i++) ans^=SG[i]; puts(ans?"Alice":"Bob"); } return 0; }。
E. Simple Skewness time limit per test:3 seconds memory limit per test:256 megab...
In the forest, there is a Banana Company that provides bananas from different pl...
D. Red-black Cobweb time limit per test:6 seconds memory limit per test:256 mega...
扫码关注云+社区
领取腾讯云代金券
我来说两句
|
https://cloud.tencent.com/developer/article/1090702
|
CC-MAIN-2020-40
|
refinedweb
| 467
| 61.36
|
Opened 4 years ago
Closed 4 years ago
#25714 closed Bug (needsinfo)
DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread.
Description
Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 85, in run self.result = application(self.environ, self.start_response) File "/usr/lib/python2.7/dist-packages/django/contrib/staticfiles/handlers.py", line 64, in __call__ return super(StaticFilesHandler, self).__call__(environ, start_response) File "/usr/lib/python2.7/dist-packages/django/core/handlers/wsgi.py", line 177, in __call__ signals.request_started.send(sender=self.__class__, environ=environ) File "/usr/lib/python2.7/dist-packages/django/dispatch/dispatcher.py", line 201, in send response = receiver(signal=self, sender=sender, **named) File "/usr/lib/python2.7/dist-packages/django/db/__init__.py", line 64, in close_old_connections conn.close_if_unusable_or_obsolete() File "/usr/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 403, in close_if_unusable_or_obsolete self.close() File "/usr/lib/python2.7/dist-packages/django/db/backends/sqlite3/base.py", line 221, in close self.validate_thread_sharing() File "/usr/lib/python2.7/dist-packages/django/db/backends/base/base.py", line 421, in validate_thread_sharing % (self.alias, self._thread_ident, thread.get_ident())) DatabaseError: DatabaseWrapper objects created in a thread can only be used in that same thread. The object with alias 'default' was created in thread id 140201111500544 and this is thread id 140201088387984.
Using instructions found in Debian bug report:
This looks like a database issue to me, however the reporter of the Debian bug thinks it is something to do with the capital-letter-named django application. Which seems weird to me.
A search for similar bugs found #17998 - not idea if this is related or not.
Change History (5)
comment:1 Changed 4 years ago by
comment:2 Changed 4 years ago by
I can't tell from the original report which database the person is using as the PostgreSQL, MySQL and SQLite adapters are installed. Django allows sharing SQLite connections across threads but not PostgreSQL and MySQL connections.
Generally speaking database connections should only be accessed through
from django.db import connection or
from django.db import connections; connections[alias]. This returns thread local objects and avoids this problem.
The TinycryptoPOS application appears to run a daemon; I'm not sure what it does exactly but I suspect that's how a connection ends up being accessed incorrectly. If every Django user saw that error, we'd probably have heard about it by now, so I suspect the bug is in TinycryptoPOS.
comment:3 Changed 4 years ago by
Closing the Debian bug and forwarding here was the right thing to do. The discussion about single-core / multi-core is irrelevant -- of course you can't reproduce an issue that's obviously related to threads when running single-threaded.
comment:4 Changed 4 years ago by
From the Debian bug report:
I found the origin of the problem: It was the pyjsonrpc library that is included into TinycryptoPOS. After I commented out every part of code that uses something from pyjsonrpc the error disappeared.
You just have to import pyjsonrpc in your Django application without using code from it and the error appears... but only on amd64. I have verified this with another Django application.
I think this is clearly a bug in pyjsonrpc and not a django bug.
Thank you for your help and time and also thanks to the people on the django mailing list for giving me the hint to the right direction.
I have looked at pyjsonrpc (download from PyPI, link to github project is dead), I am not convinced it could cause this problem. However it uses things like gevent and WebSocketClient from ws4py.client.geventclient - both of which I haven't used myself, so I might be mistaken.
comment:5 Changed 4 years ago by
If this is a Django problem, I think you'll need to propose a fix or at least provide the reasoning why.
Forgot to clarify - The Debian bug report is against Django 1.7.7, however I reproduced the above with Django 1.8.4
|
https://code.djangoproject.com/ticket/25714
|
CC-MAIN-2019-26
|
refinedweb
| 687
| 50.02
|
What is an Array in Python 3?
An array is a data structure that can contain or hold a fixed number of elements that are of the same Python data type. An array is composed of an element and an index. Index in an array is the location where an element resides. All elements have their respective indices. Index of an array always starts with 0.
Unlike other programming languages, such as Java, C, C++, and more, arrays are not that popular in Python since there are many iterable data types in Python that are flexible and fast to use such as Python lists. However, arrays in Python 3 are still used in certain cases. In this module, we will learn all about all the important aspects of arrays in Python 3, from what they are to when they are used.
Following is the list of topics covered in this Python module.
- Difference_between_Array_and_List in Python
- Creating an Array in Python 3
- Accessing a Python Array Element
- Basic Operations of Arrays in Python
So, without further delay, let’s get started.
Learn more about Python from this Python for Data Science Course to get ahead in your career!
Difference between Array and List in Python
The basic difference between arrays and lists in Python is that lists are flexible and can hold completely arbitrary data of any data type while arrays can only hold data of the same data type.
Arrays are considered useful in terms of memory efficiency, but they are usually slower than lists. As mentioned above, the Python array module is not that popular to use, but they do get used in certain cases such as:
Creating an Array in Python 3
The array module supports numeric arrays in Python 3. So, to create an array in Python 3, we will have to import the array module. Following is the syntax for creating an array. Now to understand how to declare array in Python, let us take a
look at the python array example given below:
from array import * arraname = array(typecode, [Initializers])
Here, typecode is what we use to define the type of the value that is going to be stored in the array. Some of the common typecodes used in the creation of arrays in Python are described in the following table.
Now, let’s create a Python array using the above-mentioned syntax.
Example:
import array as arr a = arr.array(‘I’, [2,4,6,8]) print(a) Output: array(‘I’, [2, 4, 6, 8])
Interested in learning Python? Enroll in our Python Course in London now!
Accessing a Python Array Element
We can access the elements of an array in Python using the respective indices of those elements, as shown in the following example.
from array import* array_1 = array(‘i’, [1,2,3,4,5]) print (array_1[0]) print (array_1[3]) 1 4
The index of the array elements starts from 0. When we printed the value of array1[0], it displayed the first element.
Basic Operations of Arrays in Python
Following are some of the basic operations supported by array module in Python:
- Traverse of an Array in Python: Iterating between elements in an array is known as traversing. We can easily iterate through the elements of an array using Python for loop as shown in the example below.
Example:
from array import * array_1 = array(‘i’, [1,2,3,4,5]) for x in array_1: print (x) Output: 1 2 3 4 5
- Insertion of Elements in an Array in Python:Using this operation, we can add one or more elements to any given index.
Example:
from array import * array_1 = array(‘i’, [1,2,3,4,5]) array_1.insert(1,6) for x in array_1: print (x) Output: 1 6 2 3 4 5
- Deletion of Elements in an Array in Python:Using this operation, we can delete any element residing at a specified index. We can remove any element using the built in remove() method.
Example:
from array import * array_1 = array(‘i’, [1,2,3,4,5]) array_1.remove(2) For x in array_1: print (x) Output: 1 3 4 5
- Searching Elements in an Array in Python:Using this operation, we can search for an element by its index or its value.
Example:
from array import * array_1 = array(‘i’, [1,2,3,4,5]) print (array_1.index(3)) Output: 2
In the above example, we have searched for the element using the built-in index() method. Using index(3) returned the output 2 which means that 3 is at the index number 2 in array_1. If the searched value is not present in the array, then the program will return an error.
- Updating Elements in an Array in Python:Using this operation, we can update an element at a given index.
Example:
from array import * array_1 = array(‘i’, [1,2,3,4,5]) array_1[2] = 100 for x in array_1: print(x) Output: 1 2 100 4 5
Kick-start your career in Python with the perfect Python Course in New York now!
In the above example, we have updated the already existing value at index 2 instead of adding a new element.
With this, we have come to the end of this module in Python Tutorial. We learnt about arrays in Python 3, how to define array in Python 3, accessing an Python Array, and different operations of Python array..
|
https://intellipaat.com/blog/tutorial/python-tutorial/python-arrays/
|
CC-MAIN-2020-05
|
refinedweb
| 900
| 60.14
|
13 December 2007 13:35 [Source: ICIS news]
LONDON (ICIS news)--The US' Dow Chemical and Kuwait's Petrochemical Industries Co (PIC) have signed a 50:50 joint venture to market and manufacture a range of petrochemicals, the two companies said on Thursday.
?xml:namespace>
To form the company, Dow will sell PIC a 50% share in five of its global businesses worth approximately $19bn and PIC will pay the ?xml:namespace>
“The joint venture, to be headquartered in the
“The JV is expected to have revenues of more than $11bn (pro forma) and employ more than 5,000 people worldwide,” it added.
The joint venture will mean Dow has access to feedstocks from the future refinery projects of Kuwait Petroleum Corp, PIC’s parent.
“This will give the new joint venture company the distinct advantage of full integration from feedstocks to derivatives, while meeting growing customer demand in emerging markets,” it said.
PIC already has two joint ventures with Dow - Equate Petrochemical and ME.
|
http://www.icis.com/Articles/2007/12/13/9086667/dow-kuwaits-pic-form-11bn-petchems-jv.html
|
CC-MAIN-2013-20
|
refinedweb
| 165
| 53.34
|
Linear Programming with Python and PuLP – Part 2
Introduction to PuLP
PuLP is an open source linear programming package for python. PuLP can be installed using pip, instructions here.
In this notebook, we’ll explore how to construct and solve the linear programming problem described in Part 1 using PuLP.
A brief reminder of our linear programming problem:
We want to find the maximum solution to the objective function:
$Z = 4x + 3y$
Subject to the following constraints:
$
x \geq 0 \\
y \geq 2 \\
2y \leq 25 – x \\
4y \geq 2x – 8 \\
y \leq 2x -5 \\
$
We’ll begin by importing PuLP
import pulp
Then instantiate a problem class, we’ll name it “My LP problem” and we’re looking for an optimal maximum so we use LpMaximize
my_lp_problem = pulp.LpProblem("My LP Problem", pulp.LpMaximize)
We then model our decision variables using the LpVariable class. In our example, x had a lower bound of 0 and y had a lower bound of 2.
Upper bounds can be assigned using the upBound parameter.
x = pulp.LpVariable('x', lowBound=0, cat='Continuous') y = pulp.LpVariable('y', lowBound=2, cat='Continuous')
The objective function and constraints are added using the += operator to our model.
The objective function is added first, then the individual constraints.
# Objective function my_lp_problem += 4 * x + 3 * y, "Z" # Constraints my_lp_problem += 2 * y <= 25 - x my_lp_problem += 4 * y >= 2 * x - 8 my_lp_problem += y <= 2 * x - 5
We have now constructed our problem and can have a look at it.
my_lp_problem
My LP Problem: MAXIMIZE 4*x + 3*y + 0 SUBJECT TO _C1: x + 2 y <= 25 _C2: - 2 x + 4 y >= -8 _C3: - 2 x + y <= -5 VARIABLES x Continuous 2 <= y Continuous
PuLP supports open source linear programming solvers such as CBC and GLPK, as well as commercial solvers such as Gurobi and IBM’s CPLEX.
The default solver is CBC, which comes packaged with PuLP upon installation.
For most applications, the open source CBC from COIN-OR will be enough for most simple linear programming optimisation algorithms.
my_lp_problem.solve() pulp.LpStatus[my_lp_problem.status]
'Optimal'
We have also checked the status of the solver, there are 5 status codes:
- Not Solved: Status prior to solving the problem.
- Optimal: An optimal solution has been found.
- Infeasible: There are no feasible solutions (e.g. if you set the constraints x <= 1 and x >=2).
- Unbounded: The constraints are not bounded, maximising the solution will tend towards infinity (e.g. if the only constraint was x >= 3).
- Undefined: The optimal solution may exist but may not have been found.
We can now view our maximal variable values and the maximum value of Z.
We can use the varValue method to retrieve the values of our variables x and y, and the pulp.value function to view the maximum value of the objective function.
for variable in my_lp_problem.variables(): print "{} = {}".format(variable.name, variable.varValue)
x = 14.5 y = 5.25
print pulp.value(my_lp_problem.objective)
73.75
Same values as our manual calculations in part 1.
In the next part we’ll be looking at a more real world problem.
|
http://benalexkeen.com/linear-programming-with-python-and-pulp-part-2/
|
CC-MAIN-2017-39
|
refinedweb
| 518
| 55.74
|
Preprocessors in C Programming
Preprocessors are programs which process the input data and produces an output which is taken as input for another program. In simpler words, it is another program that processes our program and sends it to the compiler.
The compilers rely on this preprocessed data for convenience. The C code that we write is known as the ‘source code’ (Eg: Hello.c) ,the preprocessor processes this source code to produce ‘Expanded Souce Code’ (Eg: Hello.I) which is then compiled by the compiler to give us the output. The C preprocessor also known as CPP is a macro preprocessor.
It is used to include header files, line control, macro expansions and conditional compilation. In C programming it is mostly used by the compiler at the beginning of the code to include certain functionalities that come with the header files.
Features of the C Preprocessor
The features offered by the C preprocessor are also known as ‘Preprocessor Directives’. These directives are preceded by a ‘#’ symbol. Here we have the following Preprocessor Directives:
- Macro Expansion
- File Inclusion
- Conditional Compilation
- Other Directives
Macro Expansion
As we already know Preprocessor are the programs which are used before compilation. As a part of the C Preprocessor, macro serves the same purpose. It is a block of statements used as a Preprocessor Directive. A macro is also known as a macro definition. Let’s have a look at an example to have a clear picture of a macro definition:
#include<stdio.h> #define NUM 10 int main() { int square; square= NUM * NUM; printf("The square is %d",square); return 0; }
The macro #define puts the value 10 everywhere NUM is being used in the program. Let’s see what is happening here in detail. Before the program passes on to the compiler it is processed by the Preprocessor for macro definitions. When it finds #define it replaces the macro template with the macro expansions everywhere in the source code and sends it to the compiler.
But an important question that arises over here is why use a macro definition when we can define NUM anywhere inside the main() function? The answer is that when we define NUM with the value 10, it replaces NUM with 10 everywhere in the program. So, in case we need to make any changes to the value of NUM the only thing we need to do is change it in the macro definition and it shall be replaced everywhere in the program, instead of manually changing it everywhere in the program which will be very difficult for complex programs.
You must’ve seen the use of capitals for the macro and wondered why? Macro Templates do not necessarily be written in capitals. It is written in capitals mainly for the programmer’s convenience. It helps to distinguish a simple variable in the code from a macro. A programmer can follow the basic variable norms to define a macro. The following are more uses of the #define directive:
- It can be used to define operators. Eg: #define OR ||
- It can be used to replace a condition. Eg:#define TAX (a>2.5 && a<4.5)
- It can be used to replace a C statement. Eg: #define TRUE printf(“The above statement is true”);
File Inclusion
This feature of C Preprocessor allows a programmer to include other files in the C code. #include is the command used to include another file or header into the program. But the question that arises her is why include files into our code?
This can be done for the following reasons:
- In the case of a complex program, the different parts of a program can be written in different files and then included in the main program. This reduces the possibility of errors in the code.
- it helps make our code modular. We write several programs which use a common file or functions or macro definitions then the same file can be included in the program without manually writing the whole function again and again which reduces errors in the code and possible inconvenience.
- In case we create library functions and make it accessible to others we need to create a filename with a .h extension which can be included in the program with minimal efforts.
- To include certain inbuilt header files we need this feature of C Preprocessor. (header files explained in detail in the next tutorial)
Conditional Compilation
This Preprocessor directive allows us to include or skip over a part of the source code by using the commands like #ifdef, #ifndef,#if, #elif, #else, #endif. Let’s have a look at the function of these conditional preprocessors:
- #ifdef : Results in true if preprocessor macro is defined.
- #ifndef : Results in true if preprocessor macro is not defined.
- #if : Results in true if the block of statements is true.
- #elif : Stands for ‘else if’.
- #else : Alternative for the #if block of statements.
- #endif : Ends the #if block of statement.
Here’s an example :
#include <stdio.h> #include <stdlib.h> #define NUM 10 int main() { int square, cube; #ifdef NUM square=NUM*NUM; printf("square is: %d",square); #else cube=NUM*NUM*NUM; printf("Cube is: %d",cube); #endif // NUM return 0; }
Output:- square is: 100
In this code we get the output as above because we have defined NUM at the beginning of the code. So, the #ifdef statement returns true and the block of statements under #ifdef gets executed.
In case we have other condition for the compilation of the code which evaluates to true, we use the #if preprocessor. The following example illustrates this :
#include <stdio.h> #include <stdlib.h> #define NUM 10 int main() { int square, cube; #if NUM>10 square=NUM*NUM; printf("square is: %d",square); #else cube=NUM*NUM*NUM; printf("Cube is: %d",cube); #endif return 0; }
Output:- cube is: 1000
Here the #if condition returns false and hence the block of statements under #else is executed.
Other Directives
The other preeprocessor directive available in C are:
- #undef : It is used to undefine a preprocessor macro. Eg: #undef NUM 10
- #error : Used to output an error message. Eg: #error “the error statement to be put here”
- #pragma : Used to instruct the compiler to use pragmatic or implementation-dependent features. It issues special commands to the compiler. They may differ for different compilers. Let’s have a look at the different #pragmas available for C:
The #Pragma Directive
- #pragma startup and #pragma exit: The #pragma startup directive allows us to call upon any function at the beginning, i.e., before the main() function. The #pragma exit directive allows us to call upon any function at the end of compilation,i.e., before termination . Eg: #pragma startup func1
- #pragma warn: This directive is used to turn on/off the warnings generated by the compiler. The ‘+’ before the warning turns the warning on, the ‘-‘ turns warning off and the ‘.’ sign toggles it. Eg: #pragma warn -par /*parameter not used*/
The ‘#’ operator
Wondering why we use ‘#’ before every preprocessor? Here’s your answer
‘#’ is the stringizing operator. In proper words, it coverts the macro preprocessor to string literals or text tokens.It is mostly used by macros with parameters or arguments. It is used to substitute macro parameters into macro body. The parameter shall be turned into a string ,i.e., enclosed within double quotes. The white spaces preceding the first token and following the last token shall be eliminated. More than one space between the tokens shall be considered as a single white space. Also if a comment line exists between the token it shall be reduced to a single space.
Below is an example of stringizing operator. Please try to understand it yourself and try it and believe me it will help you in better understanding. Still have some questions then do not forget to comment.
#include <stdio.h> #define STRINGIFY_(x) #x #define STRINGIFY(x) STRINGIFY_(x) #define STR "Hello! Welcome to " #define DOMAIN Codingeek #define S_DOMAIN STRINGIFY(DOMAIN) #define WELCOME_MSG STR S_DOMAIN int main() { //When we actually pass some value printf("%s",STRINGIFY(Hello)); // When it is pre calculated printf("\n%s",WELCOME_MSG); return 0; }
Output:- Hello Hello! Welcome to Codingeek
An investment in knowledge always pays the best interest. Hope you like the tutorial. Do come back for more because learning paves way for a better understanding.
Do not forget to share and Subscribe.
Happy coding!! 🙂
|
http://www.codingeek.com/tutorials/c-programming/preprocessors-in-c-programming/
|
CC-MAIN-2017-34
|
refinedweb
| 1,400
| 64.3
|
Support Vector Machines are supervised learning models which can be used for both classification and regression. SVMs are among the best supervised learning algorithms. It is effective in high dimensional space and it is memory efficient as well. Consider a binary classification problem, where the task is to assign a one of the two labels to given input. We plot each data item as a point in n-dimensional space as follows:
We can perform classification by finding the hyperplane that differentiate the two classes very well. As you can see in the above image, we can draw m number of hyperplanes. How do we find the best one? We can find the optimal hyperplane by maximizing the margin .
We define margin as a twice of the distance between the hyperplane and the nearest sample points to the hyperplane. This points are known as support vector. They known as support vectors because they hold up optimal hyperplane. In above figure, support vectors are represented with filled color. Consider a first hyperplane in figure-1 which touches the two sample points(red). Although it classifies all the examples correctly, but the problem is our hyperplane is close to the so many sample points and other red examples might fall on the other side of the hyperplane. This problem can be solved by choosing a hyperplane which is farthest away from the sample points. It turns out that this type of model generalize very well. This optimal hyperplane is also known as maximum margin separator.
We know that we want hyperplane with maximum margin and we also discussed why we want this. Now, let us learn how to find this optimal hyperplane? Before that, please note in case of SVMs, we represent class labels with +1 and -1 instead of 0 and 1(Binary Valued Labels). Here, we represent each hyperplane, the optimal one, negative and positive hyperplane(dashed lines) with linear equations - wTx + b = 0, wTx+b = -1 and wTx + b = +1 respectively. The left most dashed line is negative hyperplane. We represent red points with x- and blue points with x+. To derive the equation for a margin let us substract equations of negative and positive hyperplane from each other.
Adding length of the vector w to normalize this,
where, 2/||w|| is the margin. Now the objective of the SVM becomes maximization of the margin under the constraint that samples are classified correctly.
This can also be written more compactly as
In practice, it is easier to minimize the below given reciprocal term
This is the quadratic programming problem with the linear constraint.
In the case of inherently noisy data, we may not want a linear hyperplane in high-dimensional space. Rather, we'd like a decision surface in low dimensional space that does not clearly seperate the classes, but reflects the reality of the noisy data. That is possible with the soft margin classifier, which allows examples to fall on the wrong side of the decision boundary, but assigns them a penalty proportional to the distance required to move them back on the correct side. In soft margin classifier, we add slack variables to the linear constraint.
Now, our objective to minimize is
C is the regularization parameter. Small C allows constraint to be easily ignored and results in large margin whereas large C makes constraints hard to ignore and results in narrow margin. This is still a quadratic optimization problem and there is a unique minimum. Now let us implement linear SVM classifier in Python using sklearn. We will use iris dataset
#import the dependenciesfrom sklearn.datasets import load_irisfrom sklearn.svm import SVC#load datasetdataset = load_iris()data = dataset.datatarget = dataset.target
In machine learning, we always need to do some preprocessing to make our dataset suitable for the learning algorithm. I will introduce few preprocessing techniques as we go through various algorithms. Here, we will perform feature scaling which is required for optimal performance. Feature scaling is used to standardize the range of features of data.
from sklearn.preprocessing import StandardScalersc = StandardScaler()sc.fit_transform(data) #check out preprocessing module of sklearn to learn more about preprocessing in ML
Output:
array([[ -9.00681170e-01, 1.03205722e+00, -1.34127240e+00,-1.31297673e+00],[ -1.14301691e+00, -1.24957601e-01, -1.34127240e+00,-1.31297673e+00],[ -1.38535265e+00, 3.37848329e-01, -1.39813811e+00,-1.31297673e+00],[ -1.50652052e+00, 1.06445364e-01, -1.28440670e+00,-1.31297673e+00],[ -1.02184904e+00, 1.26346019e+00, -1.34127240e+00,-1.31297673e+00],......[ 1.03800476e+00, 5.69251294e-01, 1.10395287e+00,1.71090158e+00],[ 1.03800476e+00, -1.24957601e-01, 8.19624347e-01,1.44795564e+00],[ 5.53333275e-01, -1.28197243e+00, 7.05892939e-01,9.22063763e-01],[ 7.95669016e-01, -1.24957601e-01, 8.19624347e-01,1.05353673e+00],[ 4.32165405e-01, 8.00654259e-01, 9.33355755e-01,1.44795564e+00],[ 6.86617933e-02, -1.24957601e-01, 7.62758643e-01,7.90590793e-01]])
#now let us divide data into training and testing setfrom sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(data, target, random_state=42, test_size=0.3)#train a modelmodel = SVC()model.fit(X_train,y_train)
Output:
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,decision_function_shape=None, degree=3, gamma='auto', kernel='rbf',max_iter=-1, probability=False, random_state=None, shrinking=True,tol=0.001, verbose=False)
from sklearn.metrics import accuracy_scoreaccuracy_score(y_test, model.predict(X_test)) # Outputs: 1.0model.support_vectors_.shape # Outputs: (39, 4)model.support_vectors_
Output:
array([[ 5.1, 3.8, 1.9, 0.4],[ 4.8, 3.4, 1.9, 0.2],[ 5.5, 4.2, 1.4, 0.2],[ 4.5, 2.3, 1.3, 0.3],[ 5.8, 4. , 1.2, 0.2],[ 5.6, 3. , 4.5, 1.5],[ 5. , 2. , 3.5, 1. ],[ 5.4, 3. , 4.5, 1.5],[ 6.7, 3. , 5. , 1.7],[ 5.9, 3.2, 4.8, 1.8],[ 5.1, 2.5, 3. , 1.1],[ 6. , 2.7, 5.1, 1.6],[ 6.3, 2.5, 4.9, 1.5],[ 6.1, 2.9, 4.7, 1.4],[ 6.5, 2.8, 4.6, 1.5],[ 7. , 3.2, 4.7, 1.4],[ 6.1, 3. , 4.6, 1.4],[ 5.5, 2.6, 4.4, 1.2],[ 4.9, 2.4, 3.3, 1. ],[ 6.9, 3.1, 4.9, 1.5],[ 6.3, 2.3, 4.4, 1.3],[ 6.3, 2.8, 5.1, 1.5],[ 7.7, 2.8, 6.7, 2. ],[ 6.3, 2.7, 4.9, 1.8],[ 7.7, 3.8, 6.7, 2.2],[ 5.7, 2.5, 5. , 2. ],[ 6. , 3. , 4.8, 1.8],[ 5.8, 2.7, 5.1, 1.9],[ 6.2, 3.4, 5.4, 2.3],[ 6.1, 2.6, 5.6, 1.4],[ 6. , 2.2, 5. , 1.5],[ 6.3, 3.3, 6. , 2.5],[ 6.2, 2.8, 4.8, 1.8],[ 6.9, 3.1, 5.4, 2.1],[ 6.5, 3. , 5.2, 2. ],[ 7.2, 3. , 5.8, 1.6],[ 5.6, 2.8, 4.9, 2. ],[ 5.9, 3. , 5.1, 1.8],[ 4.9, 2.5, 4.5, 1.7]])
Till now, we see problems where input data can be separated by linear hyperplane. But what is data points are not linearly separable as shown below?
To solve this type of problems where data can not be seperated linearly, we add new feature. For example, let us add new feature z = x2 + y2. Now, if we plot data points on x and z axis we get :
As you can see, now we can have a linear hyperplane that can seperate data points very well. Do we need to add this additional feature manually? And the answer is no. We use the technique called Kernel Trick. Kernel trick is nothing but a set of functions which takes low-dimensional input space and transform it into high-dimensional space where data points are linearly seperable. These functions are called kernels. Widely used kernels are Radial Basis Function Kernel, Polynomial Kernel, Sigmoid kernel, etc.
Let us implement this in sklearn.
#we have already imported libs and datasetmodel2= SVC(kernel="rbf", gamma=0.2)model2.fit(X_train, y_train)model2.score(X_test, y_test)# Output: 1.0
We can have different decision boundary for different kernels and gamma values. Here is the screenshot from scikit-learn website.
|
https://www.commonlounge.com/discussion/17083a917de049908407bb8f5e32c9be
|
CC-MAIN-2020-10
|
refinedweb
| 1,399
| 64.2
|
Java Class File Naming Conventions
Last modified: March 30, 2021
1. Overview
When a Java class is compiled, a class file with the same name is created. However, in the case of nested classes or nested interfaces, it creates a class file with a name combining the inner and outer class names, including a dollar sign.
In this article, we'll see all those scenarios.
2. Details
In Java, we can write a class within a class. The class written within is called the nested class, and the class that holds the nested class is called the outer class. The scope of a nested class is bounded by the scope of its enclosing class.
Similarly, we can declare an interface within another interface or class. Such an interface is called a nested interface.
We can use nested classes and interfaces to logically group entities that are only used in one place. This not only makes our code more readable and maintainable, but it also increases encapsulation.
In the next sections, we're going to discuss each of these in detail. We'll also take a look at enums.
3. Nested Classes
A nested class is a class that is declared inside another class or interface. Any time we need a separate class but still want that class to behave as part of another class, the nested class is the best way to achieve it.
When we compile a Java file, it creates a .class file for the enclosing class and separate class files for all the nested classes. The generated class file for the enclosing class will have the same name as the Java class.
For nested classes, the compiler uses a different naming convention – OuterClassName$NestedClassName.class
First of all, let's create a simple Java class:
public class Outer { // variables and methods... }
3.1. Static Nested Classes
As the name suggests, nested classes that are declared as static are called static nested classes. In Java, only nested classes are allowed to be static.
Static nested classes can have both static and non-static fields and methods. They are tied to the outer class and not with a particular instance. Hence, we don’t need an instance of the outer class to access them.
Let's declare a static nested class within our Outer class:
public class Outer { static class StaticNested { public String message() { return "This is a static Nested Class"; } } }
When we compile our Outer class, the compiler creates two class files, one for Outer and another for StaticNested:
3.2. Non-Static Nested Classes
Non-static nested classes – also called inner classes – are associated with an instance of the enclosing class, and they can access all the variables and methods of the outer class.
An outer class can have only public or default access, whereas an inner class can be private, public, protected, or with default access. However, they can't contain any static members. Also, we need to create an instance of the outer class to access the inner class.
Let's add one more nested class to our Outer class:
public class Outer { class Nested { public String message() { return "This is a non-static Nested Class"; } } }
It generates one more class file:
3.3. Local Classes
Local classes, also called inner classes, are defined in a block — a group of statements between balanced braces. For example, they can be in a method body, a for loop, or an if clause. The scope of the local class is restricted within the block just like the local variables. Local classes, when compiled, appear as a dollar sign with an auto-generated number.
The class file generated for the local class uses a naming convention – OuterClassName$1LocalClassName.class
Let's declare a local class within a method:
public String message() { class Local { private String message() { return "This is a Local Class within a method"; } } Local local = new Local(); return local.message(); }
The compiler creates a separate class file for our Local class:
Similarly, we can declare a local class within an if clause:
public String message(String name) { if (StringUtils.isEmpty(name)) { class Local { private String message() { return "This is a Local class within if clause"; } } Local local = new Local(); return local.message(); } else return "Welcome to " + name; }
Although we're creating another local class with the same name, the compiler doesn't complain. It creates one more class file and names it with the number increased:
3.4. Anonymous Inner Classes
As the name suggests, anonymous classes are the inner classes with no name. The compiler uses an auto-generated number after a dollar sign to name the class file.
We need to declare and instantiate anonymous classes in a single expression at the same time. They usually extend an existing class or implement an interface.
Let's see a quick example:
public String greet() { Outer anonymous = new Outer() { @Override public String greet() { return "Running Anonymous Class..."; } }; return anonymous.greet(); }
Here, we've created an anonymous class by extending the Outer class, and the compiler added one more class file:
Similarly, we can implement an interface with an anonymous class.
Here, we're creating an interface:
interface HelloWorld { public String greet(String name); }
Now, let's create an anonymous class:
public String greet(String name) { HelloWorld helloWorld = new HelloWorld() { @Override public String greet(String name) { return "Welcome to "+name; } }; return helloWorld.greet(name); }
Let's observe the revised list of class files:
As we see, a class file is generated for the interface HelloWorld and another one for the anonymous class with the name Outer$2.
3.5. Inner Class Within Interface
We have seen class inside another class, further, we can declare a class within an interface. If the functionality of class is closely associated with interface functionality, we can declare it inside the interface. We can go for this inner class when we want to write the default implementation for interface methods.
Let's declare an inner class inside our HelloWorld interface:
interface HelloWorld { public String greet(String name); class InnerClass implements HelloWorld { @Override public String message(String name) { return "Inner class within an interface"; } } }
And the compiler generates one more class file:
4. Nested Interfaces
Nested interfaces, also known as inner interfaces, are declared inside a class or another interface. The main purpose of using nested interfaces is to resolve the namespace by grouping related interfaces.
We can't directly access nested interfaces. They can only be accessed using the outer class or outer interface. For example, the Entry interface inside the Map interface is nested and can be accessed as Map.Entry.
Let's see how to create nested interfaces.
4.1. Interface Inside an Interface
An interface declared inside the interface is implicitly public.
Let's declare our interface inside the HelloWorld interface:
interface HelloWorld { public String greet(String name); interface HelloSomeone{ public String greet(String name); } }
This will create a new class file named HelloWorld$HelloSomeone for the nested interface.
4.2. Interface Inside a Class
Interfaces declared inside the class can take any access modifier.
Let's declare an interface inside our Outer class:
public class Outer { interface HelloOuter { public String hello(String name); } }
It will generate a new class file with the name: OuterClass$StaticNestedClass
5. Enums
The enum was introduced in Java 5. It's a data type that contains a fixed set of constants, and those constants are the instances of that enum.
The enum declaration defines a class called an enum type (also known as enumerated data type). We can add many things to the enum like a constructor, methods, variables, and something called a constant-specific class body.
When we create an enum, we're creating a new class, and we’re implicitly extending the Enum class. Enum cannot inherit any other class or can't be extended. However, it can implement an interface.
We can declare an enum as a standalone class, in its own source file, or another class member. Let's see all the ways to create an enum.
5.1. Enum as a Class
First, let's create a simple enum:
enum Level { LOW, MEDIUM, HIGH; }
When it is compiled, the compiler will create a class file with the name Level for our enum.
5.2. Enum Within a Class
Now, let's declare a nested enum in our Outer class:
public class Outer { enum Color{ RED, GREEN, BLUE; } }
The compiler will create a separate class file named Outer$Color for our nested enum.
5.3. Enum Within an Interface
Similarly, we can declare an enum within an interface:
interface HelloWorld { enum DIRECTIONS { NORTH, SOUTH, EAST, WEST; } }
When the HelloWorld interface is compiled, the compiler will add one more class file named HelloWorld$Directon.
5.4. Enum Within an Enum
We can declare an enum inside another enum:
enum Foods { DRINKS, EATS; enum DRINKS { APPLE_JUICE, COLA; } enum EATS { POTATO, RICE; } }
Finally, let's take a look at the generated class files:
The compiler creates a separate class file for each of the enum types.
6. Conclusion
In this article, we saw different naming conventions used for Java class files. We added classes, interfaces, and enums inside a single Java file and observed how the compiler creates a separate class file for each of them.
As always, the code examples for this article are available over on GitHub.
|
https://www.baeldung.com/java-class-file-naming
|
CC-MAIN-2021-43
|
refinedweb
| 1,556
| 60.85
|
Scroll down to the script below, click on any sentence (including terminal blocks!) to jump to that spot in the video!
gstreamer0.10-ffmpeg
gstreamer0.10-plugins-goodpackages.
To use Vue, we, of course, need to install it in our app. And, because we're using modern JavaScript practices, we're not going to include a
script tag to a CDN or manually download Vue. We're going to install it with yarn.
But first, in addition to downloading Vue into our project, we also need to teach Webpack how to parse
.vue files. Like React, Vue uses some special - not-actually-JavaScript - syntaxes, which Webpack needs to transform into real JavaScript.
To tell Webpack to parse vue files, open
webpack.config.js. Near the bottom, though it doesn't matter where, add
.enableVueLoader().
Yep! That's all you need. If you want to use Vue 3, you can pass an extra argument with a
version key set to 3. Eventually, 3 will be the default version that Encore uses.
And, even though Encore is watching for changes, whenever you update
webpack.config.js, you need to stop and restart Encore. I'll hit Control+C and then re-run:
yarn watch
When we do this... awesome! Encore is screaming at us! To use Vue, we need to install a few packages. Copy the
yarn add line, paste and run it:
yarn add vue@^2.5 vue-loader@^15 vue-template-compiler --dev
Once these are done downloading, restart Encore again with:
yarn watch
It works! Nothing has really changed yet, but Encore is ready for Vue.
In the simplest sense, Vue is a templating engine written in JavaScript. That over-simplifies it... but it's more or less true. In Symfony, if you go back to
ProductController, we're accustomed to using Twig. It's easy: we tell it what template to render and we can pass variables into that template.
The Twig file itself is just HTML where we have access to a few Twig syntaxes, like
{{ variableName }} to print something.
Vue works in much the same way: instead of Twig rendering a template with some variables, Vue will render a template with some variables. And the end-result will be the same: HTML. Of course, the one extra super power of Vue is that you can change the variables in JavaScript, and the template will automatically re-render.
So instead of rendering this markup in Twig, delete all of it and just add
<div id="app">. That
id could be anything: we're creating an empty element that Vue will render into.
Now, what we're building will not be a single page application, and that's on purpose. Using Vue or React inside of a traditional web app is actually trickier than building a single page application. On our site, the homepage will soon contain a Vue app... but the layout - as you can see - is still rendered in Twig. We also have a login page which is rendered completely with Twig and a registration page that's the same. We'll purposely use Vue for part of our site, but not for everything... at least not in this tutorial.
Go back and open
webpack.config.js again. This has one entry called
app. The purpose of
app is to hold any JavaScript or CSS that's used across our entire site, like to power the layout. We actually don't have any JavaScript, but the
app.scss contains the CSS for the body, header and other things. The
app script and link tags are included on every page.
But, our Vue app isn't going to be used on every page. So instead of adding our code to
app.js, let's create a second entry and include it only on the pages that need our Vue app.
Copy the first
addEntry() line, paste, and rename it to
products - because the Vue app will eventually render an entire product section: listing products, viewing one product and even a cart and checkout in the next tutorial.
Now, in
assets/js, create that file:
products.js. Let's start with something exciting: a
console.log():
Boring JavaScript file: make me cooler!
Oh, we will. But before we do, I'm going to open my PhpStorm settings and search for
ESLint. Make sure "Automatic ESLint configuration" is selected. Because... I've already added a
.eslintrc config file to the app. ESLint enforces JavaScript coding standards and PhpStorm can automatically read this and highlight our code when we mess something up. I love it! We're using a few basic rule sets including one specifically for Vue. You definitely don't need to use this exact setup, but I do recommend having this file.
Back in
products.js, ha! Now PhpStorm is highlighting
console:
Unexpected console statement (
no-console)
One of our rules says that we should not use
console because that's debugging code. Of course, we are debugging right now, so it's safe to ignore.
Ok: we added a new entry and created the new file. The last step is to include the
script tag on our page. Open up
templates/product/index.html.twig. Here, override a block called
javascripts, call
parent() and then I'll use an Encore function -
encore_entry_script_tags() - to render all the script tags needed for the
products entry.
If you look in the base template -
base.html.twig - it's quite traditional: we have a
block stylesheets on top and a block
javascripts at the bottom.
Back in our template, also override the
stylesheets block and call
encore_entry_link_tags. Eventually, we'll start using CSS in our
products entry. When we do, this will render the link tags to the CSS files that Encore outputs.
Before we try this - because we just updated the
webpack.config.js file - we need to restart Encore one more time:
yarn watch
When that finishes, move back over, refresh... then open your browser's debug tools. Got it! Our boring JavaScript file is alive!
Let's... make it cooler with Vue! Back in
products.js, start by importing Vue:
import vue from 'vue'. This is one of the few parts that will look different in Vue 3 - but the ideas are the same.
If you imagine that Vue is a templating engine - like Twig - then all we should need to do is pass Vue some template code to render. And... that's exactly what we're going to do. Add
const app = new Vue() and pass this some options. The first is
el set to
#app. That tells Vue to render inside of the
id="app" element. Then, pass one more option:
template. This is the HTML template - just like a Twig template - except that, for now, we're going to literally add the HTML right here, instead of in a separate file:
<h1>Hello Vue!Is this cooler?</h1>
That's... all we need! Moment of truth: find your browser and refresh. There it is! We just built our first Vue app in about 5 lines of code.
Next, let's make it more interesting by passing variables to the template and witnessing Vue's awesomeness first hand.
// } }
|
https://symfonycasts.com/screencast/vue/vue-install
|
CC-MAIN-2021-31
|
refinedweb
| 1,203
| 76.11
|
- 11 Mar, 2016 40 commits
It's unclear how these blank values got added, but GitLab.com had a few: ``` irb(main):002:0> Note.where("line_code IS NOT NULL AND line_code = ''").count => 439 ``` We've added a migration to convert any existing records to use a NULL value when blank, and updated Note to set blank values to nil before validation.
Refactor searching and use PostgreSQL trigram indexes for significantly improved performance Related issue:. Also fixes #12410 See merge request !2987
This explains the user what they need to run and where to go in case they want to learn more about "CREATE EXTENSION".
The OR condition for source_project_id/target_project_id leads to a query plan that performs rather poorly on PostgreSQL due to the use of sub-queries. Because Rails offers no easy alternative for this particular problem we're forced to using a UNION for both conditions. The resulting query performs much faster than just using an OR.
This ensures searching namespaces works exactly the same as searching for any other resource.
We can just use "arel_table" in these cases instead of "SomeClass.arel_table".
We don't need the extra layer of nesting of UNION queries here (as User#authorized_projects already returns a UNION'd query).
There's no need to order queries used as sub-queries and doing so can add potential overhead.
This ensures some other methods such as the "issues" method still work.
This spec was still passing an ID to the #initialize method instead of a Project instance.
This code is mostly a copy-paste from existing pull requests so there's no point in running Rubocop on it.
This ensures that options such as `using: :gin` and PostgreSQL operator classes are ignored when loading a schema into a MySQL database.
This also includes e.g. the appearances table which apparently wasn't already included in the schema.
This is needed to support creating/dumping/loading indexes that use the gin_trgm_ops operator class on PostgreSQL. These changes are taken from Rails pull request.
Previously this class would be given a project ID which was then used to retrieve the corresponding Project object. However, in all cases the Project object was already known as it was used to grab the ID to pass to ProjectSearchResults. By just passing a Project instead we remove the need for an extra query as well as the need for some other complexity in this class.
This removes the need for plucking snippet IDs into memory.
Instead of plucking IDs this class now uses ActiveRecord::Relation objects. Plucking IDs is problematic as searching for projects can lead to a huge amount of IDs being loaded into memory only to be used as an argument for another query (instead of just using a sub-query).
Previously this used a regular LIKE which is case-sensitive on PostgreSQL. This ensures that for both PostgreSQL and MySQL the searching is case-insensitive similar to searching for projects.
Similar to the changes made to Project.search the method Project.search_by_title now also uses Arel so it can automatically use ILIKE/LIKE instead of the lower() function.
This chance is broken up in two steps: 1. Use ILIKE on PostgreSQL and LIKE on MySQL, instead of using "WHERE lower(x) LIKE lower(y)" as ILIKE is significantly faster than using lower(). In many cases the use of lower() will force a slow sequence scan. 2. Instead of using 1 query that searches both projects and namespaces using a JOIN we're using 2 separate queries that are UNION'd together. Using a JOIN would force a slow sequence scan, using a UNION avoids this. This method now uses Arel as Arel automatically uses ILIKE on PostgreSQL and LIKE on MySQL, removing the need to handle this manually.
This allows the LIKE condition to use an index. Without a GIN + trigram index LIKE queries using a wildcard at the start _won't_ use an index and instead perform a sequence scan.
Move group activity feed to separate page for consistency with dashboard and project pages Fixes #14161. Part of #13480 See merge request !3157
- Achilleas Pipinellis authored
Fix incorrect gitlab.rb variable in CI docs Fixes See merge request !3187
- Achilleas Pipinellis authored
[ci skip]
- Jacob Schatz authored
Improved search results filter dropdown ## Current Currently filter dropdowns on search results page can be **very** long and off the page ## New Changed over to the new dropdown See merge request !3183
- Patricio Cano authored
Upgrade `omniauth-saml` to 1.5.0 and document it's new capabilities. With this MR I'm upgrading `omniauth-saml` to 1.5.0 to include new and improved functionality. See for more details. This MR includes new documentation, so @axil can you also take a look? /cc @DouweM See merge request !3170
- Patricio Cano authored
[ci skip]
- Jacob Schatz authored
Updated UI of award emoji Closes #13878 See merge request !3028
|
https://foss.heptapod.net/heptapod/heptapod/-/commits/01f6db4f643380d143772958b22d3f318b1db3a7
|
CC-MAIN-2022-40
|
refinedweb
| 820
| 65.32
|
On Wed, Nov 14, 2012 at 1:11 AM, SZEDER Gábor <sze...@ira.uka.de> wrote: > On Tue, Nov 13, 2012 at 07:31:45PM +0100, Felipe Contreras wrote: >> On Mon, Nov 12, 2012 at 9:07 PM, Marc Khouzam <marc.khou...@gmail.com> wrote: >> > + # Call _git() or _gitk() of the bash script, based on the first >> > + # element of the command-line >> > + _${COMP_WORDS[0]} >> >> You might want to use __${COMP_WORDS[0]}_main instead. > > That wouldn't work. __git_main() doesn't set up the > command-line-specific variables, but the wrapper around it does.
Advertising
Yeah, but you can set those command-line-specific variables manually, like the zsh completion wrapper does. The problem with the _git wrapper is that it will call the bash-specific complete command. >> > +# Make the script executable if it is not >> > +if ( ! -x ${__git_tcsh_completion_script} ) then >> > + chmod u+x ${__git_tcsh_completion_script} >> > +endif >> >> Why not just source it? > > The goal is to re-use a Bash script to do completion in tcsh. They > are two different breeds, tcsh doesn't grok bash. So sourcing the > completion script is not an option, but we can still run it via Bash > and use it's results. I see, but the tcsh script can do something like this: bash <<\EOF echo $BASH \EOF Cheers. -- Felipe Contreras -- 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/msg12100.html
|
CC-MAIN-2016-44
|
refinedweb
| 241
| 65.62
|
Hi to everyone,
I am new to CUDA computing and I would like to ask a question the more experienced members about double precision in the CUDA 2.3 environment. First of all I have a GTX295 card which, according to the CUDA programming guide, supports compute capability 1.3, meaning that it supports double precision numbers. Also I am using the nvcc compiler through the Microsoft developer studio 2008 (actually the code is built using a one of the SDK sample programs as a template).
So I was experiencing with a simple code, which can be found here (…t-cuda-program/ ), I have modified it a bit as following (in short I have changed the way the matrix a_h is allocated and the array elements that have to be calculated):
#include <stdio.h>
#include <cuda.h>
// Kernel that executes on the CUDA device
global void square_array(float *a, int N)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
a[idx] = a[idx] * a[idx];
}
// main routine that executes on the host
int main(void)
{
float *a_h=new float 60;
float *a_d; // Pointer to host & device arrays
const int N = 60; //2;
cudaMemcpy(a_d, a_h, size, cudaMemcpyHostToDevice);
// Do calculation on device:
int nblocksize=500;
int Nblocks=N/nblocksize+ (N%nblocksize == 0 ? 0 : 1);
square_array <<< Nblocks, nblocksize >>> (a_d, N);
// Retrieve result from device and store it in host array
cudaMemcpy(a_h, a_d, size, cudaMemcpyDeviceToHost);
// Print results
for (int i=0; i<N; i++) printf("%d %f\n", i, a_h[i]);
// Cleanup
delete a_h; cudaFree(a_d);
}
So when I run the executable the program works as it should since it gives the correct results. But when I replace all float declarations to double, then I get a warning :
warning : Double is not supported. Demoting to float
Also the results are wrong (to be precise it is like the array elements were never processed by the device, since what is printed is just the elements intialized by the host). Why do I get the warning and the error results ? Do I miss anything here?
Thanks in advance.
|
https://forums.developer.nvidia.com/t/double-precision-in-cuda-2-3/11514
|
CC-MAIN-2020-29
|
refinedweb
| 344
| 57
|
#include <smartptr.h>
Inheritance diagram for ParentPtr:
If ObjectA has a smart pointer to ObjectB it shares ownership of it (and so ObjectA is a parent of ObjectB). A child may not hold a smart pointer to a parent (or grand-parent etc.) otherwise a loop will be formed and these objects will never be deleted. Child objects may reference parents using ParentPtr.
Construct a parent pointer that points to nothing.
Construct a parent pointer from a smart pointer.
Construct a parent pointer to an object.
Copy construct.
Destructor clears the pointer without decrementing the count.
Set value from a parent pointer.
Set value from a pointer.
Clear the recorded value of this pointer.
Clear the recorded value of this pointer.
This call does not remove us from the parent's list of parent pointers (called by the parent)
|
http://www.freemxf.org/mxflib-docs/mxflib-1.0.0-docs/classmxflib_1_1_parent_ptr.html
|
CC-MAIN-2013-20
|
refinedweb
| 139
| 69.28
|
Simplifying low latency servicesA way to model the service is to have an interface for the methods/requests/events you want to support and another interface for events out of the processing engine. A demo has been added to demonstrate this approach. Processing Engine Demo with Chronicle A simple request to pass to the processing engine from the gateway. You can have any number of arguments and use primitives instead of command objects, but we are trying to be simple here rather than ultra fast.
public interface Gw2PeEvents { public void small(MetaData metaData, SmallCommand command); } public class SmallCommand implements ExcerptMarshallable { public StringBuilder clientOrderId = new StringBuilder(); public String instrument; public double price; public int quantity; public Side side;A simple response per request is as follows
public interface Pe2GwEvents { public void report(MetaData metaData, SmallReport smallReport); } public class SmallReport implements ExcerptMarshallable { public CharSequence clientOrderId = new StringBuilder(); public ReportStatus status; public CharSequence rejectedReason = new StringBuilder();The MetaData class wraps the timestamps for the end to end process. It records a tenth of micro-second time stamp for when
- the request is written
- the request is read
- the response is written
- the response is read.
- Includes a sourceId and eventId triggering the response, needed for restart
How does it perform?The throughput on a 3.8 GHz i7 with two gateways producing 10 million inbound and 10 million outbound messages each took 12.2 second to return to the gateways which sent them or 1.6 millon request/responses per second. For 200 million messages the speed of the SSDs starts to matter as disk cache size is exceeded and the performance dropped to 200 million in 176 seconds or 1.1 million per second. The critical latencies to look at are not the average or typical latencies but the higher percentiles. In this test, the 90th, 99th and 99.9th percentiles (worst 10%, 1% and 0.1%) were 3.3 µs, 4.9 µs, 9.8 µs. Under higher load with 200 million request and 200 million responses, a burst exceeding the main memory size, the latencies increased to 4.2 µs, 6.8 µs, and 28.8 µs There are very few systems which can handle bursts of activity which exceed the main memory size, without dropping in performance too much. (1.5x to 3x worse) If you run this test with -verbosegc you may see a minor GC on startup with a small heap size of 16 MB, however the demo is designed to create less than one object per request/response and you don't get additional GCs. Note: this test didn't include a warm up to make the numbers more representative of what you might see in a real application. i.e. worse than a micro-benchmark usually shows.
What does the memory profile look like?The memory profile is basically flat. If you look at the processes with VisualVM you will see the memory used to poll the process (i.e. it's the same as when you are not doing anything) If you use -XX:-UseTLAB for more accurate memory usage and jstat -gccapacity it doesn't show any memory usage for 200 million request and responses. This is not correct as Chronicle does use some heap but jstat only shows page usage (multiples of 4 KB) i.e. the usage is less than 4 KB.
What is ExcerptMarshallable?This interface is basically the same as Externalizable, however it supports all of Excerpts functionality for improved performance and make the stream more compact. Given services can be limited by you disk sub-system memory bandwidth when you have large bursts of data, this can matter. Compared with Externalizable in real programs you might expect to have half of the data serialized and double the throughput. ExcerptMarshallable is designed to support object recycling. A large percentage of the cost of de-serialization is having to create new objects which fills your CPU caches with garbage slowing down your whole program, not just the de-serialization code but all the code running on the same socket (including other programs on that socket)
When you consider it is recording every message sent including detailed 0.1 µs time stamp, you are getting a lot of support for very accurate tracing of the timings with very little cost to the application.While coding for Chronicle to get maximum performance is very low level, too low level for most developers, you can still get very good performance with higher level designs which make it easier to use. Summary of performance
-
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)
|
http://java.dzone.com/articles/simplifying-low-latency
|
CC-MAIN-2014-35
|
refinedweb
| 782
| 53.1
|
Conditional filtering of pandas data frame
I have a pandas data frame about football results. Each row of the dataframe represents a football match. The information of each match are:
Day | WinningTeamID | LosingTeamID | WinningPoints | LosingPoints | WinningFouls | ... | 1 13 1 45 5 3 1 12 4 21 12 4
That is, the information are divided based on the game result: winning or losing. I would like to retrieve the data of each game for a specific team (e.g. 12).
Day | Points | Fouls | ... | 1 21 4 ... 2 32 6 ...
The simplest way is to scan the whole dataframe, check if a specific teamID is on WinningID or LosingID and then, based on that, retrieve the "Losing-columns" or the "Winning-columns". Is there a more "elegant" way of slicing the pandas dataframe? This will simply give me the subset of matches where the team 12 is involved.
df[df[WinningTeamID == 12] | [LosingTeamID == 12]]
How can I filter those data and create the desired dataframe?
2 answers
- answered 2017-06-17 18:25 unutbu
Suppose we could choose the format of the data. What would be ideal? Since we want to collect stats per
TeamID, ideally we would have a column of
TeamIDs and separate columns for each stat including the outcome.
So the data would look like this:
| Day | Outcome | TeamID | Points | Fouls | | 1 | Winning | 13 | 45 | 3 | | 1 | Losing | 1 | 5 | NaN | | 1 | Winning | 12 | 21 | 4 | | 1 | Losing | 4 | 12 | NaN |
Here is how we can manipulate the given data into the desired form:
import numpy as np import pandas as pd df = pd.DataFrame({'Day': [1, 1], 'LosingPoints': [5, 12], 'LosingTeamID': [1, 4], 'WinningFouls': [3, 4], 'WinningPoints': [45, 21], 'WinningTeamID': [13, 12]}) df = df.set_index(['Day']) columns = df.columns.to_series().str.extract(r'^(Losing|Winning)?(.*)', expand=True) columns = pd.MultiIndex.from_arrays([columns[col] for col in columns], names=['Outcome', None]) df.columns = columns df = df.stack(level='Outcome').reset_index() print(df)
yields
Day Outcome Fouls Points TeamID 0 1 Losing NaN 5 1 1 1 Winning 3.0 45 13 2 1 Losing NaN 12 4 3 1 Winning 4.0 21 12
Now we can obtain all the stats about
TeamID12 using
print(df.loc[df['TeamID']==12]) # Day Outcome Fouls Points TeamID # 3 1 Winning 4.0 21 12
df = df.set_index(['Day'])moves the
Daycolumn into the index.
The purpose of placing
Dayin the index is to "protect" it from manipulations (primarily the
stackcall) that are intended only for columns labeled
Losingor
Winning. If you had other columns, such as
Locationor
Officialswhich, like
Day, do not pertain to
Losingor
Winning, then you'd want to include them in the
set_indexcall too: e.g.
df = df.set_index(['Day', 'Location', 'Officials']).
Try commenting out
df = df.set_index(['Day'])from the code above. Then step through the code line-by-line. In particular, compare what
df.stack(level='Outcome')looks like with and without the
set_indexcall:
With
df = df.set_index(['Day']):
In [26]: df.stack(level='Outcome') Out[26]: Fouls Points TeamID Day Outcome 1 Losing NaN 5 1 Winning 3.0 45 13 Losing NaN 12 4 Winning 4.0 21 12
Without
df = df.set_index(['Day']):
In [29]: df.stack(level='Outcome') Out[29]: Day Fouls Points TeamID Outcome 0 NaN 1.0 3.0 45 13 Losing NaN NaN 5 1 Winning 1.0 3.0 45 13 1 NaN 1.0 4.0 21 12 Losing NaN NaN 12 4 Winning 1.0 4.0 21 12
Without the
set_indexcall you end up with rows that you do not want -- the rows where
Outcomeequals
NaN.
The purpose of
columns = df.columns.to_series().str.extract(r'^(Losing|Winning)?(.*)', expand=True) columns = pd.MultiIndex.from_arrays([columns[col] for col in columns], names=['Outcome', None])
is to create a multi-level column index (called a MultiIndex) which labels columns
Losingor
Winningas appropriate. Notice that by separating out the
Losingor
Winningparts of the labels, the remaining parts of the labels become duplicated.
We end up with a DataFrame,
df, with two columns labeled "Points" for example. This allows Pandas to identify these columns as somehow similar.
The big gain -- the reason why we went through the trouble of setting up the MultiIndex is so that these "similar" columns can be "unified" by calling
df.stack:
In [47]: df Out[47]: Outcome Losing Winning Points TeamID Fouls Points TeamID Day 1 5 1 3 45 13 1 12 4 4 21 12 In [48]: df.stack(level="Outcome") Out[48]: Fouls Points TeamID Day Outcome 1 Losing NaN 5 1 Winning 3.0 45 13 Losing NaN 12 4 Winning 4.0 21 12
stack,
unstack,
set_indexand
reset_indexare the 4 fundamental DataFrame reshaping operations.
df.stackmoves a level (or levels) of the column MultiIndex into the row index.
df.unstackmoves a level (or levels) of the row index into the column index.
df.set_indexmoves column values into the row index
df.reset_indexmoves a level (or levels) of the row index into a column of values
Together, these 4 methods allow you to move data in your DataFrame anywhere you want -- in the columns, the row index or the column index.
The above code is an example of how to use these tools (well, two of the four) to reshape data into a desired form.
- answered 2017-06-17 18:25 Ajay Ohri
df.query['WinningTeamID == 12 | LosingTeamID == 12']
|
http://codegur.com/44608005/conditional-filtering-of-pandas-data-frame
|
CC-MAIN-2018-09
|
refinedweb
| 899
| 67.15
|
choose, because API levels are backward compatible, you can run an app with a lower API level on a device with a higher API level..
- Complete one of the following:
- In Windows and Linux, on the Window menu, click Preferences.
- In Mac OS, on the Momentics menu, click Preferences.
- Expand BlackBerry, and then then click Properties.
- Click BlackBerry API Level and select the API level that your project supports from the drop-down list.
- Click Apply, and then.
Control app flow based on API level
In most cases, you select the API level that includes all the functionality required by your app and build one executable that works on devices running that level and later. In certain cases, you might want to produce versions for different API levels. You can use one code base to produce binaries for different API levels by using the macros from bbndk.h to control which code is used for each version.
The BBNDK_VERSION_CURRENT macro contains the API level of the project that you're working on. The BBNDK_VERSION_AT_LEAST(major,minor,patch) macro tests if the (major,minor,patch) API level is at least as high as that of BBNDK_VERSION_CURRENT. You can use these macros in your app's logic to control what to do, based on the API level. For example, suppose you're building an app that has separate versions built for different OS levels. The following code sample shows how to use the BBNDK_VERSION_AT_LEAST(major,minor,patch) macro to control application logic.
#ifdef BBNDK_VERSION_AT_LEAST #if BBNDK_VERSION_AT_LEAST(10,3,0) // Add logic used by the 10.3.0+ binary here #elif BBNDK_VERSION_AT_LEAST(10,2,1) // Add logic used by the 10.2.1+ binary here #else // Add logic used by the 10.0.0+ binary here #endif #endif
In the code sample above, running the app built using a 10.3.0 API level executes the first set of logic, running the app that was built using a 10.2.1 API level runs the second set of logic, and running the app built using an API level below 10.2.1 runs the final set of logic.
Last modified: 2015-07-24
Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
|
http://developer.blackberry.com/native/documentation/dev/tools/api_levels.html
|
CC-MAIN-2019-35
|
refinedweb
| 376
| 66.03
|
Kevin Dangoor wrote:
(...)
> SQLiteConnection can be patched to add an optional encoding parameter.
> Does that seem like something folks would want? If not, maybe I could
> subclass SQLiteConnection and redo __init__ to open a unicode
> connection.
i second the first option, in MySQLdb too there's a connect
param named "unicode" where user can specify preferred codec.
from the 1.1.8 connections.Connection.__init__ doc:
unicode -- If set to a string, character columns are returned as
unicode objects with this encoding. If set to None, the
default encoding is used. If not set at all, character
columns are returned as normal strings.
and there's also a:
unicode_errors -- If set to a string, this is used as the errors
parameter to the unicode function; by default it is
'strict'. See documentation for unicode for more details.
maybe normalize the param name across all the adapters that
accepts a way to specify a codec upon connection would not hurt
either.
bye
I'm using SQLite with SQLObject 0.6, and I need to store and retrieve
unicode values. From my testing, I can get PySQLite to do unicode like
so:
def test_unicodeGoesInUnicodeComesOut(self):
cx = sqlite.connect(":memory:", encoding="utf-8")
cu = cx.cursor()
cu.execute("create table test(myfield unicode)")
cu.execute(u"insert into test values (%s)", (u"\x99sterreich",))
cu.execute("select * from test")
value = cu.fetchone()[0]
assert type(value) == unicode
(This is almost straight out of the PySQLite doc... I wanted to get it
confirmed in a test in my code).
The first problem is the SQLiteConnection does not provide a way for
me to set the encoding for the connection. I've tested this, and it is
required in order to successfully do unicode in both directions.
The second problem is that the column type needs to be unicode. If
it's just "text", PySQLite returns standard strings.
SQLiteConnection can be patched to add an optional encoding parameter.
Does that seem like something folks would want? If not, maybe I could
subclass SQLiteConnection and redo __init__ to open a unicode
connection.
For the second problem, I spotted a fairly recent thread
()
even with code ()
about making a unicode column. It also appears that there will be a
unicode column in 0.6.1. It seems like the main thing I need is to set
the column type.
My app is not going to be in production for a couple of months, so I
don't mind using alpha or beta code. I'm just looking for the "right"
way to do this in the context of SQLObject.
Thanks,
Kevin
|
http://sourceforge.net/p/sqlobject/mailman/message/9071501/
|
CC-MAIN-2014-49
|
refinedweb
| 433
| 67.55
|
Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
3 years, 8 months ago.
C++ std::list memory problem using the ARM compiler, allocator question
I have the following C++ code which works fine with the GCC compiler but does needs 4624 bytes memory using the ARM online compiler for a single entry in the _myrecs list. Which is way too much for a single 36 byte record.
list sample code
#include "mbed.h" #include <list> struct TestRec { uint32_t lastTxSize; int tmp[32]; }; main { struct TestRec rc; list<TestRec> _myrecs; _myrecs.push_back(rc); // __heapstats((__heapprt)mprintf, stdout); // __heapvalid((__heapprt)mprintf, stdout, 1); for(;;) ; }
I was running out of memory therefore I investigated into it using the heapstats feature. Any ideas what can be done. I have four different lists in my solution. I believe there is an default allocator which pre-allocates 100 entries or so.
Any help is appreciated, thanks Helmut
1 Answer
3 years, 8 months ago.
Consider using either an array, or a linked list for example (), or something else which meets your requirements.
Those standard C++ things like list and also vector take a ton of space. Apparently less with GCC, but probably still alot.
Hi Eric thank you for the advise, I use C++ lists and maps because they are efficient and part of the C++ language available on all platforms/compilers. They are also good documented. I have a project with a 20kB STM MCU and it works quite well, only the ARM compiler has a different allocation problem as described. Maybe some ARM engineers give advise on it. I can also open a case with Keil for by MDK which under support. PS: In code size of the ARM compiler is way better then gcc, however in this case gcc runtime lib is better.posted by 20 Aug 2017
Do you know roughly how many objects are going to be pushed to this list? Also, I am curious to see if you see similar sizing results when explicitly creating a list of one element, std::list<TestRec> _myrecs(1, TestRec(), std::allocator<TestRec>());posted by Michael Bartling 22 Aug 2017
Hi Michael, I will look into this and update this post.posted by Helmut Tschemernjak 24 Aug 2017
Dear Michael, I found the source of the problem after debugging it within MDK for a while. The default _RWSTD_MINIMUM_NEW_CAPACITY is 32 (in _defs.h) causes the excessive memory usage, as I have few entries only I added the following defines before I include the mbed, etc. headers:
The resolves the problem.posted by Helmut Tschemernjak 02 Sep 2017
Glad to hear the problem has been resolved!posted by Michael Bartling 06 Sep 2017
|
https://os.mbed.com/questions/78855/C-stdlist-memory-problem-using-the-ARM-c/
|
CC-MAIN-2021-21
|
refinedweb
| 468
| 64.41
|
X11 Version and Manager.h ??
Expand Messages
- Which Version of X11 should we be using
X11R6 OR X11R66 ??
Manager.h Does Not exist in X11R6
--
You received this message from the "vim_dev" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit
- Thanks Very Much for your response
I am building the Motif version
I built this successfully in December
I guess much has changed since December :)
-----Original Message-----
From: Tony Mechelynck [mailto:antoine.mechelynck@...]
Sent: Friday, April 27, 2012 6:06 PM
To: vim_dev@...
Cc: Bovy, Stephen
Subject: Re: X11 Version and Manager.h ??
On 28/04/12 01:23, Bovy, Stephen wrote:
> Which Version of X11 should we be using
>
> X11R6 OR X11R66 ??
>
> Manager.h Does Not exist in X11R6
>
There is no X11R66 yet. "Releases 6.7 and later are brought to you by the X.Org Foundation." (sic, from the X(7) manpage installed here). The version currently distributed with the current openSUSE Linux distro + all Online Updates is 7.6 (i.e., sub-version 6 of X11R7).
I see the line
# include <Xm/Manager.h>
only once in the source, at src/gui_xmebw.c line 33, and ifdef'fed as
follows:
26: #ifdef FEAT_TOOLBAR
30: #if defined(HAVE_XM_TRAITP_H) && defined(HAVE_XM_MANAGER_H) \
31: && defined(HAVE_XM_UNHIGHLIGHTT_H) && defined(HAVE_XM_XPMP_H)
If FEAT_TOOLBAR is unset the whole gui_xmebw.c is skipped, except for an #include "vim.h".
The more complex #if has an #else branch with only
38: # include <X11/xpm.h>
in it.
That gui_xmebw module is not compiled into my GTK2/Gnome2 gvim; it seems to be part of the Motif GUI.
As a temporary stopgap measure, you can try to remove
defined(FEAT_GUI_MOTIF) ||
at line 760 of src/feature.h; but a better fix would be to find what is wrong with your Motif packages, or maybe use a different GUI.
Best regards,
Tony.
--
A Riverside, California, health ordinance states that two persons may
not kiss each other without first wiping their lips with carbolized
rosewater.
--
You received this message from the "vim_dev" maillist.
Do not top-post! Type your reply below the text you are replying to.
For more information, visit
Your message has been successfully submitted and would be delivered to recipients shortly.
|
https://groups.yahoo.com/neo/groups/vimdev/conversations/topics/64949?viscount=-30&l=1
|
CC-MAIN-2015-27
|
refinedweb
| 376
| 67.96
|
Last time in this series I presented an algorithm for generating a random number, and the time before I presented an algorithm that turns such a number into a permutation, so we can put them together to make an algorithm that returns a random permutation:
static Permutation RandomPermutation(int size, Random random) { return Permutation.NthPermutation(size, RandomFactoradic(size, random)); }
Is this actually a correct algorithm for generating a random permutation? Give it some thought.
Turns out, surprisingly, no, it is not correct. Now, there’s no flaw that I’m aware of in the logic or the mathematics that underlies it. Rather, the problem is that the
Random type is a big fat lie. We’d like to have the property that a random permutation generator produces every possible permutation with equal likelihood; that is, it should be unbiased. This algorithm is deeply biased because
Random is not a strong enough source of random numbers. Some permutations are less likely than others.
So what’s the big deal? If there were just a small bias, that would be unfortunate but not fatal. It’s actually worse than that. With this bad source of randomness, given a portion of a permutation, you can work out what the rest of the permutation likely is.
And that’s my challenge to you. I’ve posted some code below, putting together everything we’ve seen so far in this series. The first five card dealt when I ran the program were:
39: Ace of Clubs 11: Queen of Spades 29: Four of Diamonds 5: Six of Spades 20: Eight of Hearts
My challenge to you is: what are the next five cards that I generated? And…. go!
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Numerics; public static class Extensions { public static IEnumerable<T> InsertAt<T>( this IEnumerable<T> items, int position, T newItem) { if (items == null) throw new ArgumentNullException("items"); if (position < 0) throw new ArgumentOutOfRangeException("position"); return InsertAtIterator<T>(items, position, newItem); } private static IEnumerable<T> InsertAtIterator<T>( this IEnumerable<T> items, int position, T newItem) { int index = 0; bool yieldedNew = false; foreach (T item in items) { if (index == position) { yield return newItem; yieldedNew = true; } yield return item; index += 1; } if (index == position) { yield return newItem; yieldedNew = true; } if (!yieldedNew) throw new ArgumentOutOfRangeException("position"); } } struct Permutation : IEnumerable<int> { public static Permutation Empty { get { return empty; } } private static Permutation empty = new Permutation(new int[] { }); private int[] permutation; private Permutation(int[] permutation) { this.permutation = permutation; } private Permutation(IEnumerable<int> permutation) : this(permutation.ToArray()) { } private static BigInteger Factorial(int x) { BigInteger result = 1; for (int i = 2 ; i <= x ; ++i) result *= i; return result; } public static Permutation NthPermutation(int size, BigInteger index) { if (index < 0 || index >= Factorial(size)) throw new ArgumentOutOfRangeException("index"); if (size == 0) return Empty; BigInteger group = index / size; bool forwards = group % 2 != 0; Permutation permutation = NthPermutation(size - 1, group); int i = (int) (index % size); return new Permutation( permutation.InsertAt(forwards ? i : size - i - 1, size - 1)); } // Produce a random number between 0 and n!-1 static BigInteger RandomFactoradic(int n, Random random) { BigInteger result = 0; BigInteger radix = 1; for (int i = 1; i < n; ++i) { // We need a digit between 0 and i. result += radix * random.Next(i+1); radix *= (i+1); } return result; } public static Permutation RandomPermutation(int size, Random random) { return NthPermutation(size, RandomFactoradic(size, random)); } public int this[int index] { get { return permutation[index]; } } public IEnumerator<int> GetEnumerator() { foreach (int item in permutation) yield return item; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } public int Count { get { return this.permutation.Length; } } public override string ToString() { return string.Join<int>(",", permutation); } } class Program { static void Main() { string[] suits = { "Spades", "Hearts", "Diamonds", "Clubs" }; string[] values = {"Ace", "Deuce", "Trey", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" }; Permutation p = Permutation.RandomPermutation(52, new Random()); foreach (int i in p) Console.WriteLine("{0}: {1} of {2}", i, values[i % 13], suits[i / 13]); } }
Well, since you’re re-using the same instance of Random, the same sequence of numbers will be generated for a given seed. That’s actually a pretty useful property for online games. What I wonder is: if you create a new instance of Random in the RandomFactoradic method, and therefore get a time-based seed, will the bias still be there?
The next 5 terms are:
7: Eight of Spades
31: Six of Diamonds
8: Nine of Spades
47: Nine of Clubs
1: Deuce of Spades
KooKiz – While bias could be a problem in a better algorithm (see the common bias in incorrect implementations of Fisher-Yates), the larger problem here is that there are only a few billion possible decks of cards (the seed is a 32-bit integer), while there are 52! distinct shuffled decks of cards. 2^32 / 52! = 5.3249002 x 10^-59. That’s a teeny tiny percentage of possible decks.
David, that was astonishingly fast but unfortunately not quite right. The sixth is:
15: Trey of Hearts
Does that give you enough information to find the answer?
What technique did you use to find the answer that you propsed?
(And your analysis of the bias due to insufficient entropy in the seed is spot on.)
There are 52*51*50*49*48 = 311875200 possible first five cards, so with 2^32 seeds we should see on average 13.77 seeds for a list of 5 starting cards. Given the sixth card, we should see about 0.29 seeds. The first seed I found that matched was 150272048. Will continue the hunt given the Trey of Harts.
And my approach was just brute force in parallel over my 8 cores. Figured I could just start it and let it run for a few hours while I’m working. :)
You are correct that I underspecified the problem; I didn’t actually bother to check if there were collisions.
I presume that you removed the error checking to make it run faster.
I tried for a while to come up with a technique that was faster than brute force. I think there is one, but I was insufficiently clever. (Clearly there are much faster techniques if you have a less complicated shuffle algorithm, like Fischer-Yates but I couldn’t come up with one for this shuffle.)
Are you making the assumption that the Random ctor without constructor uses Environment.TickCount wich increment the value only by 15 or 16 (avarage 1000/64)? In this case, I think the sixth number isn’t needed.
Knowing Eric’s habits regarding PC reboots would help too.
Unfortunately the machine I did the run on had not been rebooted in many days, so there’s not much of an advantage there.
So about 226 bits of randomness are needed, right? Up from a “32 which isn’t even really 32 because time isn’t random”. Where can you even get something like that?
Harold, you can get it at:
I recall reading about a poker website which published their deck randomization algorithm for the sake of transparency. But since every hand was individually seeded based on the current server time…
Yep, here’s an very nice, slightly long description of that. The site had several other problems as well.
15: Trey of Hearts
3: Four of Spades
16: Four of Hearts
33: Eight of Diamonds
43: Five of Clubs
The Random seed for this is -781599298.
It was done via a brute force search, but by rewriting the NthPermutation method to short-circuit as soon as the RandomFactoradic value (index parameter) was known to produce a bad permutation (for example, placing any of the numbers 40-51 in one of the first 5 positions of the permutation).
My final NthPermutation method didn’t actually produce a Permutation value, as that wasn’t necessary. It simply returned a bool if the index parameter would cause a proper permutation to be produced.
You got it!
In case people were interested, here is the rewritten NthPermutation method, now called PermutationCheck..
Obviously that is not a good representation of the code. I may try again later.
Use “pre” tags and HTML escape sequences for less-than, greater-than and ampersand.
Here, again, is the PermutationCheck() method..
In the original post, I had the pre tags, just not the HTML escapes. Thanks for the tip.
Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1349
I let it run all night, and I got the same result as Joel, except that for me the seed is *positive* 781599298, not negative… I didn’t optimize as heavily as Joel though, I just removed the error checking.
I wonder if there is a more efficient way than brute force to solve this problem. Knowing an approximate value of the system’s TickCount would help a lot of course, but TickCount doesn’t seem to always be accurate: I usually shut down my computer every night, and the TickCount reports a duration of more than 23 days…
Just had a look at the Random source code () and I see the absolute value of the seed is used (or Int32.MaxValue in the case of Int32.MinValue). That may have been the easiest and best optimization I could have done.
Looking at the source code (thanks Joel, it is much faster than looking at ildasm) the pseudo-random algorithm isn’t all that good, at least if non-reversability is desirable, even tought there are a lot of operations to fill the SeedArray they all happen to same places for every seed, the InternalSample is weak as well, it is possible to brute force much cheaper than creating a Random instance for every possible seed by just producing and looking at needed values, also keeping a track of those operations may reveal how to reverse them, to some point, but I think than humans trying to find the reverse will take more time than computers trying to brute force…
I wonder if Neil Stephenson’s Cryptonomicon was an inspiration for this challenge, along with the detailed description of the Solitair encryption in the afterword to the novel. In any case, this random permutation stuff, complete with high-quality randomness, simply begs to be used for encryption.
One interested in this topic may find interesting to read about format-preserving encryption. I’ve ported one implementation to .NET, available at dotfpe.codeplex.com .
Hi Eric, I’ve noted with much interest the behavior of Random as discussed here in your bog. Now what I have is more of a question than anything. If one wanted to minimize the bias, would using code such as this really suffice?
FischerYatesShuffle(array1, new Random(new Random().Next()));
|
http://ericlippert.com/2013/05/02/producing-permutations-part-six/
|
CC-MAIN-2015-06
|
refinedweb
| 1,786
| 53.51
|
import keras keras.__version__
Using TensorFlow backend.
'2.0.8'
This notebook contains the code samples found in Chapter 3, Section 6 of Deep Learning with Python. Note that the original text features far more content, in particular further explanations and figures: in this notebook, you will only find source code and related comments.
In our two previous examples, we were considering classification problems, where the goal was to predict a single discrete label of an input data point. Another common type of machine learning problem is "regression", which consists of predicting a continuous value instead of a discrete label. For instance, predicting the temperature tomorrow, given meteorological data, or predicting the time that a software project will take to complete, given its specifications.
Do not mix up "regression" with the algorithm "logistic regression": confusingly, "logistic regression" is not a regression algorithm, it is a classification algorithm.
We will be attempting to predict the median price of homes in a given Boston suburb in the mid-1970s, given a few data points about the suburb at the time, such as the crime rate, the local property tax rate, etc.
The dataset we will be using has another interesting difference from our two previous examples: it has very few data points, only 506 in total, split between 404 training samples and 102 test samples, and each "feature" in the input data (e.g. the crime rate is a feature) has a different scale. For instance some values are proportions, which take a values between 0 and 1, others take values between 1 and 12, others between 0 and 100...
Let's take a look at the data:
from keras.datasets import boston_housing (train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()
train_data.shape
(404, 13)
test_data.shape
(102, 13)
As you can see, we have 404 training samples and 102 test samples. The data comprises 13 features. The 13 features in the input data are as follow:
The targets are the median values of owner-occupied homes, in thousands of dollars:
train_targets
array([ 15.2, 42.3, 50. , 21.1, 17.7, 18.5, 11.3, 15.6, 15.6, 14.4, 12.1, 17.9, 23.1, 19.9, 15.7, 8.8, 50. , 22.5, 24.1, 27.5, 10.9, 30.8, 32.9, 24. , 18.5, 13.3, 22.9, 34.7, 16.6, 17.5, 22.3, 16.1, 14.9, 23.1, 34.9, 25. , 13.9, 13.1, 20.4, 20. , 15.2, 24.7, 22.2, 16.7, 12.7, 15.6, 18.4, 21. , 30.1, 15.1, 18.7, 9.6, 31.5, 24.8, 19.1, 22. , 14.5, 11. , 32. , 29.4, 20.3, 24.4, 14.6, 19.5, 14.1, 14.3, 15.6, 10.5, 6.3, 19.3, 19.3, 13.4, 36.4, 17.8, 13.5, 16.5, 8.3, 14.3, 16. , 13.4, 28.6, 43.5, 20.2, 22. , 23. , 20.7, 12.5, 48.5, 14.6, 13.4, 23.7, 50. , 21.7, 39.8, 38.7, 22.2, 34.9, 22.5, 31.1, 28.7, 46. , 41.7, 21. , 26.6, 15. , 24.4, 13.3, 21.2, 11.7, 21.7, 19.4, 50. , 22.8, 19.7, 24.7, 36.2, 14.2, 18.9, 18.3, 20.6, 24.6, 18.2, 8.7, 44. , 10.4, 13.2, 21.2, 37. , 30.7, 22.9, 20. , 19.3, 31.7, 32. , 23.1, 18.8, 10.9, 50. , 19.6, 5. , 14.4, 19.8, 13.8, 19.6, 23.9, 24.5, 25. , 19.9, 17.2, 24.6, 13.5, 26.6, 21.4, 11.9, 22.6, 19.6, 8.5, 23.7, 23.1, 22.4, 20.5, 23.6, 18.4, 35.2, 23.1, 27.9, 20.6, 23.7, 28. , 13.6, 27.1, 23.6, 20.6, 18.2, 21.7, 17.1, 8.4, 25.3, 13.8, 22.2, 18.4, 20.7, 31.6, 30.5, 20.3, 8.8, 19.2, 19.4, 23.1, 23. , 14.8, 48.8, 22.6, 33.4, 21.1, 13.6, 32.2, 13.1, 23.4, 18.9, 23.9, 11.8, 23.3, 22.8, 19.6, 16.7, 13.4, 22.2, 20.4, 21.8, 26.4, 14.9, 24.1, 23.8, 12.3, 29.1, 21. , 19.5, 23.3, 23.8, 17.8, 11.5, 21.7, 19.9, 25. , 33.4, 28.5, 21.4, 24.3, 27.5, 33.1, 16.2, 23.3, 48.3, 22.9, 22.8, 13.1, 12.7, 22.6, 15. , 15.3, 10.5, 24. , 18.5, 21.7, 19.5, 33.2, 23.2, 5. , 19.1, 12.7, 22.3, 10.2, 13.9, 16.3, 17. , 20.1, 29.9, 17.2, 37.3, 45.4, 17.8, 23.2, 29. , 22. , 18. , 17.4, 34.6, 20.1, 25. , 15.6, 24.8, 28.2, 21.2, 21.4, 23.8, 31. , 26.2, 17.4, 37.9, 17.5, 20. , 8.3, 23.9, 8.4, 13.8, 7.2, 11.7, 17.1, 21.6, 50. , 16.1, 20.4, 20.6, 21.4, 20.6, 36.5, 8.5, 24.8, 10.8, 21.9, 17.3, 18.9, 36.2, 14.9, 18.2, 33.3, 21.8, 19.7, 31.6, 24.8, 19.4, 22.8, 7.5, 44.8, 16.8, 18.7, 50. , 50. , 19.5, 20.1, 50. , 17.2, 20.8, 19.3, 41.3, 20.4, 20.5, 13.8, 16.5, 23.9, 20.6, 31.5, 23.3, 16.8, 14. , 33.8, 36.1, 12.8, 18.3, 18.7, 19.1, 29. , 30.1, 50. , 50. , 22. , 11.9, 37.6, 50. , 22.7, 20.8, 23.5, 27.9, 50. , 19.3, 23.9, 22.6, 15.2, 21.7, 19.2, 43.8, 20.3, 33.2, 19.9, 22.5, 32.7, 22. , 17.1, 19. , 15. , 16.1, 25.1, 23.7, 28.7, 37.2, 22.6, 16.4, 25. , 29.8, 22.1, 17.4, 18.1, 30.3, 17.5, 24.7, 12.6, 26.5, 28.7, 13.3, 10.4, 24.4, 23. , 20. , 17.8, 7. , 11.8, 24.4, 13.8, 19.4, 25.2, 19.4, 19.4, 29.1])
The prices are typically between \$10,000 and \$50,000. If that sounds cheap, remember this was the mid-1970s, and these prices are not inflation-adjusted.
It would be problematic to feed into a neural network values that all take wildly different ranges. The network might be able to automatically adapt to such heterogeneous data, but it would definitely make learning more difficult. A widespread best practice to deal with such data is to do feature-wise normalization: for each feature in the input data (a column in the input data matrix), we will subtract the mean of the feature and divide by the standard deviation, so that the feature will be centered around 0 and will have a unit standard deviation. This is easily done in Numpy:
mean = train_data.mean(axis=0) train_data -= mean std = train_data.std(axis=0) train_data /= std test_data -= mean test_data /= std
Note that the quantities that we use for normalizing the test data have been computed using the training data. We should never use in our workflow any quantity computed on the test data, even for something as simple as data normalization.
from keras import models from keras import layers=['mae']) return model
Our network ends with a single unit, and no activation (i.e. it will be linear layer).
This is a typical setup for scalar regression (i.e. regression where we are trying to predict a single continuous value).
Applying an activation function would constrain the range that the output can take; for instance if
we applied a
sigmoid activation function to our last layer, the network could only learn to predict values between 0 and 1. Here, because
the last layer is purely linear, the network is free to learn to predict values in any range.
Note that we are compiling the network with the
mse loss function -- Mean Squared Error, the square of the difference between the
predictions and the targets, a widely used loss function for regression problems.
We are also monitoring a new metric during training:
mae. This stands for Mean Absolute Error. It is simply the absolute value of the
difference between the predictions and the targets. For instance, a MAE of 0.5 on this problem would mean that our predictions are off by
\$500 on average.
To evaluate our network while we keep adjusting its parameters (such as the number of epochs used for training), we could simply split the data into a training set and a validation set, as we were doing in our previous examples. However, because we have so few data points, the validation set would end up being very small (e.g. about 100 examples). A consequence is that our validation scores may change a lot depending on which data points we choose to use for validation and which we choose for training, i.e. the validation scores may have a high variance with regard to the validation split. This would prevent us from reliably evaluating our model.
The best practice in such situations is to use K-fold cross-validation. It consists of splitting the available data into K partitions (typically K=4 or 5), then instantiating K identical models, and training each one on K-1 partitions while evaluating on the remaining partition. The validation score for the model used would then be the average of the K validation scores obtained.
In terms of code, this is straightforward:
import numpy as np k = 4 num_val_samples = len(train_data) // k num_epochs = 100 all_scores = []) model.fit(partial_train_data, partial_train_targets, epochs=num_epochs, batch_size=1, verbose=0) # Evaluate the model on the validation data val_mse, val_mae = model.evaluate(val_data, val_targets, verbose=0) all_scores.append(val_mae)
processing fold # 0 processing fold # 1 processing fold # 2 processing fold # 3
all_scores
[2.0750808349930412, 2.117215852926273, 2.9140411863232605, 2.4288365227161068]
np.mean(all_scores)
2.3837935992396706
As you can notice, the different runs do indeed show rather different validation scores, from 2.1 to 2.9. Their average (2.4) is a much more reliable metric than any single of these scores -- that's the entire point of K-fold cross-validation. In this case, we are off by \$2,400 on average, which is still significant considering that the prices range from \$10,000 to \$50,000.
Let's try training the network for a bit longer: 500 epochs. To keep a record of how well the model did at each epoch, we will modify our training loop to save the per-epoch validation score log:
from keras import backend as K # Some memory clean-up K.clear_session()
num_epochs = 500 all_mae_histories = []) history = model.fit(partial_train_data, partial_train_targets, validation_data=(val_data, val_targets), epochs=num_epochs, batch_size=1, verbose=0) mae_history = history.history['val_mean_absolute_error'] all_mae_histories.append(mae_history)
processing fold # 0 processing fold # 1 processing fold # 2 processing fold # 3
We can then compute the average of the per-epoch MAE scores for all folds:
average_mae_history = [ np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]
Let's plot this:
import matplotlib.pyplot as plt plt.plot(range(1, len(average_mae_history) + 1), average_mae_history) plt.xlabel('Epochs') plt.ylabel('Validation MAE') plt.show()
It may be a bit hard to see the plot due to scaling issues and relatively high variance. Let's:
def smooth_curve(points, factor=0.9): smoothed_points = [] for point in points: if smoothed_points: previous = smoothed_points[-1] smoothed_points.append(previous * factor + point * (1 - factor)) else: smoothed_points.append(point) return smoothed_points smooth_mae_history = smooth_curve(average_mae_history[10:]) plt.plot(range(1, len(smooth_mae_history) + 1), smooth_mae_history) plt.xlabel('Epochs') plt.ylabel('Validation MAE') plt.show()
According to this plot, it seems that validation MAE stops improving significantly after 80 epochs. Past that point, we start overfitting.
Once we are done tuning other parameters of our model (besides the number of epochs, we could also adjust the size of the hidden layers), we can train a final "production" model on all of the training data, with the best parameters, then look at its performance on the test data:
# Get a fresh, compiled model. model = build_model() # Train it on the entirety of the data. model.fit(train_data, train_targets, epochs=80, batch_size=16, verbose=0) test_mse_score, test_mae_score = model.evaluate(test_data, test_targets)
32/102 [========>.....................] - ETA: 0s
test_mae_score
2.5532484335057877
We are still off by about \$2,550.
Here's what you should take away from this example:
This example concludes our series of three introductory practical examples. You are now able to handle common types of problems with vector data input:
In the next chapter, you will acquire a more formal understanding of some of the concepts you have encountered in these first examples, such as data preprocessing, model evaluation, and overfitting.
|
https://nbviewer.jupyter.org/github/fchollet/deep-learning-with-python-notebooks/blob/master/3.7-predicting-house-prices.ipynb
|
CC-MAIN-2019-18
|
refinedweb
| 2,194
| 58.82
|
I have the following code that did not work:
import matplotlib.pyplot as plt
# Make the plot
fig, axs = plt.subplots(3, 1, figsize=(3.27, 6))
axs[0].plot(range(5), range(5), label='label 1')
axs[0].plot(range(5), range(4, -1, -1), label='label 2')
axs[0].legend(bbox_to_anchor=(0, 1.1, 1., 0.1), mode='expand', ncol=2, frameon=True, borderaxespad=0.)
# Adjust subplots to make room
fig.subplots_adjust(top=.5)
fig.savefig('test.png', format='png', dpi=300)
With the help of tcaswell, I got it solved by entirely closing the IPython Notebook and re-run the code via the ipython-qtconsole. It seems that the subplots_adjust() simply doesn't work for python 3 in ipython-notebook. I am new to python, and is really interested in what difference is there between the qtconsole and the notebook, backend-wise, if anyone has got ideas.
Anyways - good to have this problem solved!
|
https://codedump.io/share/6PDLxauhe6Fs/1/subplotsadjust-in-matplotlib-does-not-work-in-ipython-notebook
|
CC-MAIN-2017-13
|
refinedweb
| 157
| 61.53
|
Man Page
Manual Section... (3) - page: aio_suspend
NAMEaio_suspend - wait for asynchronous I/O operation or timeout
SYNOPSIS
#include <aio.h> int aio_suspend(const struct aiocb * const cblist[],
int n, const struct timespec *timeout); Link with -lrt.
DESCRIPTIONTheIf this function returns after completion of one of the indicated requests, it returns 0. Otherwise it returns -1 and sets errno appropriately.
ERRORS
- EAGAIN
- The call was ended by timeout, before any of the indicated operations had completed.
- EINTR
- The call was ended by signal; see signal(7). (Possibly the completion signal of one of the operations we were waiting for.)
CONFORMING TOPOSIX.1-2001.
NOTESOne can achieve polling by using a non-NULL timeout that specifies a zero time interval.
SEE ALSOaio_cancel(3), aio_error(3), aio_fsync(3), aio_read(3), aio_return(3), aio_write(3), time
|
http://linux.co.uk/documentation/man-pages/subroutines-3/man-page/?section=3&page=aio_suspend
|
CC-MAIN-2016-36
|
refinedweb
| 132
| 50.94
|
Drop-in replacement for Parse with added Redux goodness!
HTML 5 Audio API in React
chrbala/react-resume-boilerplate 9
a way to jump start writing your resume and cover letter in HTML and CSS
chrbala/horizon-react-webpack-hmr-boilerplate 4
A semi-opinionated boilerplate for horizon-react and webpack, with hot module reloading
leveldown compatible binding to LMDB
✏️ Tooling for development and production Apollo workflows
My rollup config
chrbala/create-react-app 0
Create React apps with no build configuration.
push eventchrbala/zod-full-stack-example
commit sha f766047c316aee0fb977be3f84f844572d0fafe6
Add a server-only validation that will hit the UI
push time in 4 days
push eventchrbala/zod-full-stack-example
commit sha 3d8abe701c458c4dc6871a436a9186dabf0045c0
Add dryruns to mutations
push time in 4 days
push eventchrbala/zod-full-stack-example
commit sha aeb2d8a33a1fd54327e618270c935bb6df6f8a46
Add a simplified allLivingThings resolver
push time in 4 days
push eventchrbala/zod-full-stack-example
commit sha 4ca394adf09254f026b803cec3f357166b303c60
Fix a couple things
commit sha 71a58adb387de9deedc14213a38ed7292ae2fc68
Automatically strip unused keys
commit sha a2af995c53644475248e8e004f0f81d61c7f591e
add backend for update and delete
commit sha 56647864646f3e21544c31e7eed93708f1723a26
Partial progress with other resolvers
commit sha 14798aa03295e69d1db755eb8d5ef74eadd6b092
Fixes
commit sha 9e139a3497c9fdd410edbd31c18c54ebada8925b
Update diet
commit sha fea35720c99464de72b8c40f3586d86539f21249
Allow explicit nulls
push time in 6 days
push eventchrbala/zod-full-stack-example
commit sha ef63e9117414d0e9af1a0b56c1e2b6dbab8c3de5
initial server work done
push time in 9 days
push eventchrbala/zod-full-stack-example
commit sha bf86b2dc389028cbec59e05a481e486cb3f92de3
remove log (+11 squashed commits) Squashed commits: [4a95289] agh [9bfe782] hmm [b6057ba] Cap diet sizes [ec5169a] Looking pretty good [3ef614c] big progress [b94cb47] progress [9c64f54] Remove garbage [d96b89a] Simplify things [483e04b] progress [1f9e423] copy draw [1370592] Copy io-ts-reporters
push time in 9 days
create barnchchrbala/zod-full-stack-example
created branch time in 11 days
startedMichalLytek/type-graphql
started time in a month
Docs on integrating with other OSS
I have a bit of progress on an example. It uses the in-progress zod transformations API and not everything works – don't rely on anything in the repo for now. I'm adding this repo to share progress here, but it shouldn't be trusted to be stable at this point.
comment created time in a month
create barnchchrbala/zod-full-stack-example
branch : work-in-progress
created branch time in a month
create barnchchrbala/zod-full-stack-example
created branch time in a month
created repositorychrbala/zod-full-stack-example
created time in a month
created repositorychrbala/zod-full-stack-example
created time in a month
Detailed errors for union schema
comment created time in a month
Okay to just leave this one hanging for a while? I think things may get clearer once more work has been done on a full-stack example for #86. I've been working on that one for some time - it's been going back and forth between that and your work on #100 which my implementation of #86 is dependent on.
comment created time in a month
Generic for parsing objects
Yeah, that seems about right for the sync implementation. It does look like
params is unused though - not sure if that was intentional.
comment created time in a month
RFC: Transformations (e.g. casting/coercion)
I have done more investigations and have come across the following 3 use cases, divided by separators:
Is there something that could be done to improve deep structural sharing of the output types? It seems like allowing something like this would make certain patterns much easier.
import * as z from 'zod'; const id = z.transformer(z.number(), z.string(), n => String(n)); const node = z.transformer( z.object({ id, }), z.object({ ID: id, }), ({ id }) => ({ ID: id }) ); node.parse({ id: 5 }); // would like { ID: 5 }, but this throws "Expected number, received string"
How would you get both the input and output types for a schema? z.TypeOf is only one type. Maybe introspection into the schema to get the input and output runtime schemas would work well for both getting the schemas themselves and their associated TS types. e.g.
const num = z.number(); const str = z.string(); const field = z.transformer(num, string, n => String(n)); const obj = z.object({ field, }); field.getInput(); // num field.getOutput(); // str obj.getInput(); // equivalent of z.object({ field: z.number() }); obj.getOutput(); // equivalent of z.object({ field: z.string() });
And in this case, getOutput() would preferably return the output types of all children in the schema, like the first section of this comment mentions. I see that there are
input,
output,
_input, and
_output fields on some zod types, but my guess is that they don't work quite like this, and it's not clear what the intention is.
- What about two-way transformations, e.g. for serialization and deserialization? This could be pretty common for lossless transformations. Should A -> B -> A require two fully separate schemas, or should there be a mechanism to enable this?
- What about arbitrary length transformation chains? A -> B -> C -> D (etc)?
My inclination is that (1) would probably be useful and (2) might get overcomplicated quickly. And what’s to say that a sequence of transformations is what makes sense in (2), rather than a tree or graph shape. (2) seems too complex for zod to incorporate.
comment created time in a month
RFC: Make object schemas nonstrict by default
The primary thing I care about regarding this issue is that there's a path to getting a clean object without erroneous keys. If you use zod to validate before a schemaless database, you might find out you have a bunch of unwanted fields if there aren't good protections in place. Perhaps making this explicit like a
ZodSchema.parse(val, { clean: true }) which would allow for this.
Even right now, this is a bit cumbersome because unused fields have to be manually removed. A value cleaner would make this nicer.
comment created time in a month
RFC: Transformations (e.g. casting/coercion)
Makes sense! I have a couple thoughts:
- Generally I'd hope that ctx has bound functions, or is an object literal, so people could destructure it without getting class errors.
(num, {makeError}) => ...
- Would the API be
ctx.customError(message: string, params?: { [key: string]: any })?
- I'm not sure I know of any kind of use case for this (perhaps transforms for tests), but is there any chance someone would want to actually transform to a ZodError? If that's a real use case, should
ctx.makeErrorreturn some special private error type that end-users don't have access to through normal means?
comment created time in a month
Generic for parsing objects
Seems to make sense to me at least. Would it be
.safeParse() and
.safeParseAsync() when async parsing is added then?
comment created time in 2 months
Guidance on creating slight schema variants for varied contexts
Yeah, agreed that at this point there isn't really an obvious action to take here. From investigating this, I've found that it's mostly easiest to make shared types from the leaf nodes up as high as what is fully shared, then do a hard fork where the types diverge. It can get pretty redundant with deeply nested types that diverge near the leaves, but I've found that the redundancy is the clearest way to represent this, rather than abstractions or core feature additions.
comment created time in 2 months
Demand for VSCode Extension?
Interesting concept! I would personally prefer to see GraphQL schema -> Zod types, but interesting either way! I suppose it's also possible to generate GraphQL -> TS -> Zod in some kind of pipeline as well. In general, I'd expect to auto-generate Zod types which then get manually edited. Certainly it's more complicated than just the proposal here, and I'm not sure exactly what it would look like in terms of UX.
comment created time in 2 months
RFC: Transformations (e.g. casting/coercion)
I guess I was actually skipping a step there. That's the value that gets passed in to the schema, and I was forgetting that it wouldn't have yet been parsed to a number. So, more accurately:
const float = z.transformer(z.string(), z.number(), x => parseFloat(x)); const int = z.transformer(z.string(), z.number().int(), x => parseInt(x)); const resolveType = (val: unknown) => typeof val === 'string' && parseFloat(val) % 1 === 0 ? int : float; const number = z.union([float, int], resolveType); number.parse('12.5');
val === '12.5' in this case, but resolveType doesn't know anything about the type yet, so the type resolver has to operate under the assumption that val is
unknown.
comment created time in 2 months
RFC: Transformations (e.g. casting/coercion)
Returning back to the issue of unions - what if there was an explicit resolver function like
resolveType in GraphQL?
Perhaps z.union could be a variadic function that by default picks the first schema that matches left-to-right, but optionally can specify a second resolver argument.
const float = z.transformer(z.string(), z.number(), x => parseFloat(x)); const int = z.transformer(z.string(), z.number().int(), x => parseInt(x)); const leftToRightNum = z.union([float, int]); const withResolverNum = z.union([float, int], val => val % 1 === 0 ? int : float );
This is kind of a trivial example, but it would line up well for people who already do type resolutions with GraphQL in some way, and the explicitness is nice.
comment created time in 2 months
Generic for parsing objects
I have written this which has somewhat different goals as the above example, which may be of interest to people:
- Intentional (validation) errors returned, not thrown. This distinguishes them from unintentional errors which are still thrown.
- Semi-strongly typed errors (properties known, but not enumerated).
- Always async
- Not concerned with creating factories, can curry if desired
- Decoupled from Zod. Returns errors that are not library specific.
import { Schema, ZodError, ZodErrorCode } from 'zod'; const asError = (e: unknown) => e instanceof Error ? e : typeof e === 'string' ? new Error(e) : new Error(); export type ExecResult<T> = | { success: true; data: T; } | { success: false; error: Error; }; export const safeExec = <T extends any>(cb: () => T): ExecResult<T> => { try { return { success: true, data: cb() }; } catch (e) { return { success: false, error: asError(e) }; } }; export const safeExecAsync = <T extends any>( cb: () => Promise<T> ): Promise<ExecResult<T>> => { // check for sync errors const res = safeExec(cb); if (!res.success) return Promise.resolve(res); return Promise.resolve(res.data).then( data => ({ success: true, data }), error => ({ success: false, error: asError(error) }) ); }; type ParseError = { code: string; path: Array<string>; }; type ParseResult<T> = | { success: true; data: T } | { success: false; errors: Array<ParseError> }; export const parse = async <T>( schema: Schema<T>, data: unknown ): Promise<ParseResult<T>> => { const res = await safeExecAsync(() => schema.parseAsync(data)); if (res.success) return res; if (res.error instanceof ZodError) { return { success: false, errors: res.error.errors.map(({ code, message, path }) => ({ path: path.map(String), code: code === ZodErrorCode.custom_error ? message : code, })), }; } throw res.error; };
Usage:
const parsed = await parse(MySchema, someValue); if (!parsed.success) { return { __typename: 'InputError', errors: parsed.errors, }; } // parsed.data is known to exist statically now because of the guard above.
comment created time in 2 months
RFC: Make object schemas nonstrict by default' }
comment created time in 2 months
startedautomerge/automerge
started time in 2 months
RFC: Transformations (e.g. casting/coercion)
Perhaps Date was a poor example because it has a builtin type in Zod. I'm more interested in the broader case where parsing, error code generation, and transforming can all happen in the same closure (or provide sufficient context sharing, etc) with arbitrary types for convenience and performance.
e.g. with simple-duration. (Again, let's say simple-duration has an error code which we can use in the refinement.)
import * as sd from 'simple-duration'; import * as z from 'zod'; const DurationString = z.string().refine(s => { try { sd.parse(s); return true; } catch (e) { return false; } }, 'need e.code here'); z.transformer(DurationString, z.number(), s => sd.parse(s));
If the type refine fails, sd.parse is only run once here, but if it passes, it gets run in both the refine and the transformer. You can see it on this RunKit where the single
t.parse('5m') results in the sd.parse getting parsed twice, evidenced by the two console.log statements.
Dates and simple-duration are of course fairly trivial data types, but conceivably there could be sufficiently complex data types (e.g. zipped data, etc) where doing multiple parses would eat into performance.
Perhaps this point could be moved to a different issue, however. I could see
z.transformer working as it currently does, and perhaps something like
z.parser which could combine parsing, error codes, and transformations like this, where Error could have an error code and additional properties that get rolled up into the list of
ZodError at the top level parse function:
.parser<A, B>(parserFn: (data:A)=> B | Error)
comment created time in 2 months
Create a zod type from a TS enum
Right now if you want to create a type from a TS enum, you have do something like the following:
enum PlantLifecycle { Evergreen = 'EVERGREEN', Deciduous = 'DECIDUOUS', SemiDeciduous = 'SEMI_DECIDUOUS' }; const lifecycle = z.union([ z.literal(PlantLifecycle.Deciduous), z.literal(PlantLifecycle.Evergreen), z.literal(PlantLifecycle.SemiDeciduous), ]);
There should be an easier way of doing this, like:
enum PlantLifecycle { Evergreen = 'EVERGREEN', Deciduous = 'DECIDUOUS', SemiDeciduous = 'SEMI_DECIDUOUS' }; z.enum(PlantLifecycle);
created time in 2 months
RFC: Transformations (e.g. casting/coercion)
Another thought I'm having on this one is similar to #88. That is, it would be a pretty reasonable case to see an external tool parsing, validating, and creating error messages. Right now, all these things are run in zod in separate closures, which means that you have to plumb these things in multiple times, and pay the runtime cost multiple times as well.
For the sake of example, let's say Date.parse throws an error that includes a "code" property instead of returning NaN when there is an invalid input. This is similar to what npm libraries sometimes do.
const DateString = z.string().refine(s => { try { Date.parse(s); return true; } catch (e) { return false; } }, 'need e.code here'); z.transformer(DateString, z.number(), s => Date.parse(s));
I don't want to have to run Date.parse 2-3 times to parse each input. This example is fairly small, but for some types, the runtime cost could start adding up. It would be nice to have a single closure that can encompass (1) validation (2) error code generation, and (3) transformations.
comment created time in 2 months
RFC: Transformations (e.g. casting/coercion)
Are transforms supposed to bubble up the object trees? I'm not getting what I'm expecting.
const ID = z.transformer(z.number(), z.string(), n => String(n)); const node = z.object({ id: ID }); const result = node.parse({ id: 5 }); // returns { id: 5 } not { id: '5' }
Interestingly,
result is typed as you'd expect here:
{ id: string }.
comment created time in 2 months
RFC: Transformations (e.g. casting/coercion)
I'll be digging deeper into this as I have time, but my first thought is that it would be nice to have async transformations. That is, you could do something like
z.transformer(z.string(), z.string(), s => Promise.resolve(s));. Then the async logic for deep fields would get hidden away with whatever solution that results from #87.
comment created time in 2 months
Similar to Yup’s meta properties?
Seems like there are quite of lot of arbitrary places where UI could be driven from metadata in some way:
- max length on a field gets set on the input
- max length on an array disables or hides an "add row" button
More complex metadata could be something like data driven UI allowing for selection of various complex forms based on a union type.
At some level it seems like there could be a question of whether zod:
- allows arbitrary fields like this suggestion
- generates user-accessible metadata based on the built-ins like
z.string().max(5)
- some combination of the above
comment created time in 2 months:
- Validations that only the server can do because of access to resources.
- Validations with a CPU performance hit, so the validations need to be debounced, run on field blur, form submission, etc so as to not drop frames
- Validations that call out to the backend (assuming #87 is done) need to be debounced, run on field blur, form submission, etc so as to preserve server resources/bandwidth/etc
So for a full-stack example, there could be 3+ schemas in operation with lots of shared logic:
- API validations
- Validations that happen frequently on user input
- Validations that happen infrequently on the client
comment created time in 2 months
Guidance on creating slight schema variants for varied contexts
Thinking about this one a bit more. I'm wondering if it might make sense to generally solve this type of thing on the application side like this:
// commonValidations.ts import * as z from 'zod'; export const id = z.string().refine(val => val.length == 8, { message: "Foreign keys should be 8 characters", });
// clientValidations.ts import * as z from 'zod'; import * as commonValidations from './commonValidations'; /* Client does not have any extra validations for ID, so it uses common directly */ export const user = z.object({ id: commonValidations.id, });
// serverValidations.ts import * as z from 'zod'; // model only exists on the server, not implemented here import { isValidId } from './applicationModel'; import * as commonValidations from './commonValidations'; export const id = commonValidations.id.refine(isValidId, { message: 'ID is invalid', }); export const user = z.object({ id, });
What I like about this design is that everything is very explicit, clear, and avoids tight coupling between client and server. What I don't like is that it could get pretty verbose with lots of redundancy across the client and server as the schema gets more complex. That is, if
user had a schema refinement, it would need to be shared across the client and server as well. Any kind of schema patching would be more concise in exchange for tighter coupling between client and server in this type of situation.
comment created time in 2 months.
comment created time in 2 months
Docs on integrating with other OSS.
comment created time in 2 months
Value transformation / object mapping
Seems like this could be really useful when it comes to more complex objects. For a specific use-case I'm thinking of, take GraphQL unions that are generated from inputs. Union types only exist on outputs, so it's required to use some workarounds to have varied inputs.
The following is a common solution for this problem illustrated in TypeScript:
type Animal = { lifespan: number; }; type Mineral = { elements: Array<string>; }; type Vegetable = { calories: number; }; type Answer = Animal | Mineral | Vegetable; type TwentyQuestions = { answer: Answer; }; // This is equivalent to TwentyQuestions shown above, but structured differently. // It is also possible to represent invalid values with this structure. type TwentyQuestionsInput = { animal?: Animal; mineral?: Mineral; vegetable?: Vegetable; };
The pattern here is to make each variant of the union a unique field on the input type which is then validated in the API logic to ensure that only one is provided and persisted.
Concretely for zod, this would look like a union on one side and an object on the other side with some additional logic (with zod refine) to ensure that only one key is provided.
There are some patterns in GraphQL and in other systems that require transformations like this. Creating complex structures for both validation/parsing and mapping would be fairly redundant, so it would be ideal to include this type of logic in a library like zod.
A couple related thoughts:
- What actually gets validated? If the parser maps A -> B, does the validation logic operate on A or B?
- What do you do if you want to have mappings from both A -> B as well as A -> C? There’s likely a lot of common logic and structure there. What is the best way of sharing it?
- Should there be library logic for composing transformations? That is, if you have logic for A -> B and B -> C, should there be something like a z.compose(a, b) that creates an A -> C mapping from the separate mappers? How would that work?
- What about reversible operations? How would you easily create both A -> B and B -> A?
comment created time in 2 months
Option to create params from input in custom validation
zod custom validation allows params to be passed in to the error object. It would be nice if these could be created based on the initial data.
That is, instead of this type signature:
.refine(validator: (data:T)=>any, params?: RefineParams)
zod could use:
.refine(validator: (data:T)=>any, params?: RefineParams | (data: T) => RefineParams
created time in 2 months
There.
created time in 2 months
Docs on integrating with other OSS
It would be nice to have docs on how to integrate zod with other OSS. This would help people:
- identify whether zod will work well with their tech stack
- figure out how to use zod with their tech stack
- help zod validate its feature set. If the docs are hard to write, zod is probably missing something.
GraphQL.
React PropTypes
Seems like an integration that would make sense for libraries. Similar docs like those for GraphQL could make sense.
formik
Formik has native support for Yup schemas. Docs on integrating zod with formik would be nice!
created time in 2 months
Guidance on creating slight schema variants for varied contexts
I am interested in using zod for frontend, API, and backend validation.
For example, a browser might validate user inputs live as they are changed on the page. The user hits "submit" which sends the data to the API. The API runs its own validations on this data that may be somewhat different. The API changes the data slightly to conform with the backend needs. The backend has a similar schema, but there are some small differences.
Differences might be things like:
- Adding a field deep in the schema
- Swapping a foreign key ID for an object pulled from some other location
- API allows partial inputs for updates, but the backend sometimes requires complete inputs. For example, take a blog post draft that can be missing a title field, but the backend requires a title to be persisted before publishing.
I'm not necessarily looking for changes to the library, but rather recommended patterns through documentation, blog posts, etc. I see that zod supports merging, masking, and extending, but am looking for higher level guidance on patterns for this type of use case. I can see schema sharing as something that could potentially make a codebase much more complex without due care. The guidance here might be to create separate schemas because the costs of coupling schemas across contexts is too high!
There may also be features that could be added to zod that make this use case easier.
created time in 2 months
I.
created time in 2 months
It looks like this
j wasn't intended to be in the doc.
pr created time in 2 months
push eventchrbala/zod
commit sha 20aaa0406475ad76ecbe765187bc8609c7ad2c7b
Remove erroneous character from readme
push time in 2 months
fork chrbala/zod
TypeScript-first schema validation with static type inference
fork in 2 months
|
https://www.gitmemory.com/chrbala
|
CC-MAIN-2020-40
|
refinedweb
| 3,876
| 55.74
|
Create JSON API:s with HMAC authentication and Django form-validation.
Install django-formapi in your python environment
$ pip install django-formapi
Add formapi to your INSTALLED_APPS setting.
INSTALLED_APPS = ( ... 'formapi', )
Add formapi.urls to your urls.py.
urlpatterns = patterns('', ... url(r'^api/', include('formapi.urls')), )
Go ahead and create a calls.py.
class DivisionCall(calls.APICall): """ Returns the quotient of two integers """ dividend = forms.FloatField() divisor = forms.FloatField() def action(self, test): dividend = self.cleaned_data.get('dividend') divisor = self.cleaned_data.get('divisor') return dividend / divisor API.register(DivisionCall, 'math', 'divide', version='v1.0.0')
Just create a class like your regular Django Forms but inheriting from APICall. Define the fields that your API-call should receive. The action method is called when your fields have been validated and what is returned will be JSON-encoded as a response to the API-caller. The API.register call takes your APICall-class as first argument, the second argument is the namespace the API-call should reside in, the third argument is the name of your call and the fourth the version. This will result in an url in the form of api/[version]/[namespace]/[call_name]/ so we would get /api/v1.0.0/math/divide/.
A valid call with the parameters {'dividend': 5, 'divisor': 2} would result in this response:
{"errors": {}, "data": 5, "success": true}
An invalid call with the parameters {'dividend': "five", 'divisor': 2} would result in this response:
{"errors": {"dividend": ["Enter a number."]}, "data": false, "success": false}
By default APICalls have HMAC-authentication turned on. Disable it by setting signed_requests = False on your APICall.
If not disabled users of the API will have to sign their calls. To do this they need a secret generate, create a APIKey through the django admin interface. On save a personal secret and key will be generated for the API-user.
To build a call signature for the DivisonCall create a querystring of the calls parameters sorted by the keys dividend=5&divisor=2. Create a HMAC using SHA1 hash function. Example in python:
import hmac from hashlib import sha1 hmac_sign = hmac.new(secret, urllib2.quote('dividend=5&divisor=2'), sha1).hexdigest()
A signed request against DivisionCall would have the parameters {'dividend': 5, 'divisor': 2, 'key': generated_key, 'sign': hmac_sign}
Visit /api/discover for a brief documentation of the registered API-calls.
MIT
|
https://crate.io/packages/django-formapi/
|
CC-MAIN-2015-22
|
refinedweb
| 388
| 50.02
|
Shootout/SumFile
From HaskellWiki Fastest (twice as fast as old Char entry)
ByteString translation, with careful attention to Core.
{-# OPTIONS -O -fbang-patterns #-} -- -- The Computer Language Shootout -- -- -- Contributed by Don Stewart -- Based on older versions by Greg Buchholz, -- Mirko Rahn, Chris Kuklewicz and David Himmelstrup -- import Data.Char import Data.ByteString.Base import qualified Data.ByteString.Char8 as B main = print . new 0 =<< B.getContents new !i s | B.null s = i | x == '-' = sub i 0 xs | otherwise = add i (parse x) xs where (x,xs) = uncons s sub !i !n t | y == '\n' = new (i-n) ys | otherwise = sub i n' ys where (!y,ys) = uncons t n' = parse y + 10 * n add !i !n t | y == '\n' = new (i+n) ys | otherwise = add i n' ys where (!y,ys) = uncons t n' = parse y + 10 * n parse c = ord c - ord '0' uncons s = (w2c (unsafeHead s), unsafeTail s)
2 This should be a bit faster, and cuter
-- -- Contributed by Don Stewart -- import qualified Data.ByteString.Char8 as B import Data.List main = print . sum . unfoldr parse =<< B.getContents parse !x | Just (n,y) <- B.readInt x = Just (n,B.tail y) | otherwise = Nothing
3 A Lazy ByteString Entry
-- -- The Computer Language Shootout -- -- -- compile with : ghc -O Sumcol.hs -o sumcol -- -- Contributed by Bryan Donlan -- Modified by Spencer Janssen import qualified Data.ByteString.Lazy.Char8 as BS main = print . sum' 0 . BS.lines =<< BS.getContents where sum' n [] = n sum' n (x:xs) = sum' (n + readInt x) xs readInt bs = case BS.readInt bs of Just (i, _) -> i
4
5 #-}'
7 Old code -} import GHC.Base data I = I !Int main = print . new (I 0) =<< getContents new (I i) [] = i new (I i) ('-':xs) = neg (I 0) xs where neg (I n) ('\n':xs) = new (I (i - n)) xs neg (I n) (x :xs) = neg (I (parse x + (10 * n))) xs new (I i) (x:xs) = pos (I (parse x)) xs where pos (I n) ('\n':xs) = new (I (i + n)) xs pos (I n) (x :xs) = pos (I (parse x + (10 * n))) xs parse c = ord c - ord '0'
7.3 Chris Kuklewicz
I tried IOUArray, mallocArray, and in the end came back to to original entry, but slightly optimized with unboxed Int# so it runs ~10% faster:
{-# GHC.Base main = print . sumFile =<< getContents where sumFile = (\rest -> newLine rest 0#) newLine [] rt = (I# rt) newLine ('-':rest) rt = negLine rest 0# where negLine ('\n':rest) soFar = newLine rest (rt -# soFar) negLine ( x :rest) soFar = negLine rest '#
7.6 Current entry
This entry has rather good performance, though space is a bit high. Currently placed 6th.
import Char( ord ) main :: IO () main = getContents >>= print . accP 0 0 accP :: Int -> Int -> String -> Int accP before this [] = before+this accP before this ('\n':xs) = accP (before+this) 0 xs accP before this ('-' :xs) = accN before this xs accP before this (x :xs) = accP before (this*10+ord(x)-ord('0')) xs accN :: Int -> Int -> String -> Int accN before this [] = before-this accN before this ('\n':xs) = accP (before-this) 0 xs accN before this (x :xs) = accN before (this*10+ord(x)-ord('0')) xs
|
http://www.haskell.org/haskellwiki/index.php?title=Shootout/SumFile&oldid=10941
|
CC-MAIN-2014-41
|
refinedweb
| 525
| 81.93
|
, May 26, 2006 at 03:26:56PM +0100, Fadhley, Salim (FID) wrote:
> I am going to try to test this with MX (we don't have it yet at work),
> and see if that makes the problems go away.
It's not enough to install mxDateTime. If you have both datetime and
mxDateTime (and you most probably have) datetime has precedence. You have
to force SQLObject to use mxDateTime. Do this before declaring tables:
from sqlobject import *
from sqlobject import col
if mxdatetime_available:
col.default_datetime_implementation = MXDATETIME_IMPLEMENTATION
See tests\test_datetime.py for examples.
Oleg.
--
Oleg Broytmann phd@...
Programmers don't die, they just GOSUB without RETURN.
Hi,
In order to re-create my validator bug with the example code I posted
some time ago you need to have the following:
1. Use Sybase (It works fine with other databases).
2. Do not have mx.Datetime installed.
The cause of the bug is that in the absence of mx.Datetime, the
Object-Craft sybase driver returns it's own custom types:
I'm guessing that they are Boost-wrapped types from the actual C++
Sybase libraries.
I am going to try to test this with MX (we don't have it yet at work),
and see if that makes the problems go away.
I am working on a patch which will detect if the Sybase libraries are
available, and if so they will add additional code to handle these odd
types.
Sal
--------------------------------------------------------).
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
|
https://sourceforge.net/p/sqlobject/mailman/message/12289333/
|
CC-MAIN-2017-17
|
refinedweb
| 283
| 74.9
|
The Gradle copy task does not preserve file modification times even when not changing the file contents.
There should at least be an option to preserve these times.
This still affects 2.2.
AbstractFileTreeElement.copyTo(File) could be extended by target.setLastModified(getLastModified());, but that would make it the default behavior. I'm not sure if that's a good idea.
Based on Jochen's comment I did the following workaround.
It records all the FileCopyDetails in a list and applies the dates in doLast. (target files have not been created at execution time of eachFile closure.)
task extractSomeStuff(type: Copy) {
from zipTree(tasks.createSomeStuff.archivePath)
destinationDir temporaryDir
def copyDetails = []
eachFile { copyDetails << it }
doLast {
copyDetails.each { FileCopyDetails details ->
def target = new File(destinationDir, details.path)
if(target.exists()) {
target.setLastModified(details.lastModified)
}
}
}
} issue affects Gradle 3.2. I can create a sample Gradle build if you like, but I think the issue should be clear without it.
@Jochen Could you please provide an reproducible example and add it to a new issue on GitHub?.
Thanks, @Jochen.
|
https://issues.gradle.org/browse/GRADLE-2698.html
|
CC-MAIN-2021-31
|
refinedweb
| 176
| 52.56
|
A using the Computer Vision API whenever a new image is uploaded to an Azure Storage account. If you have not already seen my other article on the Computer Vision API, I suggest you take a look at that first.
Using Azure Storage for static web content storage makes sense in lots of ways; it is very cheap, very fast and very easy to work with using the Cloud Explorer tool (Part of the Azure SDK). However in this context, Azure Storage gives us an extra benefit of built-in hooks into Azure Functions.
Azure Functions are one of the newest features in the Azure world (announced at Build 2016) and they are simply a way to execute code in the cloud. They can be triggered on a timer schedule or in response to a web hook, http request, push notification or one of many other types of 'bindings'. If you have ever used Azure Web Jobs, Functions is like web jobs extra.
The third piece of technology in the mix here is the Microsoft Cognitive Services Computer Vision API. Computer Vision does lots of amazing things with digital images, but one of the simpler features is the ability to generate thumbnails. I discussed this in more detail here.
Get Setup
I encourage you to follow along with this sample to get to grips with Functions in a useful way. We are going to buidl a solution that generates smart thumbnails from images uploaded to Azure Storage.
We'll use these three technologies to build a smart thumbnail solution. There are a few things you'll need setup if you want to follow along, they are:
- An Azure Subscription. Get a trial here
- A key for the Computer Vision API. See this article for details on how to get that
- Any version of Visual Studio 2015 (the Community Edition is free by the way)
- Azure SDK for Visual Studio 2015
- Some images to play with
Create an Azure Function App
Functions are very easy to get started with. You simply go to the Azure Portal and go to
New >
Web + Mobile >
Function App.
You'll be asked about resource groups, app service plans etc. You'll also be asked to create or select a Storage Account, this is important because your Function App needs somewhere to put logging information, but having a storage account is especially useful for our solution because we need somewhere to upload images and thumbnails. When you are finished, you'll be presented with the Function App configuration screen (if you cannot find it, just look in your 'web apps' section).
Function Apps are a collection of Functions and the Functions themselves are built from templates that represent that various triggers and bindings available. The home screen offers you a wizard-style experience based 'pre-made' functions, however I find it easier to look at the full list of Function templates. You can see this by clicking
New Function.
You'll see a list of the following templates in both C# and Node (JavaScript):
To follow along with the smart image re-size scenario in this article, choose
BlobTrigger - C# and use these settings:
- Name: Leave as default
- Path:
originals/{name}. This corresponds to a Blob container called 'originals' (we'll create this later) and the
{name}parameter is used to identify the file name of the incoming blob
- Storage Account Connection: Use the
+ newbutton to choose the storage account you create at the start.
When the function is created, avoid the temptation to start coding. We need to do some configuration in our Storage account first.
Create your Blob Containers in Azure Storage
When you created your Function App, you will have created an Azure Storage account as part of the process. We need to add two Blob Containers to this account for our example to work. Blob Containers are like top-level folders within the storage account.
You can find the storage account under the
Storage Accounts menu in the portal. Once you are in the Storage Account, click
Blobs under the services section and add two containers named
originals and
thumbs.
Define the Integration points
Now that the Storage Account is configured, we can tell the Azure Function how to use it. Go to your Function App (under
Web Apps) and load the
BlobTriggerCSharp1 function we created earlier.
Go to the
Integrate tab.
The
Trigger should already have the right settings because you set this when you created the Function. But just double check that the Path is set to
originals/{name}.
You need to define an Output which is where the generated thumbnail gets placed. Click
New Output and use these settings:
- Choose the
Azure Storage Blobtemplate
- Name: Leave the default of
outputBlob
- Path: Set to
thumbs/{name}
- Storage Account Connection: Use the
+ newbutton to choose the storage account you create at the start.
- Save
Implement the CSP (C# script)
You can now implement the code for your function. Go to your Function App (under
Web Apps) and load the
BlobTriggerCSharp1 function we created earlier.
Go to the
Develop tab.
Paste this code into the
Code section, replacing
YOURKEYHERE with your Cognitive Services Computer Vision API ke. Overwrite all existing code).
using System; using System.Text; using System.Net.Http; using System.Net.Http.Headers; public static void Run(Stream myBlob, Stream outputBlob, TraceWriter log) { int width = 320; int height = 320; bool smartCropping = true; string _apiKey = "YOURKEYHERE"; string _apiUrlBase = ""; using (var httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(_apiUrlBase); httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", _apiKey); using (HttpContent content = new StreamContent(myBlob)) { //get response content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/octet-stream"); var uri = $"{_apiUrlBase}?width={width}&height={height}&smartCropping={smartCropping.ToString()}"; var response = httpClient.PostAsync(uri, content).Result; var responseBytes = response.Content.ReadAsByteArrayAsync().Result; //write to output thumb outputBlob.Write(responseBytes, 0, responseBytes.Length); } } }
Now click
Save and check that the log says "compilation succeeded".
Try it out
You can now try the process out by uploading a file to your
Originals blob container.
The easiest way to do this is via the Cloud Explorer tool which is part of the Azure SDK in Visual Studio 2015.
As you upload your files, watch the log in the Azure portal, you'll see it log the function start and end. Once it has completed, you should see your smartly resized file in the 'Thumbs' Blob Container.
In Summary
Azure Functions is a great way to have code hosted in the cloud and execute in response to a wide range of events, schedules and other triggers. When combined with Cognitive Services, you can easily create some very compelling scenarios which can help automate business processes in a smart, easy, quick way.
Thanx.
But its a little expansive, I must pay for Two services here, Azure Functions and Cognitive Services.
Its a better to use a famework instead. Like ImageResizer for example
Its a good point but both Functions and Cognitive Services are free beneath a certain threshold and very cheap beyond that. The problem with something like ImageResizer is that you need to write and manager more code, plus there is no .net core version yet
yes, you right, but what do mean by “plus there is no .net core version yet” !!
did you mean that only Azure Functions are referenced only on .Net Core !! if yes, you are wrong, we can use Full .NET, plus you can find some examples use ImageResizer instead of Cognitive Services
Thanx for article, I really like this approach, But its expansive. We must pay for two services her !!
Use a Framework to resize images (like ImageResizer) instead of Cognitive Service (Computer Vision API).
Hi,
Great article and I followed this steps to replicate this in my account and updated with my Key but the Function fails to complete with below error you help is appreciated
016-06-12T00:10:36.718 run.csx(1,1): error CS0246: The type or namespace name ‘sing’ could not be found (are you missing a using directive or an assembly reference?)
2016-06-12T00:10:36.718 run.csx(21,47): error CS0246: The type or namespace name ‘MediaTypeWithQualityHeaderValue’ could not be found (are you missing a using directive or an assembly reference?)
2016-06-12T00:10:36.718 Compilation failed.
2016-06-12T00:10:52.571 Exception while executing function: Functions.BlobTriggerCSharp1. Microsoft.Azure.WebJobs.Host: Exception binding parameter ‘myBlob’. Microsoft.WindowsAzure.Storage: The remote server returned an error: (404) Not Found.
2016-06-12T00:11:57.237 Function compilation error
2016-06-12T00:11:57.237 run.csx(2,1): error CS1529: A using clause must precede all other elements defined in the namespace except extern alias declarations
|
https://blogs.msdn.microsoft.com/martinkearn/2016/05/06/smart-image-re-sizing-with-azure-functions-and-cognitive-services/
|
CC-MAIN-2018-39
|
refinedweb
| 1,451
| 63.19
|
Quoting Alexey Dobriyan (adobriyan@gmail.com):> I don't like this even more.> > Pid namespaces are hierarchical _and_ anonymous, so simply> set of numbers doesn't describe the final object.> > struct pid isn't special, it's just another invariant if you like> as far as C/R is concerned, but system call is made special wrt pids.> > What will be in an image? I hope "struct kstate_image_pid" with severalSure pid namespaces are anonymous, but we will give each an 'objref'valid only for a checkpoint image, and store the relationship betweenpid namespaces based on those objrefs. Basically the same way that userstructs and hierarchical user namespaces are handled right now.> numbers and with references to such object from other places, so it> seems natural to do alloc_pid() with needed numbers and that attach new> shiny pid to where needed. But this clone_pid is only for task_struct's pids.
|
https://lkml.org/lkml/2009/9/24/339
|
CC-MAIN-2014-15
|
refinedweb
| 149
| 64.1
|
Hi guys, I'm stuck on the following simple problem. Method 1 asks for input. Method 2 gets input and checks it against a criterion - if it fails, we start back at method 1, if it passes, we finish. But it doesn't work - if the input fails the test the first time around, it gets stuck in a loop where the new input isn't recognised. I'm really struggling with understanding why/how this is happening, and I'd be eternally grateful if somebody could help me.
As an example, if the user inputs a value less than 10, the program goes back to Method 1, BUT, if they then enter a (valid) number greater than 10 the system still goes back to Method 1 - it doesn't exit. I suspect it has something to do with using the while loop - I understand I can use an if statement instead, but I want to understand why it fails with the while loop. Any feedback appreciated.
Cheers,
Al.
import java.util.Scanner; public class TESTINGCODE { public static void main(String[] args) { Method1();} public static void Method1(){ System.out.println("Enter an integer greater than 10"); Method2();} public static void Method2(){ Scanner input = new Scanner(System.in); int value = input.nextInt(); while(value < 10){ Method1(); } } }
|
http://www.javaprogrammingforums.com/whats-wrong-my-code/20440-simple-question-re-while-loop-input.html
|
CC-MAIN-2016-30
|
refinedweb
| 215
| 71.65
|
Opened 9 years ago
Closed 9 years ago
Last modified 9 years ago
#3439 closed (fixed)
django.dispatch.* is grossly slow
Description
Attached is a refactoring chopping off a good chunk of dispatch's overhead; hard to test it standalone, so testing was done for simple iteration over records and isolating the diff in the profiling for the refactoring.
Short version, attached patch shows 5x boost in dispatch speed; for iteration (just that, no rendering) over 53k records, time drops from ~15.5s to ~11.6s just by cleaning up dispatch.*
The internal data structs dispatch is using are still fairly innefficient- scaling will be an issue the more receivers there are for dispatched signals. So... can clean that up further, but there isn't any documentation re: the expectations of dispatcher. For example- order of connection to a signal, must the order be maintained for notifications at a specific sender/signal level? If I connect (in this order) func f1, func f2, both to object("foo") signal Any, must they be notified in order f1,f2?
I realize pydispatcher is a seperate project- that said, they've already moved onto 2.0, and there are several 1.0.x's for pydispatcher released already- djangos' bundled copy is still at 1.0.0. Whats the intention? Intending on keeping it in sync, or is it just a fork point?
Either way, the attached refactoring is not covered by tests at the moment- mainly since there are no tests in django for dispatcher. Would like to get feedback on the expectations of dispatcher (f1/f2 from above for example) prior to writing those tests, since the implementation (and google for that matter) lack any material on it.
Finally, due to the massive number of calls to send (thus to getAllReceivers and friends), normal seperation (getAllReceivers using getReceivers for example) was intentionally broken down a bit- in other words, inlined a few functions. The codes invoked enough that the overheads seperation really isn't worth it, especially if you're not actually using signals for the most part (thus dispatcher is pretty much pure time waste).
Attachments (2)
Change History (8)
Changed 9 years ago by (removed)
comment:1 Changed 9 years ago by SmileyChris
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
Changed 9 years ago by (removed)
import of upstream tests, fix deregistration bug
comment:2 Changed 9 years ago by Simon G. <dev@…>
- Triage Stage changed from Unreviewed to Accepted
comment:3 Changed 9 years ago by (removed)
Minor optimization I missed, although it's quadratic worst case correction; in _killBackref
while senderkey in receivers_list: try: receivers_list.remove(senderkey) except: break
is... certifiably insane. Utterly.
No idea how I missed that one...
receivers_list = [x for x in receivers_list if senderkey != x]
avoids quadratic worst case for if receivers_list is all senderkey; python lists are arrays, popleft forces everything beyond to be moved one to the left (worth noting context, and resolve_variable have the same whackyness).
comment:4 Changed 9 years ago by jacob
This patch works quite well for me -- major props for tests, too :)
However, for some reason I can't understand at all, it seems to be failing under sqlite. I'm going to check the patch in anyway since the performance gains are measurable, but Brian, if you're still following this thread, can you *please* take a look at it under sqlite and try to figure out what's going on?
comment:5 Changed 9 years ago by jacob
- Resolution set to fixed
- Status changed from new to closed
(In [4588]) Fixed #3439: vastly improved the performance of django.dispatch (and added tests!). Thanks to Brian Harring for the patch. Note that one of the new tests fails under sqlite currently; it's not clear if this is a sqlite problem or a problem with the tests, but it appears not to be a problem with the dispatcher itself.
comment:6 Changed 9 years ago by (removed)
Well... I guess since you said please. ;)
Which test is failing? The code *should* be totally unaware of sqlite also- quick grep of backends namespace, nothing in there seems to know of dispatch, so I'm semi at a loss why you're running into issues. Additionally... my testing was strictly against sqlite, so I'm a fair bit curious ;)
dispatcher refactoring round 1.
|
https://code.djangoproject.com/ticket/3439
|
CC-MAIN-2016-07
|
refinedweb
| 729
| 59.84
|
26 CFR 25.6151-1 - Time and place for paying tax shown on return.
The tax shown on the gift tax return is to be paid by the donor at the time and place fixed for filing the return (determined without regard to any extension of time for filing the return), unless the time for paying the tax is extended in accordance with the provisions of section 6161. However, for provisions relating to certain cases in which the time for paying the gift tax is postponed by reason of an individual serving in, or in support of, the Armed Forces of the United States in a combat zone, see section 7508. For provisions relating to the time and place for filing the return, see §§ 25.6075-1 and 25.6091-1.
Title 26 published on 2013-04-01
no entries appear in the Federal Register after this date.
|
http://www.law.cornell.edu/cfr/text/26/25.6151-1
|
CC-MAIN-2014-23
|
refinedweb
| 148
| 68.1
|
PackagingDrafts/MultilibTricks
From FedoraProject
Revision as of 16:47, 25 August 2011
Multi lib tricks
Architecture independent files
File conflicts
For architecture independent files conflicts should be avoided, so the files should be identical among arches. It may involve some work with upstream when header files include architecture specific files, for example header files which contains autoconf conditionals like HAVE_INT32.
Another problem that sometimes appears is with gzipped files. Normally gzip will embed the timestamp of the file in its output, and this can cause a multilib conflict. The way to avoid this is to use gzip's '-n' option whenever files are gzipped at build time.
If you are not sure what the reason for a particular conflict is, fetch the packages from two multilibbed architectures (e.g. i386 and x86_64) and unpack them like this:
mkdir i386 x86_64 rpm2cpio blah-1.2-3.i386.rpm | (cd i386; cpio -idv) rpm2cpio blah-1.2-3.x86_64.rpm | (cd x86_64; cpio -idv)
Then you can use the diff or cmp utilities to discover exactly what is different between the conflicting files.
myautoconf.h files with a size in them
Some packages install myautoconf.h type files which will have something in them relating to the byte size of (size_t) or (void *) at compile time, the possible way to get around this problem is to change from myautoconfig.h to myautoconfig-32.h and myautoconfig-64.h (depending on the platform) and have myautoconfig.h containing just the following on all platforms:
#include <bits/wordsize.h> #if __WORDSIZE == 32 #include "myautoconfig-32.h" #elif __WORDSIZE == 64 #include "myautoconfig-64.h" #else #error "Unknown word size" #endif
This kind of API specification is bad in most cases, however, since an API should be completely platform independent.
If what is needed are integer of a length independent from the platform, integers like
int32_t from inttypes.h can be used.
Doxygen default footers include the date. This leads to conflict since
doc files are not generated at the exact same time. To use a custom
footer without the date, it is possible to modify the dox file used to
drive the documentation generation, and set
HTML_FOOTER, for example:
HTML_FOOTER = no_date_footer.html
The
no_date_footer.html file could be along:
<hr size="1"><address style="text-align: right;"><small> Generated for $projectname by <a href=" index.html"><img src="doxygen.png" alt="doxygen" align="middle" border="0"></a> $doxygenversion</small></address> </body> </html>
PNG images
PNG images generated for example by doxygen can include the date as part of the PNG format. This leads to conflicts since the *.png files are not generated at the exact same time. To solve this, you can set the internal timestamps of PNG images to a reference timestamp which can be achieved by using the python script png-mtime .
Put this command into your spec file so that it applies to the PNG files where the reference date/file shall be used.
Timestamps
Files should also have the same timestamps. For most of the files this means taking care to keep the timestamps (which should be done in every package). For autoconf based packages this is in general achieved by doing something along:
make install DESTDIR=$RPM_BUILD_ROOT INSTALL="%{__install} -p"
For the architecture independent files generated at build time it is possible to use the timestamp of a reference file. For example:
touch -r ../cernlib.in src/scripts/cernlib
or
touch -r NEWS $RPM_BUILD_ROOT%{_includedir}/Xbae/patchlevel.h
Multiarch, binaries and compilation scripts
In multilib environments there is a preferred architecture, 64 bit over 32 bit in x86_64, 32 bit over 64 bit in ppc64 and sparc64. When a conflict is found between two packages corresponding with different arches, the installed file is the one from the preferred arch. This is very common for executables in /usr/bin, for example. If the file /usr/bin/foo is found in an x86_64 package and in an i386 package, the executable from x86_64 will be installed.
These implicit conflicts are accepted in Fedora, though they are considered bad by some contributors. There may be some long-term solution for these issues, but before that there are some tricks that may allow to avoid those conflicts that are presented below. Once again they are optional.
- In compilation scripts (in general named along mylib-config) it should be advisable to remove
-L$libdirwhen $libdir is the default library directory on this platform. Indeed this is automatically added when linking with the gcc compiler (it may be needed when linking with ld, but using ld is wrong in general, so a user linking with ld should add the flag by himself).
- binaries may be put outside of the packages selected to be included in multilib repositories. In general the devel subpackages and their dependencies are included in multilib repositories. A typical split of a package is:
- foo for the binaries
- foo-libs for the libraries
- foo-devel for the development headers, and development symlinks
foo-devel and foo both requires foo-libs, and foo isn't present in multilib repository.
- wrapper scripts may be used to run a binaries based on which one is present. Here is a script example (adapted from firefox)
ARCH=$(uname -m) case $ARCH in x86_64 | sparc64 | s390x | ppc64) LIB_DIR=/usr/lib64 SECONDARY_LIB_DIR=/usr/lib ;; * ) LIB_DIR=/usr/lib SECONDARY_LIB_DIR=/usr/lib64 ;; esac if [ ! -x $LIB_DIR/package-0.0.1/foo ] ; then if [ ! -x $SECONDARY_LIB_DIR/package-0.0.1/foo ] ; then echo "Error: $LIB_DIR/package-0.0.1/foo not found" if [ -d $SECONDARY_LIB_DIR ] ; then echo " $SECONDARY_LIB_DIR/package-0.0.1/foo not found" fi exit 1 fi LIB_DIR=$SECONDARY_LIB_DIR fi
Another way to handle those conflicts could be to have a different directory for each architecture, even for executables, enabling Fedora to be multiarch and not only multilib.
Splitting libraries into separate packages
If you have binaries, libraries, configuration, and data files all in the same package, conflicts can also arise. One way to fix this is to split libraries off into a separate lib<foo> or <foo>-libs package. However, some care must be done when doing this in order to ensure proper upgrades.
For example, if you previously had:
foo-1.1-1
that had binaries, libraries, etc. and had file conflcits, and you split the package into: into:
foo-1.1-2 foo-libs-1.1-2
you should add:
Obsoletes: foo < 1.1-2
in the %package section for foo-libs. This ensures that an upgrade with yum will remove the older foo for any alternative architecture.
|
https://fedoraproject.org/w/index.php?title=PackagingDrafts/MultilibTricks&diff=prev&oldid=250399
|
CC-MAIN-2016-40
|
refinedweb
| 1,090
| 55.44
|
Struts dispatch action - Struts
Struts dispatch action i am using dispatch action. i send the parameter="addUserAction" as querystring.ex:
at this time it working fine.
but now my problem is i want to send another value as querystring for example
Struts Action Classes
Struts Action Classes 1) Is necessary to create an ActionForm to LookupDispatchAction.
If not the program will not executed.
2) What is the beauty of Mapping Dispatch Action
Adduser.jsp in struts Dispatch
Adduser.jsp in struts Dispatch AddUser.jsp:
<%@taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@taglib uri="/WEB-INF/struts-logic.tld" prefix
Dispatcher Result Example
Dispatcher Result Example
The Dispatcher Result forwarded the action to the different action. The
Dispatcher does not looses the request data. It forwarded the same to the
dispatch the request data to the desired action. To use
Struts Action Chaining
Struts Action Chaining Struts Action Chaining Action Class
Struts Action Class What happens if we do not write execute() in Action class
Doubt Regarding Charts
Doubt Regarding Charts Hi,
Can you please help me out by answering "hoe to include charts in core java code and struts code"
thanks in advance,
Swaroop Eswara
Please visit the following link:
Jfreechart
Java - Struts
in DispatchAction in Struts.
How can i pass the method name in "action... more the one action button in the form using Java script.
please give me... 2 action-validation.xml not loading
Struts 2 action-validation.xml not loading Hi All,
I am getting... error
SERVER : Caught exception while loading file package/action-validation.xml
Connection refused: Connect - (unknown location)
The path of my action
Advance Struts Action
Advance Struts2 Action
In struts framework Action is responsible for controlling the request coming
from the clients. It is a java class class it can... for writing action classes that
provides a lots of flexibility. The most common which how to solve actionservlet is not found error in dispatch
doubt regarding JSF
doubt regarding JSF Hi,
pls explain what is difference between struts &JSF?
pls explain what is difference between SPRING &JSF
No action instance for path
;
</action-mappings>
</struts-config>... struts@roseindia.net
*/
/**
* Struts File Upload Action Form...No action instance for path <%@ taglib uri="http
attribute in action tag - Java Beginners
attribute in action tag I'm just a beginner to struts.
The name tag(name="bookListForm") is used to define the form used with the action class. But i`m not clear about the attribute tag(attribute
Java - Struts
doubt is when we are using struts tiles, is there no posibulity to use action class...
in struts-config file i wrote the following action tag...Java hello friends,
i am using struts, in that i am using tiles Redirect Action
Struts 2 Redirect Action
In this section, you will get familiar with struts 2 Redirect
action and learn to use it in the struts 2 application.
Redirect After Post:
This post
The password forgot Action is invoked... password action requires user name and passwords same as you had entered
during what is the default Action class in struts 1) Difference between Action form and DynaActionForm?
2) How the Client request was mapped to the Action file? Write the code and explain
doubt in struts - Struts
doubt in struts i don't understand the concept on Resource bundle in struts can u please help me out
Capturing JSP Content Within My Strut Action Servlet - JSP-Servlet
or Struts Action ... */
BufferedHttpResponseWrapper wrapper = new...Capturing JSP Content Within My Strut Action Servlet My end goal... a dispatch to the JSP and is some how able to hold onto the response so as to be able
struts
struts hi
i would like to have a ready example of struts using "action class,DAO,and services" for understanding.so please guide for the same.
thanks Please visit the following link:
Struts Tutorials
Action in Struts 2 Framework
action provides the processing logic for a specific URL with which it is linked. Actions are mostly associated with a HTTP request of User.
The action class..., and select the view result page that should send back to the user
action class
Introduction to Action interface
Introduction To Struts Action Interface
The Action interface contains the a single method execute(). The business
logic of the action is executed within... from user.
NONE- If the execution of action is successful but you do
not want Forward Action Example
Struts Forward Action Example
.....
Here in this example
you will learn more about Struts Forward Action... an Action Class
Developing the Action Mapping in the struts-config.xml
Java - Struts
Java this error occur when we run our struts wev b applcation
Servlet action is currently unavailable
getting null value in action from ajax call
getting null value in action from ajax call Getting null value from ajax call in action (FirstList.java)... first list is loading correctly. Need... language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding
struts when the action servlet is invoked in struts? Hi Friend,
Please visit the following link:
Thanks
code - Struts
code How to write the code for multiple actions for many submit buttons. use dispatch action
struts - Struts
Struts dispatchaction vs lookupdispatchaction What is struts...; Hi,Please check easy to follow example at
Reg struts - Struts
Reg struts Hi, Iam having Booksearch.jsp, BooksearchForm.java,BooksearchAction.java. I compiled java files successfully. In struts-config.xml Is this correct? I would like to know how do i have to make action
Regarding struts validation - Struts
Regarding struts validation how to validate mobile number field should have 10 digits and should be start with 9 in struts validation? Hi...
-------------------------------------------------------------
For more information :
Writing action classes in struts2.2.1
Writing action classes
Action Classes
AdmissionAction.java- It action class for admission process. It
takes data from admission form and process for registration. There is a execute
method which holds connection code
Why Struts 2
core interfaces are HTTP
independent. Struts 2 Action classes... handling per action, if
desired.
Easy Spring
integration - Struts 2...
Why Struts 2
The new version Struts
Configuring Actions in Struts application
Configuring Actions in Struts Application
To Configure an action in struts application, at first write a simple Action
class such as
SimpleAction.java... the package roseindia extends the the
struts default package.
<action name
java - Struts
friend.
what can i do.
In Action Mapping
In login jsp
Hi friend,
You change the same "path" and "action" in code :
In Action Mapping
In login jsp
For read more information on struts
java struts error - Struts
java struts error
my jsp page is
post the problem...*;
import javax.servlet.http.*;
public class loginaction extends Action{
public... on struts visit to :
Thanks how can i get dynavalidation in my applications using struts... :
*)The form beans of DynaValidatorForm are created by Struts and you configure in the Struts config :
*)The Form Bean can be used
struts
struts <p>hi here is my code can you please help me to solve...;
<p><html>
<body></p>
<form action="login.do">...*;
import org.apache.struts.action.*;
public class LoginAction extends
Chain Action Result Example
;
<action...Chain Action Example
Struts2.2.1 provides the feature to chain many actions... in an application by applying
Chain Result to a action. A Chain Result is an result type
load next page after submitting how to submit the details and how to go the next page after submitting.please clarify my doubt I don't know how to submit details.
1)page1.html:
<html>
<form type=get action
Doubt
Submit and process form how to submit the details and how to go the next page after submitting.please clarify my doubt I don't know how to submit details.
1)page1.html:
<html>
<form type=get action
|
Struts
Built-In Actions |
Struts
Dispatch Action |
Struts
Forward Action |
Struts
LookupDispatchAction |
Struts MappingDispatchAction...
Works? |
Struts Controller |
Struts Action Class |
Struts
ActionFrom Class <p>hi here is my code in struts i want to validate my...;gt;
<html:form
<pre>... RegisterAction extends Action
{
public RegisterAction()
{="
Doubt regarding charts and jsp
Doubt regarding charts and jsp Hi,
I successfully executed the bar chart in normal java application.
But I want the Bar Chart to be executed... java application output to an jsp page?
thanks in advance
Put the jar
struts - Struts
-config.xml
Action Entry:
Difference between Struts-config.xml...struts hi,
what is meant by struts-config.xml and wht are the tags...
2. wht is the difference b/w the web.xml and struts-config.xml
3. what
|
http://www.roseindia.net/tutorialhelp/comment/61065
|
CC-MAIN-2014-41
|
refinedweb
| 1,432
| 57.16
|
Shared Bookmarks
This page serves as a shared bibliography for working group members. Feel free to add, classify, reorganize, and annotate!
Proposed design principles are in bold throughout below.
Contents
- General Usability Design Principles
- Usable Security Design Guidelines
- Usability Studies about Internet Security
- Browser Security and Anti-phishing Proposals
- Secure Web Development Practices
- Other
General Usability Design Principles
The {Design, Psychology, Psychopathology} of Everyday Things, Don Norman. Chapter 1. This text is not available online, thefollowing concepts are the ones applicable to the working group.
- affordance
- an aspect of an object which makes it obvious how the object is to be used
- conceptual model
- a user's understanding of what something does and how it works
Ten Usability Heuristics, by Jacob Nielsen Here are the ones Mez thinks will be particularly useful for us: Match between system and the real world The system should speak the users' language, with words, phrases and concepts familiar to the user, rather than system-oriented terms. Follow real-world conventions, making information appear in a natural and logical order..
- "Humane Interface, The: New Directions for Designing Interactive Systems", Chapter 2-3, by Jef Raskin
At any given moment, a user has only a single locus of attention, a feature or an object in the physical world or an idea about which you are intently and actively thinking.
- The user does not have complete control over what their "locus of attention" is. The environment can shift it, for example a loud noise.
- Things outside the user's locus of attention go unnoticed. Humans are wired to ignore things that aren't their current locus of attention.
- A detail in the user's locus of attention is only in short term memory and will be forgotten quickly once the detail is no longer the user's locus of attention.
Persistent use of any interface will cause the user to develop habits. Reactions to things outside the user's locus of attention are largely determined by these habits. User interfaces should leverage habit formation to shape the user's workflow.
- "Designing the User Interface", Chapter 2, by Ben Shneiderman
Know thy user All design should begin with an understanding of the intended users. This includes population profiles that reflect age, gender, physical abilities, education, cultural or ethnic background, training, motivation, goals, and personality. An example of creating profiles would be the division of users into novice or first-time users, knowledgeable intermittent users, and expert frequent users.
Create task profilesAfter drawing out user proifiles, designers should formally write down user tasks.
- Strive for consistency. Consistency should be a goal for the appearance of data displayed, the language used, and the sequences of actions required.
- Offer informative feedback. For every user action, there should be system feedback.
- Design dialogs that yield closure. When an action has been completed it should be clear to the user that the action was successful and that they can consider their task completed and can move on to the next one.
- Offer error prevention and simple error handling. Whenever possible, design the system so the user can not make serious errors.
- Reduce short-term memory load. Users should not be expecting to remember information across a number of screens.
- When displaying data to the user, the format should be familiar to the operator and should be related to the tasks required of the user.
- Present data only if they assist the operator.
- Techniques to get the user's attention
- intensity: only use two levels of color intensity
- marking: underline, enclose in a box, point to with an arrow
- size: use up to 4 sizes
- Inverse video: use inverse coloring
- blinking: use blinking displays in limited areas with great care
- color blinking: use changes in color with great care and in limited areas.
- audio: use soft tones for regular positive feedback, and harsh sounds for rare emergency conditions
Usable Security Design Guidelines
Why Johnny can't encrypt, Alma Whitten and John D Tygar
The user must be aware of the task they are to perform.
- We are focusing on presenting the user with information they can use to make decisions regarding the security of a web site. The user must be aware of what information they should use to make this decision, this includes being aware of where to look for this information.
The user must be able to figure out how to perform the task.
- They must know what the information presented to them means, and know what the relevance of the information is.
- Security is always a secondary goals, it is never the main focus of a user.
- The user can't be expected to actively seek information about security, the information should be presented in a way that is easily accessible, and understood at a glance.
The user should be given feedback when the state of the security of a page is changed.
- The feedback should be relevant, and should be given in a way that won't annoy the user.
Alma Whitten and J. D. Tygar, “Safe Security Staging”, CHI 2003 Workshop on Human-Computer Interaction and Security Systems, Ft. Lauderdale, Florida. Safe staging. Safe staging is “a user interface design that allows the user freedom to decide when to progress to the next stage, and encourages progression by establishing a context in which it is a conceptually attractive path of least resistance.” Metaphor tailoring. Metaphor tailoring starts with a conceptual model specification of the security related functionality, enumerates the risks of usability failures in that model, and uses those risks to explicitly drive visual metaphors.
Mary Ellen Zurko, Charlie Kaufman, Katherine Spanbauer, Chuck Bassett, Did You Ever Have To Make Up Your Mind? What Notes Users Do When Faced With A Security Decision, Proceedings of 18th Annual Computer Security Applications Conference, Las Vegas, Nevada, December 2002. False positive warnings rapidly dilute warning usability. "the common software practice of warning users of danger but letting them click on something to proceed anyway" does not provide security in a large portion of the user population. The same overall issue comes up in Wu, Miller and Garfinkle, and in Gutmann, below.
Paul DiGioia, Paul Dourish, “Social Navigation as a Model for Usable Security”, Proceedings of the 2005 Symposium On Usable Privacy and Security, Pittsburgh, Pennsylvania, pp. 101 – 108. Integrated security aligns security with user actions and tasks so that the most common tasks and repetitive actions are secure by default. Provides information about security state and context in a form that is useful and understandable to the user, in a non-obtrusive fashion. Although actually about privacy, which I (Mez) contend is easier than security, since it's information the user understands in the first place.
- Andrew S. Patrick, Pamela Briggs, and Stephen Marsh, "Designing Systems That People Will Trust", Security and Usability: Designing Secure Systems that People Can Use, ed. Lorrie Faith Cranor and Simson Garfinkel.
- The trust design guidelines tie directly in to the kinds of things phishing attacks do or can do to successfully get users to trust them (and overlook, ignore, or explain away security context information that contradicts their trustworthienss). Some examples from the chart on page 95 (including at least one that would be hard for a phisher) [wiki formatting issue; I attempted to number them with the numbers from the table but so far have failed]:
- Maximize the consistency, familiarity, or predictability of an interaction both in terms of process and visually.
- Include seals of approval such as TRUSTe.
- Provide explanations, justifying the advice or information given.
- Provide independent peer evaluation such as refernces from past and current users and independent message boards.
- Provide clearly stated security and privacy statements, and also rights to compensation and return.
Offer a personalized service that takes account of each client's needs and preferences and reflects its social identity.
Phishing Tips and Techniques, Peter Gutmann
- Humans evaluate alternatives serially, generating options one at a time and accepting the first that works (Singular Evaluation Approach)
- Habituation and user conditioning mean that people don't read dialogs or think twice about having to enter their passwords
- People are very susceptible to confirmation bias, and are likely to accept an invalid yet plausible conclusion that supports their hypothesis
Having a user change their behaviour due to the absence of a stimulus is hard, and goes against evolutionary training
- Users don't understand that it's easy to forge web content, relating it to the difficulty of forging real-world content
Usability Studies about Internet Security
Browser Security and Phishing Studies
Why Phishing Works, Rachna Dhamija, J.D. Tygar, Marti Hearst
- User characteristics that are commonly exploited by phishers:
- Lack of knowledge.
- Users don't know what the URL format is, they don't know ebay-security.com has nothing to do with ebay.com
- They don't realize things can be spoofed (like the sender of an email)
- Don't know what the different versions of the lock icon mean
- Don't know the difference between the browser chrome and the content, and what controls the info in each
- Visual Deception
- URL deception. e.g. paypal with a one instead of an L
- Images of a hyperlink to a site, that are a hyperlink to another site
- Images that mimic windows
- Borderless pop-ups that belong to another site
- Recreating look and feel of the legitimate site
- Bounded attention
- Users don't pay attention to security or security indicators
- Users don't notice the absence of security indicators
- Participants were asked to distinguish legitimate websites from spoofed phishing websites. They were asked to assume the role of someone who had clicked on a link in email and arrived at the website in question.
- Results: Despite the heightened security awareness and educated users, the study found that some phishing websites were able to fool a large fraction of participants.
- 23% of participants in our study did not look at the address bar, status bar, or any SSL security indicators (HTTPS, lock icon)
- Popup warnings about fraudulent certificates were ineffective: 15 out of 22 participants proceeded without hesitation when presented with warnings.
- Participants proved vulnerable across the board to phishing attacks- neither education, age, sex, previous experience, hours of computer use showed a statistically significant correlation with vulnerability to phishing. (This doesn't mean differences don't exist, just that they were not found in this sample)
- Study showed that users don't have a clear understanding of what the security cues mean, or where they should be located (chrome or content). Also showed users could easily be tricked by pages that had a professional feel and animations - users relied more on the content of a page than the security indicators, users don't pay attention to indicators in the periphery.
Do Security Toolbars Actually Prevent Phishing Attacks? by Wu, Miller and Garfinkel
Methodology: Wu created dummy accounts in the name of John Smith at various e-commerce websites. The participants were asked to play the role of John Smith's personal assistant, to process email messages on his behalf, and to protect his passwords. Wu's study design also featured a tutorial, where users were trained on how to use the anti-phishing toolbar.
- Results found that participants were fooled 34% of the time. Even when asked to focus on the toolbars, many participants ignored them when webpages looked convincing enough.
- Users do not understand phishing attacks, or don't realize how sophisticated phishers can be.
- Users entered information at spoofed sites where the content looked professional, or similar to what they had seen before. A user can either think a phishing site doesn't have the resources to recreate aspects of the site (videos, images) or wouldn't bother to look professional. Some users think they should only be weary of sites with spelling errors, or simple content.
- Users ignore warning signs, or reason them away. In the case of a url that contains the real site's name, but isn't in the right format. User's gave a number of reasons why this might be the case. Example: Maybe is the real site, and Target is using it because was taken.
- Users don't pay attention to toolbars, or don't look at them at all. Users from the study admitted to not looking at the toolbar 25% of the time.
- The toolbars were used more effectively when a tutorial was given on the toolbar's use.
Users rely on the content of a web page to make security decisions. Buttressed by Why Phishing Works and Patrick, Briggs, and Marsh, above, and Whalen and Inkpen below.
- Even when a user initially checks for security information, they don't check the information continually throughout a session.
- A few common phishing attacks
- Using a similar name. Example: paypal with a one instead of an L
- Using an IP address instead of the domain name in a link.
- Hijacking a server of a legitimate company and hosting a phishing site.
- Displaying the real site in a browser, with a borderless pop-up window to the phishing site requesting personal information
Gathering Evidence: Use of Visual Security Cues in Web Browsers, Tara Whalen and Kori M. Inkpen
- Study asked participants to perform common online browsing tasks, some of which required participants to login to an account and make purchases. An eyetracker was used to reveal whether security indicators were checked by participants. This includes looking for the lock, looking for https, clicking on the lock - checking the certificate.
Methodology: Participants used login and credit card information created for the study; they were asked to treat the data as their own and to keep it confidential. In the second half of the study, participants were specifically instructed to behave securely.
- They found that unless instructed to behave securely, many participants did not check whether a page was secure.
- Results suggested people also use the security statements made by a company on their web page to judge whether a site is secure.
- Most of the users weren't aware the lock could be clicked for more information. Of those who knew they lock could be clicked, only 2/16 knew what a certificate was but only 1 of them was able to extract useful information from the certificate.
- Using the eyetracker, when asked to behave securely, users did look for the lock and did look for https. They even did this at about the same time, suggesting users know the two are linked in some way. The eyetracker data also showed the users looking in the lower left and right hand corners of the browser for the lock icon - suggests a standard is needed across browsers.
- Users don't continue to look for security cues after log-in is complete.
"Decision Strategies and Susceptibility to Phishing" Julie Downs, Mandy Holbrook, Lorrie Faith Cranor
Methodology: users drawn from a random cross section of the Pittsburg PA population. Users were questioned & observed while responding to various simulated possible phishing scenarios. Browsers used were MSIE, Firefox, Netscape, & Safari. Their report will be very valuable to the work of WSC.
- Most participants [85%] had seen lock images on a web site, and knew that this was meant to signify security, but most had only a limited understanding of what how to interpret locks, e.g., “I think that it means secured, it symbolizes some kind of security, somehow.” Few knew that the lock icon in the chrome (i.e., in the browser’s border rather than the page content) indicated that the web site was using encryption or that they could click on the lock to examine the certificate. Indeed, only 40% of those who were aware of the lock realized that the lock had to be within the chrome of the browser.
Only about a third [35%] had noticed a distinction between "http://" and "https://" URLs. Of those some did not think that the “s” indicated anything. But those who were aware of the security connotation of this cue tended to take it as a fairly reliable indication that it is safe to enter information. For those people this extra security was often enough to get them beyond their initial trepidations about sharing sensitive information, e.g., “I feel funny about putting my credit card number in, but they say it is a secure server and some of them say ‘https’ and someone said that it means it’s a secure server.”
- About half [55%] had noticed a URL that was not what they expected or looked strange. For some, this was a reason to be wary of the website. For others, it was an annoyance, but no cause for suspicion. The other half [45%} appeared to completely ignore the address bar and never noticed even the most suspicious URLs.
- Participants appeared to be especially uncertain what to make of certificates. Many respondents specifically said that they did not know what certificates were, and made inferences about how to respond to any "mysterious message" mentioning certificates. Some inferred that certificates were a "just a formality". Some used previous experience as their basis for ignoring it, e.g., “I have no idea [what it means], because it’s saying something about a trusted website or the certificate hasn’t, but I think I’ve seen it on websites that I thought were trustworthy.”
- Almost half [42%] recognized the self-signed certificate warning message as one they'd seen before. A third [32%] always ignored this warning, a fourth [26%] consistently avoided entering sites when this warning was displayed, and the rest responded inconsistently.
- When asked about warnings generally, only about half of participants recalled ever having seen a warning before trying to visit a web site. Their recollections of what they were warned about were sometimes vague, e.g., “sometimes they say cookies and all that,” or uncertain, e.g., “Yeah, like the certificate has expired. I don’t actually know what that means.” When they remembered warnings about security, they often dismissed them with logical reasoning, e.g., “Oh yeah, I have [seen warnings], but funny thing is I get them when I visit my [school] websites, so I get told that this may not be secure or something, but it’s my school website so I feel pretty good about it.”
- Only half of participants had heard the term "phishing". The other half couldn't guess what it meant. Most participants had heard the term "spyware" but a number of those believed it was something good that protects one's computer from spies.
What Do They Indicate? Evaluating Security and Privacy Indicators, Lorrie Faith Cranor
Criteria for evaluating indicators:
- Does the indicator behave correctly when not under attack? Does the correct indicator appear at the correct time without false positives or false negatives?
- Does the indicator behave correctly when under attack? Is the indicator resistant to attacks designed to deceive the software into displaying an inappropriate indicator?
- Can the indicator be spoofed, obscured, or otherwise manipulated so that users are deceived into relying on an indicator provided by an attacker rather than one provided by their system?
- Do users notice the indicator?
- Do the users know what the indicator means?
- Do users know what they are supposed to do when they see the indicator?
- Do they actually do it?
- Do they keep doing it?
- How does the indicator interact with other indicators that may be installed on a user's computer?
The Emperor's New Security Indicators Stuart Schechter, Rachna Dhamija, Andy Ozment, and Ian Fischer.
- Measures the efficacy of HTTPS indicators and site-authentication images
- Reveals problems with the use of role playing in security usability studies
- Provides a study design in which participants appear to put their own credentials at risk
An Evaluation of Extended Validation and Picture-in-Picture Phishing Attacks Collin Jackson (Stanford University), Dan Simon (Microsoft Research), Desney Tan (Microsoft Research, Adam Barth (Stanford University)
- Evaluates the ability for IE7 with Extended Validation certs to help users detect phishing attacks (homograph attacks where the URL is obscured and Picture in Picture Attacks where images of chrome are copied into the webpage content.
- Result: PIP attacks were very effective in fooling users with or without EV certs. Training with IE7 help documentation actually reduced users' ability to detect attacks.
Social Phishing Tom Jagatic, Nathaniel Johnson, Markus Jakobsson, and Filippo Menczer, to appear in Communications of the ACM.
- A social network was used for extracting information about social relationships. The researchers used this information to send phishing email to students on a university campus that appeared to come from a close friend.
- Results: 72% of users responded to phishing email that was from a friend's address, while only 16% of users responded in the control group to phishing email from an unknown address.
Designing Ethical Phishing Experiments: A study of (ROT13) rOnl auction query features M. Jakobsson and J. Ratkiewicz, WWW2006.
- Jakobsson and Ratkiewicz used the features of an online auction website to send simulated phishing emails to that site's members. The phishing email only appeared to be a phishing attempt; to respond to the message the recipient had to provide their credentials to the real auction site. Researchers could learn that users logged into the auction site if they received a response to their message, without having to collect user credentials.
- Experiments revealed that, on average, 11% of users logged into the auction site to respond to the illegitimate messages.
The Human Factor in Phishing, Markus Jakobsson, To appear in Privacy & Security of Consumer Information '07
- discusses the importance of understanding psychological aspects of phishing, and review some recent findings.
- critiques some commonly used security practices and suggest and review alternatives, including educational approaches.
Designing and Conducting Phishing Experiments, P. Finn and M. Jakobsson. To appear in IEEE Technology and Society Magazine, Special Issue on Usability and Security
- This paper talks about ethical issues and IRB approval for phishing studies.
- The authors argue that the "informed consent" requirements should be waived for phishing studies.
Do consumers understand the role of privacy seals in e-commerce?, Trevor T. Moores and Gurpreet Dhillon. Communications of The ACM, Volume 48, Issue 3 (March 2005).
This paper discusses a user study where participants were supposed to recognize web seals (e.g. TRUSTe, BBBOnline, etc.). The study found that 42% recognized TRUSTe, 29% recognized BBBOnline, 15% (incorrectly) recognized the "Web Shield" logo which was made up for this study, and 8% recognized CPA WebTrust.
- "This finding suggests that any official-looking graphic placed on a Web site has an equal chance of persuading the consumer that the site is trustworthy, regardless of any relation between the graphic and the actual Web assurance seals."
- Most users unaware how a site gets a seal.
Empirical Studies about Password Behavior, Phishing and Privacy Concerns
A Large Scale Study of Web Password Habits D. Florencio and C. Herley, WWW 2007, Banff.
An Empirical Analysis of the Current State of Phishing Attack and Defense, Tyler Moore and Richard Clayton, Computer Laboratory, University of Cambridge
An Empirical Approach to Understanding Privacy Valuation, Luc Wathieu and Allan Friedman, Harvard Business Review
- Contrary to some research, the chief privacy concern appears based on data use, not data itself.
- There is consumer demand for social control that focuses on data use.
- Sophisticated consumers care about economic context and indirect economic effects.
Why Johnny Can't Encrypt: A Usability Evaluation of PGP 5.0 Alma Whitten and J.D. Tygar
- an early usability study that asked participants to use email encryption software.
- participants were asked to assume the role of a political campaign coordinator who was tasked with sending sensitive email messages to other campaign volunteers.
- The study concluded that a majority of participants could not successfully sign and encrypt a message using PGP 5.0.
Johnny 2: A User Test of Key Continuity Management with S/MIME and Outlook Express Garfinkel and Miller
- They used the same scenario as Whitten and Tygar to test a Key Continuity Management (KCM) email encryption interface.
- In addition, they also simulated an escalating series of attacks (spoofed messages that appeared to come from other campaign members)
- Results: they found that the interface was successful in preventing some attacks and not others, users were confused by security messages that appeared in the chrome versus those that appeared in the content of the email messages.
Studies about Education and Training
Studies about Warning Messages
Empirical Studies on Software Notices to Inform Policy Makers and Usability Designers by Jens Grossklags and Nathan Good and Stopping Spyware at the Gate:. A User Study of Privacy, Notice and Spyware by Nathan Good, Rachna Dhamija, Jens Grossklags and Deirdre Mulligan
- Both of these studies show that users click through EULAs and security warning dialogs
You've Been Warned: An Empirical Study of the Effectiveness of Web Browser Phishing Warnings by Serge Egelman, Lorrie Faith Cranor, and Jason Hong.
- A study on web browser phishing warning message. The researchers found that 97% of participants fell for at least one spear phishing attack, but 79% were protected by warnings which interrupted them, whereas those shown warnings which did not interrupt them were no better off than those who did not see any warnings. They also found that none of the 60 participants noticed the EV SSL indicators, but several participants noticed URLs, but only after seeing the warning messages.
Browser Security and Anti-phishing Proposals
Petname Tool Firefox extension, Tyler Close
- Need to distinguish sites the user has a relationship with from sites that are strangers. The user types in a petname to mark the creation of a new relationship.
- Need to give each relationship a name, so as to distinguish the relationships from one another. It's not enough to know there is a relationship, the user needs to know which one is currently relevant. For example, don't want the "joke of the day" site impersonating the online banking site.
- The display of the currently relevant relationship needs to be always on and always in the same place, to prevent spoofing and to provide consistency.
- A user's set of petnames is a local namespace for their online relationships. This local namespace is under the exclusive control of the user. This user control ensures the namespace meets the user's requirements for distinct names. By exclusively using this local namespace, the petname tool denies the spoofer the opportunity to inject confusing names into the user's namespace.
- The petname for a relationship is always readily updated by the user, to enable the easy integration of new experience or new recommendations. For example, if a friend refers the user to a site the user has already petnamed, the user may update their petname to reflect this recommendation.
- By allowing the user to choose their own names, the petname tool maximizes the ability of a name to act as a memory aid. Upon seeing their chosen petname, a user is better able to remember the nature of their relationship with the site. This feature is similar to the way users are allowed to choose their own filenames for files stored on their computer, or their own tag names for categories of email.
- By only allowing the user to create petnames, the petname tool helps the user better understand the origins of trust and bolsters the user's memory of trust decisions. For example, "I decided to trust this site when I gave it a petname based on my friend's recommendation."
PASSPET: CONVENIENT PASSWORD MANAGEMENT AND PHISHING PROTECTION Ka-Ping Yee (University of California, Berkeley) and Kragen Sitaker.
- Builds on Petnames, does password management, has its own password input (for password generation to sites).
WEB WALLET: PREVENTING PHISHING ATTACKS BY REVEALING USER INTENTIONS Min Wu, Robert C. Miller, and Greg Little (Massachusetts Institute of Technology) Specific interaction for passwords to train users, plus in task integration.
Haidong Xia and Jose Carlos Brustoloni, “Hardening Web Browsers Against Man-In-The-Middle Eavesdropping Attacks”, The 14th International World Wide Web Conference, ACM Press, Japan, 2005, pp. 489 – 498. "
- Example of redoing all browser SSL dialogs to give users actionable steps to take. Includes blocking certain actions as well, which I (Mez) am less certain is a good idea. But it's a thorough reworking to try to ensure each action and reaction is motivated.
Ye, Smith, Anthony: "Trusted Paths for Browsers", ACM Transactions on Information and System Security 8(2) (2005) 153-186
Spoofguard Dan Boneh, John Mitchell, Robert Ledesma, Neil Chou, Yuka Teraguchi
Ethical Hacking
The tools of a hackers trade can either be used to exploit a computer resource as in Malicious Hacking, or be used to support Ethical Hacking to help designers, developers and IA staff figure out what exposure a computer resource has and how to protect it.
The tools presented are broken out into to two catagories, Browser privacy testing, where a client connects to a server that analyses the browser to determine what software and versions are running. The second catagory of tools are Exploit Tools that are used by a Server. Once the Server queries the User Agent to know what versions of software are running, it can select from its toolbox the most appropriate application that will provide the best results.
Browser (User Agent) Privacy Testing
User Agents can give away information and privacy details that enable programmatic hacking scripts to run when ever a user enters a malicious site. The link below are to sites that can run tests on browsers. The user of corporate or local firewalls can alter results
PC flank
Browser Hawk
Scanit Browser test
Expoit and Testing tools
Metaspoit
Secure Web Development Practices
Best Practices for Secure Web Development by Razvan Peteanu
- Similar to our own document - several practical recommendations with some motivation for each
The World Wide Web Security FAQ by Lincoln Stein
- Dated, having been written in 2002, but many sections are still relevant
Other
Standards, Usable Security, and Accessibility: Can we constrain the problem any further? Mary Ellen Zurko, Kenny Johar
Overview of accessibility approaches and challenges, around the time of wsc-ui last call.
|
https://www.w3.org/2006/WSC/wiki/SharedBookmarks.html
|
CC-MAIN-2017-22
|
refinedweb
| 5,012
| 50.67
|
Learn how to use Bonjour, with UDP/TCP sockets, streams and how to communicate through CoreBluetooth or the watch APIs.
TL;DR: proof of concept sample repository, do NOT use in production
NOTE: this article was originally written back in the end of 2015. I just updated the source code and the article to support the latest version of Xcode 9 with Swift 4.
If you want to learn how to make a network connection between your devices using Bonjour discovery service you are on the right place. In this post I am going to show you the basics, so for example you will be able to make a remote controller from your watch or iOS device in order to send data directly to any tvOS or macOS machines.
Multi-platform development
If you want to create an app that supports multiple platforms, you might want to target macOS, iOS, watchOS, tvOS and soon Linux as well. The code snippet below is going to help you detecting the current platform that you are working with.
#if os(iOS) let platform = "iOS" #elseif os(macOS) let platform = "macOS" #elseif os(watchOS) let platform = "watchOS" #elseif os(tvOS) let platform = "tvOS" #elseif os(Linux) let platform = "linux" #else let platform = "unknown" #endif print(platform)
Network connection 101
Bonjour discovery service
Bonjour, also known as zero-configuration networking, enables automatic discovery of devices and services on a local network using industry standard IP protocols.
So basically with Bonjour you can find network devices on your local network. This comes very handy if you are trying to figure out the list of devices that are connected to your LAN. Using NetService class will help you to detect all the devices with the available services that they support. The whole Bonjour API is relatively small and well-written. From the aspect of server side you just have to create the NetService object, and listen to the incoming connections through the NetServiceDelegate.
NOTE: You have to be on the same WiFi network with all devices / simulators.
TCP connection
TCP provides reliable, ordered, and error-checked delivery of a stream of octets (bytes) between applications running on hosts communicating by an IP network.
With the help of TCP you can build up a reliable network connection. There is a Stream class in Foundation to help you sending data back and forth between devices. If you have a working connection form NetServiceDelegate, just listen to the stream events to handle incoming data through the StreamDelegate. I don't want to go into the details, just download the example code and check it out for yourself.
UDP connection
With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol (IP) network.
If you look at the article about UDP you'll clearly see that the main difference from TCP is that this protocol will not guarantee you safety of the data delivery. Data may arrives unordered or duplicated, it's your task to handle these scenarios, but the UDP is fast. If you want to build a file transfer app you should definitely go with TCP, but for example controlling a real-time action game UDP is just as good enough.
CocoaAsyncSocket
This library is the absolute winner for me and probably it is the best option for everyone who wants to set up a network connection really quickly, because it requires way less code than implementing delegates. Of course you'll still need the Bonjour layer above the whole thing, but that's just fine to deal with.
If you are using CocoaAsyncSocket you will see that the API is straightforward, only after 5 minutes I could relatively easily figure it out what's going on and I was able to send messages through the network. It supports all the Apple platforms, you can seamlessly integrate it using Carthage or CocoaPods.
CoreBluetooth APIs
I was not really familiar with the CoreBluetooth framework API's, that's the reason why I basically just followed and ported this tutsplus.com code example to Swift 4. Honestly I felt that the API is somehow overcomplicated with all those messy delegate functions. If I have to chose between CoreBluetooth or CocoaAsyncSocket, I'd go with the last one. So yes, obviously I am not a bluetooth expert, but this little project was a good first impression about how things are working inside the CB framework.
WatchConnectivity framework
If you want to communicate between iOS and watchOS you'll probably use the WatchConnectivity framework, especially the WKSession class. It's really not so complicated, with just a few lines of code you can send messages form the watch to the iPhone. You can read this tutorial, but if you download my final sources for this article, you'll find almost the same thing inside the package.
External sources
- Bonjour and DNS Discovery
- NSNetServices and CFNetServices Programming Guide
- UDPEcho sample code
- Networking Programming Topics
- Beej's Guide to Network Programming Using Internet Sockets
- Using Bonjour in Swift
- Creating a Game with Bonjour - Client and Server Setup
- CocoaAsyncSocket library
- iOS 7 SDK: Core Bluetooth - Practical Lesson
|
https://theswiftdev.com/2018/02/27/networking-examples-for-appleos/
|
CC-MAIN-2019-39
|
refinedweb
| 861
| 56.39
|
Many small changes can lead to big gains. Enable users to interact with your site with the least amount of friction. Run the smallest amount of JavaScript to deliver real value. This can mean taking incremental steps to get there but, in the end, your users will thank you. Here's some advice for making that happen.
Introduce code splitting
Code splitting (opens in new tab) helps you break up your JavaScript so you only load the code a user needs upfront and lazy-load the rest. This helps avoid shipping a monolithic main.js file to your users containing JavaScript for the whole site versus just what the page needs.
The best approach to introduce code splitting into your site is using the dynamic import() syntax (opens in new tab). What follows is an example of using JavaScript Modules (opens in new tab) to statically 'import' some math code. Because we're not loading this code dynamically (lazily) when it's needed, it will end up in our default JavaScript bundle.
import { add } from './math'; console.log(add(30, 15));
After switching to dynamic import(), we can lazily pull in the math utilities when they are needed. This could be when the user is about to use a component requiring it, or navigating to a new route that relies on this functionality. Below we import math after a button click.
const btn = document.getElementById('load'); btn.addEventListener('click', () => { import('./math').then(math => { console.log(math.add(30, 15)); }); });
When a JavaScript module bundler like Webpack (opens in new tab) sees this import() syntax, it starts code splitting your app. This means dynamic code can get pushed out into a separate file that is only loaded when it is needed.
Code splitting can be done at the page, route or component level. Tools like Create React App, Next.js, Preact-CLI, Gatsby and others support it out of the box. Guides to accomplish this are available for React (opens in new tab), Vue.js (opens in new tab) and Angular (opens in new tab).
If you're using React, I'm happy to recommend React Loadable (opens in new tab), a higher-order component for loading components efficiently. It wraps dynamic imports in a nice API for introducing code splitting into an app at a given component.
Here is an example statically importing a gallery component in React:
import GalleryComponent from './GalleryComponent'; const MyComponent = () => ( <GalleryComponent/> );
With React Loadable, we can dynamically import the gallery component as follows:
import Loadable from 'react-loadable'; const LoadableGalleryComponent = Loadable({ loader: () => import('./GalleryComponent'), loading: () => <div>Loading...</div>, }); const MyComponent = () => ( <LoadableGalleryComponent/> );
Many large teams have seen big wins off the back of code splitting recently. In an effort to rewrite their mobile web experiences to make sure users were able to interact with their sites as soon as possible, both Twitter (opens in new tab) and Tinder (opens in new tab) saw up to a 50 per cent improvement in time to interactive when they adopted aggressive code splitting.
Audit your workflow
Stacks like Next.js (opens in new tab), Preact CLI (opens in new tab) and PWA Starter Kit (opens in new tab) try to enforce good defaults for quickly loading and getting interactive on average mobile hardware.
Another thing many of these sites have done is adopt auditing as part of their workflow. Thankfully, the JavaScript ecosystem has a number of great tools to help with bundle analysis. Tools like Webpack Bundle Analyzer (opens in new tab), Source Map Explorer (opens in new tab) and Bundle Buddy (opens in new tab) enable you to audit your bundles for opportunities to trim them down.
If you're unsure whether you have any issues with JavaScript performance, check out Lighthouse (opens in new tab). Lighthouse is a tool baked into the Chrome Developer Tools and is also available as a Chrome extension (opens in new tab). It gives you an in-depth analysis that highlights opportunities to improve performance.
We've recently added support for flagging high JavaScript boot-up time to Lighthouse (opens in new tab). This audit highlights scripts that might be spending a long time parsing/compiling, which delays interactivity. You can look at this audit as opportunities to either split up those scripts or just do less work.
Check you're not shipping unused code
Another thing you can do is make sure you're not shipping unused code down to your users: Code Coverage (opens in new tab) is a feature in Chrome DevTools that alerts you to unused JavaScript (and CSS) in your pages. Load up a page in DevTools and the Coverage tab will display how much code was executed vs how much was loaded. You can improve the performance of your pages by only shipping the code that a user needs.
This can be valuable for identifying opportunities to split up scripts and defer the loading of non-critical ones until they're needed. Thankfully, there are ways we can we can try to work around this and one way is having a performance budget in place.
Devise a performance budget
Performance budgets are critical because they keep everybody on the same page. They create a culture of shared enthusiasm for constantly improving the user experience and team accountability. Budgets define measurable constraints so a team can meet their performance goals. As you have to live within the constraints of budgets, performance is a consideration at each step, as opposed to an afterthought. Per Tim Kadlec (opens in new tab), metrics for performance budgets can include:
- Milestone timings: Timings based on the user experience loading a page (e.g. time-to-interactive).
- Quality-based metrics: Based on raw values (e.g. weight of JavaScript, number of HTTP requests), focused on the browser experience.
- Rule-based metrics: Scores generated by tools such as Lighthouse or WebPageTest; often a single number or series to grade your site.
Performance is more often a cultural challenge than a technical one. Discuss performance during planning sessions. Ask business stakeholders what their performance expectations are. Do they understand how performance can impact the business metrics they care about? Ask engineering teams how they plan to address performance bottlenecks. While the answers here can be unsatisfactory, they get the conversation started.
What about tooling for performance budgets? You can set up Lighthouse scoring budgets in continuous integration with the Lighthouse CI project (opens in new tab). A number of performance monitoring services support setting perf budgets and budget alerts including Calibre (opens in new tab), Treo (opens in new tab) and SpeedCurve (opens in new tab).
4 quick ways to lessen JS load times
Modern sites often combine all of their JavaScript into a single, large bundle. When JavaScript is served this way, download and processing times can be significant on mobile devices and networks. Here are a few tips for how to ensure you load your JavaScript quickly.
01. Only load the JS required for the current page
Prioritise what a user will need and lazy-load the rest with code splitting. This gives you the best chance at loading and getting interactive fast. Learn to audit your JavaScript code to discover opportunities to remove non-critical code.
02. Optimise your JavaScript
Use compression, minification and other JS optimisation techniques. Compression and minification are good optimisations for shipping fewer bytes of JavaScript to your users. If you’re already gzipping JavaScript, consider evaluating Brotli (opens in new tab) for even more savings. Building a site using Webpack and a framework? Tree shaking (removing unused imported code), trimming unused libraries and polyfills, opting for leaner versions of utilities all add up to some nice savings.
03. Assess the UX benefits
If client-side JavaScript isn’t benefiting the user experience, ask yourself if it’s really necessary. Maybe server-side-rendered HTML would actually be faster. Consider limiting the use of client-side frameworks to pages that absolutely require them. Server-rendering and client-rendering are a disaster if done poorly.
04. Embrace performance budgets
Embrace performance budgets and learn to live within them. For mobile, aim for a JS budget of < 170kB minified/compressed. Uncompressed this is still ~0.7MB of code. Budgets are critical to success; however, they can’t magically fix performance in isolation. Team culture, structure and enforcement matter.
Resources
Real-world performance budgets (opens in new tab)
A deep-dive into why performance budgets matter. This guide by Alex Russell questions if we can afford all the JavaScript we load for users on median mobile phones given their impact on user experience.
Reducing JavaScript payloads with code splitting (opens in new tab)
A practical guide to reducing how much JavaScript you’re loading Webpack or Parcel. It also includes links to code-splitting guides for React, Angular and others.
Reducing JavaScript payloads with tree shaking (opens in new tab)
Tree shaking is a form of dead code elimination. This guide covers how to remove JavaScript imports not being used in your web pages to help trim down your JavaScript bundles.
Lighthouse (opens in new tab)
Lighthouse is a free automated tool for improving the quality of web pages by the Chrome team. It has audits for performance, accessibility and more.
Pinterest case study (opens in new tab)
Pinterest reduced its JavaScript bundles from 2.5MB to < 200kB and reduced time-to-interactive from 23 seconds to 5.6 seconds. Revenue went up 44 per cent, sign-ups are up 753 per cent, weekly active users on mobile web are up 103 per cent (opens in new tab).
AutoTrader case study (opens in new tab)
AutoTrader reduced its JavaScript bundle sizes by 56 per cent and reduced time-to-interactive by ~50 per cent.
This article was originally published in net (opens in new tab), the world's best-selling magazine for web designers and developers. Buy issue 313 (opens in new tab) or subscribe (opens in new tab).
Read more:
|
https://www.creativebloq.com/advice/how-to-code-faster-lighter-javascript/2
|
CC-MAIN-2022-27
|
refinedweb
| 1,660
| 63.49
|
GetPixel - Pixel Color of background Window
By
KryTonX, in AutoIt Example Scripts
Recommended Posts
Similar Content
- By 2Toes
Hey there,
I have a program that I'm working on, and I have a button that's supposed to stop a running function, when it's pressed.
However, I cannot get that to work.
I put together a sample script that is set up in the same way:
#include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #Region ### START Koda GUI section ### Form= Opt("GUIOnEventMode", 1) Global $Form1 = GUICreate("Form1", 290, 106, 192, 124) GUISetOnEvent($GUI_EVENT_CLOSE, "_Exit") Global $btnStart = GUICtrlCreateButton("Start", 24, 24, 99, 49) GUICtrlSetOnEvent($btnStart, "_Start") Global $btnStop = GUICtrlCreateButton("Stop", 152, 24, 99, 49) GUICtrlSetOnEvent($btnStop, "_Stop") GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### While 1 ;~ $nMsg = GUIGetMsg() ;~ Switch $nMsg ;~ Case $GUI_EVENT_CLOSE ;~ Exit ;~ EndSwitch WEnd Func _Start() Global $bStartFlag = True $num = 1 While $bStartFlag ConsoleWrite($num & @CRLF) Sleep(1000) $num += 1 WEnd ConsoleWrite("Exited loop.." & @CRLF) EndFunc Func _Stop() Global $bStartFlag = False EndFunc Func _Exit() Exit EndFunc
With the code above, while the _Start() func is running, the Stop button doesn't do anything.
I even threw a MsgBox into the _Stop() func, to see if the script was at least accessing the _Stop() func. But that showed that the _Stop() func is not being accessed at all while the _Start() func is running.
I'm sure this is a simple solution that I'm just over looking. But I can't figure out what that solution is lol.
Any help here would be greatly appreciated!
Thank you in advance!
- By jantograaf
Hi all,
I'm trying to write a script that connects with a VBA/COM API to get the status of a connected phone. I've been looking up and down this forum for tips or other user's experiences, but I can't seem to find anything (even remotely) similar. It shouldn't be so hard to do, however.
Software I'm trying to connect to
I'm trying to integrate CallCenter by using their API, which is documented over here : JustRemotePhone API Reference
Things I've tried
I've tried using ObjCreate but I don't get any result, it always returns the same (negative) error.
#Version 1 tried ObjCreate("JustRemotePhone.RemotePhoneService") #Version 2 tried ObjCreate("JustRemotePhoneCOM.RemotePhoneService") #Version 3 tried ObjCreate("JustRemotePhoneCOM.RemotePhoneService.Application") None of the three versions I tried seem to deliver any result other than a negative error value which basically says that the given class is not valid.
I am starting to get the hang of AutoIt by now, but unmanaged programming languages and object-oriented stuff is still quite a grey zone for me. If anyone could help me 'talk' to this application, I'd be immensely grateful!
Thanks in advance and kind regards from Belgium!
Jan
- By nooneclose
Hello everyone, I am wondering if and how it is possible to connect my AutoIt script to a different email in my outlook. I have two different accounts when I open outlook. The first which my script always connects to is my own email while the second is a group email account. How or can I make the script connect to the second one and access its inbox instead of mine? This is all work related so no funny business here.
Global $oOutlook = _OL_Open() ; Store all the Unread emails into an array Global $aItems = _OL_ItemFind($oOutlook, "*\Outlook-UDF-Test", $olMail, _ "[UnRead]=True", "Subject", "Maintenance Request from Eagle's Nest", "EntryID,Subject", "", 1) ; Display ; Get the number of unread emails Global $numberOfUnRead = UBound($aItems, $UBOUND_ROWS) - 1 ;MsgBox("", "Number of Unread emails", $numberOfUnRead) ConsoleWrite("Number of unread emails: " & $numberOfUnRead & @CRLF) I might be missing some code in the post but my code works It's just so long I don't want to post all 2300+ lines.
Thank you for the help I greatly appreciate this community.
- By TheDcoder.
- By FordsFinest
I
-
|
https://www.autoitscript.com/forum/topic/178979-getpixel-pixel-color-of-background-window/?tab=comments
|
CC-MAIN-2019-26
|
refinedweb
| 651
| 60.85
|
Hide Forgot
From Bugzilla Helper:
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4) Gecko/20030703
Epiphany/0.8.0
Description of problem:
The following script makes python crash on a glade2 project created with the
glade2 included in Beta1. I have also downloaded glade2 from rawhide (31 July
2003) and it does not change anything so i guess it must be the python module
that is buggy.
Here is the script (It is also the same that could be found in
"/usr/share/doc/pygtk2-1.99.16/examples/glade")
(The gnome2 project is the easiest one possible, i start glade and create a new
gnome2 project. Then saves the file and tries to open the .glade file. I have
not done some fancy UI.. just the standard one created when doing a glade2-gnome
project.)
[code start]
#!/usr/bin/env python
import sys
import gtk
import gtk.glade
if len(sys.argv) > 1:
fname = sys.argv[1]
else:
fname = 'test.glade'
# create widget tree ...
xml = gtk.glade.XML(fname)
def gtk_main_quit(*args):
gtk.main_quit()
xml.signal_autoconnect(locals())
gtk.main()
[code end]
The error message i get is the following:
(glade-demo.py:4233): GLib-GObject-CRITICAL **: file gobject.c: line 1002
(g_object_get): assertion `G_IS_OBJECT (object)' failed
(glade-demo.py:4233): GLib-GObject-CRITICAL **: file gobject.c: line 1002
(g_object_get): assertion `G_IS_OBJECT (object)' failed
Segmenteringsfel
Version-Release number of selected component (if applicable):
pygtk*1.99.16-6
How reproducible:
Always
Steps to Reproduce:
1. Well, since it is a script i can run it and it always crash when i try to
load the .glade file.
2. It is always the same error-message.
3.
Actual Results: The interface is not loaded, the script segfaults.
Expected Results: It should show the interface.
Additional info:
I asked if some one had these problem on the mailinglist and sent the script. I
got a reply from one person saying it worked for him on a gnome2 .glade file. I
have sent my .glade file to him but have not yet got a reply if it workes or not.
Created attachment 93300 [details]
This is the .glade file i use.
Well, this is my .glade file. It should be a simple gnome2 project from glade.
You need to call gnome.init() before loading a .glade file that requires GNOME.
Also, your script will be more portable with the following statements:
import pygtk
pygtk.require( '2.0' )
SuSE Linux 8.2, for example, still defaults to PyGTK 0.6 for GTK+ 1 by the end of 2006 will be closed as 'CANTFIX'. Thanks again for
your help.
Closing as CANTFIX.
|
https://bugzilla.redhat.com/show_bug.cgi?format=multiple&id=101407
|
CC-MAIN-2019-30
|
refinedweb
| 443
| 79.26
|
> "max" <max at theslimmers.net> wrote in message > news:4f55e45a.0312191451.73b8f84b at posting.google.com... > > I am trying to use a sdk to access quickbooks, the sdk provided a COM > > interface and I think it installed the com server files/dlls. A VB > > code example is provided, but I can't figure out how to map "Dim > > sessionManager As New QBFC2_1Lib.QBSessionManager" > > into a corresponding Python statement, when I try > > obj = win32com.Client.Dispatch("QBFC2_1Lib.QBSessionManager") I get > > traceback Shown below. > > > > I have been able to run makepy and it generates a lovely file. I can > > find a Type Library, but need a little help mapping this to be able to > > access the com object and call its methods. > > > > I have included a snipit of the sample VB code and the traceback from > > my attempt to create a client com object ? > > > > Any help much appreciated, > > > > max > > > > > > > > =======Traceback ============= > > >>> o = win32com.client.Dispatch("QBFC2_1Lib.QBSessionManager") > > Traceback (most recent call last): > > File "<interactive input>", line 1, in ? > > File "C:\Python23\lib\site-packages\win32com\client\__init__.py", > > line 95, in Dispatch > > dispatch, userName = > > dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) > > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", > > line 84, in _GetGoodDispatchAndUserName > > return (_GetGoodDispatch(IDispatch, clsctx), userName) > > File "C:\Python23\lib\site-packages\win32com\client\dynamic.py", > > line 72, in _GetGoodDispatch > > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > > pythoncom.IID_IDispatch) > > com_error: (-2147221005, 'Invalid class string', None, None) > I had a similar problem with a different library that would early bind in VB but wouldn't work with win32com.client.Dispatch. IIRC I got around it by hunting in the registry with regedit for likely looking class ID's ("SomeLibrary.SomeObject"). It is also possible that the VBP file will contain the GUID which you can then use in a registry search to find a class ID. It may be a shot in the dark but in my case when the VB code was, Dim S As MYLIB.Server Set S = MYLIB.DefaultServer the corresponding Python ended up being, c = win32com.client.Dispatch("MYLIB.MYLIB") s = c.DefaultServer I'm not sure if this will work in your case but I think if you search the registry for "QBFC" you might turn something up. Paul
|
https://mail.python.org/pipermail/python-list/2003-December/178792.html
|
CC-MAIN-2017-30
|
refinedweb
| 371
| 58.89
|
Basic you that if you mouse over the lone flower on the main page, the page changes. She is already working on the next iteration so whatever I tell you may change.
Update: I don’t get to put a link to the site at this time (which is a bummer because it is good) but the main goal for this article is to help plant some ideas to help get children involved so hopefully I can do that without the actual site.
For Taylor’s project, we started in Expression Blend with a new Silverlight Application + Website. She put a grid inside the layout grid and split it to make a small area for the menu and a main area for her content. The idea for the hills and sun came from the weather project from the Design .Toolbox.
The Rainbow is a full ellipse with a round gradient fill. The trick is that just the edge of the gradient makes up the visible rainbow (see settings for the gradient fill below). For the Rainbow to size properly, it extends beyond the visible image and is contained in a ViewBox so the dimensions shrink and grow evenly (second image below).
She chose to show one flower, the sun and the hills when you go to the page then if you mouse over the single flower, the rainbow and a lot of other various flowers show up and the page will look like the first image above.
Introducing a user control – how about a flower?? how about pedals that spin when you mouse over them? and the ability to set the pedal color?
To create the flower, add a new item to the project and chose UserControl.
She wanted pedals that will spin so she chose to use a path list box. Start with an ellipse that will run through the center of where you vision all of the pedals. Right click on the ellipse and choose Path - Make a Layout Path. Next make ellipses that will serve as pedals. Pedal colors should be gradient from dark on the outside to white in the center. Either make them all and drag and drop them on the path list box or make one ellipse on the path and copy and paste it multiple times (there are other ways to add items to a path list box but these are the easiest visual ways). Set the Layout Paths to have Orient to Path and set the FillBehavior to FullSpan (see settings image below on the right).
The head of the flower needs a white background (or whatever color you chose for the inside of the pedal gradient). This background allows the flower to be placed on any background and still have the radiant look you see in the image. To do this, choose the original center ellipse (that the path list box was made from the first time), make the fill color white (or the same color as the inside gradient on the pedals). With it centered above the current pedals, right click to bring up a menu, choose Order and click on “send to back”.
The last part to the head of the flower isn’t difficult to do but can be hard to conceptualize. The pedals are made out of a path list box. The key here is “list box” which gives it the same template behaviors as a list box. This means that when one of the pedals are selected, the outline gets a color, when you hover over one, the color changes, and more selection changes that come with a list box.
To remove the “list box” look behaviors, just right click on the pathListBox (see image below left) choose Edit Additional Templates - Edit Generated Item Container - Edit a copy (NOTE: If you come back to modify after, you should choose Edit Current because the first time you click Edit a copy, it makes a copy of the template and makes it the current template for this project – Edit Current is unavailable the first time).
After you are in the template, your view will look like the image on the right above (NOTE: “bread crumb” arrows at the top of the image). Click on the States tab at the top. You will need to go through each state and see the highlights/color changes that each state makes and remove them but we are just showing the Focused state here. To see the Focused state changes, click Focused. There will be a red outline around the object. Then look at the objects and timeline for anything that has a red dot next to it (shown in image to the right above). When you highlight an item with a red dot, you can look at the properties panel to see the current properties. In this case, the blue Stroke is not wanted so highlight Stroke and choose no stroke (or click on the little advanced box and click reset). When you are done editing all the states, double click on the first item in the “breadcrumb” in this case, that is the first arrow above the image canvas that says pathListBox.
If you can’t figure out the rest of the state changes from this one, shoot me a comment and I will post more details.
Now the flower needs a stem. The stem is just a pen stroke slightly bend at the end with a wider StrokeThickeness and green fill. The same way the center was sent to back, send the stem backwards so it is behind the pedals.
The leaves are a little challenging but the trick is to use the pen tool and make half of one leaf. Fill it with a gradient from dark at the bottom to light at the top (see left and center image below).
Then copy and paste to make a second half leaf. Flip the copy using the transform - Flip (tool box part shown below) then Rotate using the transform rotate until the two sides match to make a leaf. Overlap the top of the two halves and make sure the bottom has a little separation (very little. Then select both paths you just made and choose path - make compound path. If you had proper overlap and separation, your leaf should now be one path and look close to the image to the far right below.
Make a copy of the full leaf and flip using the same transform tool you did in the previous step for the second leaf. Place both on the stem.
OK… time to animate the pedals
Make a new animation storyboard in the objects and timelines. At 0, the pathListBox Start will be at 0% then at 2 seconds, it should be set to 100% (image2). Run this and it should spin the pedals. Now look in the properties for the animation itself (image 3) and set the RepeatBehavior to Forever.
In Taylors case, she wanted the pedals to spin when moused over and stop spinning when the mouse leaves it. To control the story board, use the ControlStoryboardAction Behavior. To find this, go to the Assets panel, highlight Behaviors and find ControlStoryboardAction in the list.
Drag that behavior and drop it on the pathListBox. Repeat so you have two of the same behaviors. One will start the animation on mouseEnter and one to stop it on mouseLeave (see last two images).
OK… so now there is a full flower that spins and is a user control so it can be added anyplace in the project multiple times but she also wanted to set each one to a different color. In order to do that there has to be a little code involved. So here we go. In the flower.xaml.cs , we need to define a color called pedalColor. In order to bind it in Expression Blend, we need to also register it as a DependencyProperty.
public static DependencyProperty pedalColorProperty = DependencyProperty.Register("pedalColor",typeof(Color),typeof(flower),null);
public Color pedalColor
{
get{
return (Color)GetValue(pedalColorProperty);
}
set{
SetValue(pedalColorProperty,value);
}
}
Rebuild your project.
Now go back to each of the pedals and just bind the dark side of the gradient to this new property. When you click on the dark color side of the gradient tool, the binding is behind the magic square next to editor. You see it in yellow in the image below because it is bound. If you clicked the white part of the gradient, the magic square would be white to indicate it is not bound.
That user control is now done. When it is placed in the project, there is a property called pedalColor that can be set.
After the flower is done, it is now available in the Assets panel under project. Plant as many flowers as you want all over the hills by dragging them from the Asset panel to the main layout covering the hills.
She set all the additional flowers and the rainbow to a 0 opacity and used another animation to make them appear over time. To make a flower appear, pick a time on the time line and se the opacity for that flower to 100. To propery stager flowers apearing (so they all don’t start apearing at the same time), also stagger the beginning 0 opacity. What this does is keeps them at 0 from the start until the point you set them to 0 then they will fade in to the time that is set to 100%. In this case, the Rainbow starts at the beginning and is the last thing set to 100% opacity.
She is still working on the rest of her pages. It is extremely fun to help her and watch her learn and explore on her own. Her pages are published so after a few more people see them, hopefully I can publish the url here. I will wait until she is comfortable.
|
http://gamecontest.geekswithblogs.net/tburger/archive/2010/08.aspx
|
CC-MAIN-2020-45
|
refinedweb
| 1,657
| 77.77
|
Forms allow our web browser to run dynamic web applications like that guest book. But form-based web applications require page loads every time you do anything, and fell out of favor in the early 2000s. What took their place are JavaScript-based applications, which run user code on web pages that can modify the pages dynamically, without reloads. Let’s add support for that to our toy web browser.
Actually writing a JavaScript interpreter is beyond the scope of this book,fn::But check out a book on programming language implementation if it sounds interesting! so this chapter uses the
dukpy library for executing JavaScript.
DukPy is a Python library that wraps a JavaScript interpreter called Duktape. There are, for course, lots of JavaScript interpreters, such as the browser implementations of TraceMonkey (Firefox), JavaScriptCore (Safari), and V8 (Chrome). Unlike those implementations, which are extremely complex because they aim for maximal speed, Duktape aims at simplicity and extensibility, especially for people who need a simple scripting language as part of a larger C or C++ project.For examples, games are usually written in C or C++ to take advantage of high-speed graphics, but use a simpler language to implement the actual plot of the game.
If you're using C or C++, you may want to try binding to the
duktape C library, which
dukpy uses internally. If you're using some other language, you may need to switch to Python for this lab. The next lab, on reflows, can be done without having done this one, though it won't be particularly well motivated.
Like any JavaScript engine, DukPy not only executes JavaScript code, but also allows JavaScript code to call Python functions that you’ve registered. We'll be heavily using this feature to allow JavaScript code to modify the web page it’s running on.
The first step to using DukPy is installing it. On most machines, including on Windows, macOS, and Linux systems, you should be able to do this with the command:
pip install dukpy
There may be quirks depending on your computer, however. You might need to install
pip. Instead of
pip, you might have to use
pip3. Or, perhaps, you may have
easy_install instead of
pip. Some Linux distributions may package
dukpy directly. If you do your Python programming through an IDE, you may need to use your IDE's package installer. In the worst case, you might have to build from source.
To test whether you installed DukPy correctly, execute:
If you get an error on the first line, you probably failed to install DukPy.Or, on my Linux machine, I sometimes get errors due to file ownership. If you get an error, or a segfault, on the second line, there’s a chance that Duktape failed to compile, and maybe doesn't support your system. In that case you might need to skip this chapter.
The test code above shows you how to run JavaScript code with DukPy: you just call
evaljs! With this newfound knowledge, let's modify our web browser to run JavaScript code.
On the web, JavaScript is found in
<script> tags, in two different ways. First, a
<script> tag may have a
src attribute with a relative URL that points to a JavaScript file, much like with CSS files. Second, a
<script> tag may also have ordinary text contents, which are run directly. In my toy browser, I’ll only implement the first; the second makes parsing a challenge.Unless you promise to avoid less than and greater than comparisons in your code.
The implementation here will look much like for CSS. First, let's implement a
find_scripts function:
def find_scripts(node, out): if not isinstance(node, ElementNode): return if node.tag == "script" and \ "src" in node.attributes: out.append(node.attributes["src"]) for child in node.children: find_scripts(child, out) return out
Then, when we load a web page, we will find all of the scripts and run them:
def parse(self, body): # ... for script in find_scripts(self.nodes, []): header, body = request('GET', relative_url(script, self.history[-1])) print("Script returned: ", dukpy.evaljs(body)) self.relayout()
Try this out on a simple web page, like this one:
where
test.js is the following very simple script:
It's cool to run JavaScript, but it’s silly for the browser to print the result. What if you don’t want to print? Or want to print more than once? The script should call the standard
console.log function when it wants to print instead of having the problem print at the end.
To allow that, we will need to register a function with DukPy, which would allow Javascript code to run Python functions. Those functions are registered on a
JSInterpreter object, which we’ll need to create:
For
console.log, we’ll first need a Python function that print its argument—
export_function:
You can now run the Javascript code:
That will take
x, convert it from a Javascript to a Python object,This conversion will do the expected things to numbers, string, and booleans, but I wouldn’t try it with more general objects. and run the
That’s pretty good, but what we actually want is a
console.log function, not a
call_python function. So we need define a
console object and then give it a
log field. We do that in JavaScript, by executing code like this:
In case you’re not too familiar with JavaScript,Now’s a good time to brush up on it! This chapter has a lot of JavaScript in it. this defines a variable called
console, whose value is an object literal with the field
log, whose value is the function you see defined there.
Taking a step back, when we run JavaScript in our browser, we’re mixing: C code, which implements the JavaScript interpreter; Python code, which handles certain JavaScript functions; and JavaScript code, which wraps the Python API to look more like the JavaScript one. We can call that JavaScript code our "JavaScript runtime"; we run it before we run any user code. So let's stick it in a
runtime.js file, and run it after all of our functions are registered but before any user code is run:
Now you should be able to run the script
console.log("Hi from JS!") and see output in your terminal.
Our browser is making one major departure here from how real web browsers work, a departure important enough to call out. In a real web browser, JavaScript code is run as soon as the browser parses the
<script> tag, and at that point most of the page is not parsed and may not even have been received over the network. But the way I've written the code, my toy browser only runs scripts after the page is fully loaded. Given how we've structured our browser, it would, unfortunately, be pretty hard to do this right, and I don’t think it’s essential to understanding how browsers run interactive scripts.
As a side benefit of using one
JSInterpreter for all scripts, it is now possible to run two scripts and have one of them define a variable that the other uses, say on a page like:
where
a.js is "
var x = 2;" and
b.js is "
console.log(x + x)".
So far, JavaScript evaluation is fun but useless, because JavaScript can't make any kinds of modifications to the page itself. Why even run JavaScript if it can’t do anything besides print? So let's work on modifying the page from JavaScript.
The JavaScript functions that manipulate a web page are collectively called the DOM API, for "Document Object Model". The DOM API is big, and it keeps getting bigger, so I'm not implementing all, or even most, of it. But a few core functions have much of the power of the full API:
querySelectorAllreturns all the elements matching a selector;
getAttributereturns an element’s value for some attribute; and
innerHTMLreplaces the contents of an element with new HTML.
I’m implemented a simplified version of these methods.
querySelectorAll will return an array, not this thing called a
NodeList;
innerHTML will only write the HTML contents of an element, and won’t allow reading those contents.
Let's start with
querySelectorAll. First, register a function:
class Browser: def parse(self): # ... self.js.export_function("querySelectorAll", self.js_querySelectorAll) # ... def js_querySelectorAll(self, sel): # ...
Normally,
querySelectorAll is a method on the
document object, so define one in the JavaScript runtime:
The
js_querySelectorAll handler will first parse the selector, then find and return the matching elements:
I'm parsing, say,
#id{ instead of
#id, because that way the selector parser won't go off the end of the string and throw an error. I've moved the actual selector matching to a recursive helper function:Have you noticed that we now have a half-dozen of these functions? If our selector language was richer, like if it supported attribute selectors, we could replace most of them with
find_selected.
def find_selected(node, sel, out): if not isinstance(node, ElementNode): return if sel.matches(node): out.append(node) for child in node.children: find_selected(child, sel, out) return out
With these minimal changes,
querySelectorAll finds the matching elements. However, if you actually try calling the function from JavaScript, you’ll see an error like this:Yes, that's a confusing error message. Is it a
JSRuntimeError, an
EvalError, or a
TypeError?
_dukpy.JSRuntimeError: EvalError: Error while calling Python Function: TypeError('Object of type ElementNode is not JSON serializable')
But what DukPy is trying to tell you is that it has no idea what to do with the
ElementNode objects you're returning from
querySelectorAll, since there is no corresponding class in JavaScript.
Instead of returning browser objects directly to JavaScript, we need to keep browser objects firmly on the Python side of the browser, and toss references to those browser objects over the fence to JavaScript. Those references can be simple numeric identifier; the browser will keep track of which identifer maps to which element. I'll call these identifiers handles.Handles are the browser analogs of file descriptors, which give user-level applications a handle to kernel data structures which they can't interpret without the kernel's help anyway.
To implement handles, I'll first create a
js_handles browser field, which will map handles to nodes:
class Browser: def parse(self, body): # ... self.js = dukpy.JSInterpreter() self.js_handles = {} # ...
I'll also add a
handle field to each
ElementNode to store its handle. If no handle has been assigned yet, I’ll set the field to 0:
I think I’d rather put two makes inside the JSEnvironment class.
Then, in
js_querySelectorAll, I'll allocate new handles for each of the matched nodes:
elts = find_selected(self.nodes, selector, []) out = [] for elt in elts: out.append(self.make_handle(elt)) return out
The
make_handle method merely creates a new handle if none exist yet:
def make_handle(self, elt): if not elt.handle: handle = len(self.js_handles) + 1 elt.handle = handle self.js_handles[handle] = elt return elt.handle
The curious
len(self.js_handles) + 1 expression computes the smallest handle not in the handles list.
Calling
document.querySelectorAll will now return something like
[1, 3, 4, 7], with each number being a handle for an element. Great! So now this script, say, will count the number of paragraphs on the page:
By the way, now is a good time to wonder what would happen if you passed
querySelectorAll an invalid selector. We're helped out here by some of the nice features of DukPy. For example, with an invalid selector,
CSSParser.selector would throw an error, and the registered function would crash. But in that case DukPy will turn our Python-side exception into a JavaScript-side exception in the web script we are running, which can catch it or do something else.
Our JavaScript code can now get references to elements, but those references are opaque numbers. How do you call
getAttribute on them?
Well, the idea is that
getAttribute should take in handles and convert those handles back into elements. It would look like this:
class Browser: def js_getAttribute(self, handle, attr): elt = self.js_handles[handle] return elt.attributes.get(attr, None)
We can register this function as
getAttribute, and now run:Note to JS experts: Dukpy does not implement newer JS syntax like
let and
const or arrow functions.
scripts = document.querySelectorAll("script") for (var i = 0; i < scripts.length; i++) { console.log(call_python("getAttribute", scripts[i], "src")); }
That should print out the URLs of all of the scripts on the page. Note that the attribute is not assigned, the
None value returned from Python will be translated by DukPy to
null in JavaScript.
Finally, we’d like to wrap this ugly
call_python method. Normally
querySelectorAll returns
Node obejcts and you call
getAttribute directly on those
Node objects. Let's define that
Node class in our runtime.If your JavaScript is rusty, you might want to read up on the crazy way you define classes in JavaScript. Modern JavaScript also provides the
class syntax, which is more sensible, but it's not supported in DukPy.
function Node(handle) { this.handle = handle; } Node.prototype.getAttribute = function(attr) { return call_python("getAttribute", self.handle, attr); }
Then, in our
querySelectorAll wrapper, we'll create these
Node objects:This code creates new
Node objects every time you call
querySelectorAll, even if there’s already a
Node for that handle. That means you can't use equality to compare
Node objects. I'll ignore that but a real browser wouldn’t.
document = { querySelectorAll: function(s) { var handles = call_python("querySelectorAll", s) return handles.map(function(h) { return new Node(h) }); }}
We can now implement a little character count function:
inputs = document.querySelectorAll('input') for (var i = 0; i < inputs.length; i++) { var name = inputs[i].getAttribute("name"); var value = inputs[i].getAttribute("value"); if (value.length > 100) { console.log("Input " + name + " has too much text.") } }
Now, ideally, we’d run the character count every time the user typed something in an input box.
The browser executes JavaScript code as soon as it loads the web page, but most changes to the page should be made in response to user actions. Bridging the gap, most scripts set code to run when page events, like clicks on buttons or changes to input areas, occur.
Here's how that works. First, any time the user interacts with the page, the browser generates events. Each event has a type, like
change,
click, or
submit, and a target element (an input area, a link, or a form). JavaScript code can call
addEventListener to react to those events:
elt.addEventListener('click', handler) sets
handler to run every time the element
elt generates a
click event.
Let’s start our implementation with generating events. First, I’ll create an
event method and call it in three places. First, any time we click in the page:
def handle_click(self, e): if e.y < 60: # ... else: x, y = e.x, e.y - 60 + self.scrolly elt = find_element(x, y, self.layout) if elt: self.event('click', elt) # ...
Second, after updating input area values:After, not before, so that any event handlers see the new value.
And finally, when submitting forms:
def submit_form(self, elt): # while elt and elt.tag != "form" if not elt: return self.event("submit", elt) # ...
So far so good—but what should the
event method do? Well, it needs to run the handlers set up by
addEventListener, so those need to be stored somewhere—where? I propose we keep that data on the JavaScript side, in an variable in the runtime. I’ll call that variable
LISTENERS; we’ll use it to look up handles and event types, so let’s make it a dictionary from handles to a dictionary from event types to a list of handlers:
LISTENERS = {} Node.prototype.addEventListener = function(type, handler) { if (!LISTENERS[this.handle]) LISTENERS[this.handle] = {}; var dict = LISTENERS[this.handle] if (!dict[type]) dict[type] = []; var list = dict[type]; list.push(handler); }
We use the
LISTENERS array to run the handlers. Still in JavaScript:
function __runHandlers(handle, type) { var list = (LISTENERS[handle] && LISTENERS[handle][type]) || []; for (var i = 0; i < list.length; i++) { list[i].call(new Node(handle)); } }
When I call the handler I use JavaScript’s
call method on functions, which allows me to set the value of
this inside that function. Here I set it to the element we’re calling the handler on, as is standard in JavaScript.
So
event now just calls
__runHandlers from Python:
def event(self, type, elt): if not elt.handle: return self.js.evaljs("__runHandlers({}, \"{}\")".format(elt.handle, type))
There are two quirks with this code. First, I'm not running handlers if the element with the event doesn't have a handle. That's because if it doesn't have a handle, it couldn't have been made into a
Node, and then
addEventListener couldn't have been called on it. Second, when I call
__runHandlers I need to pass it arguments, which I do by generating JavaScript code that embeds those arguments directly. This would be a bad idea if, say,
type contained a quote or a newline. But the browser supplies that value, and it’ll never be weird.DukPy provides the
dukpy object to do this better, but in the interest of simplicity I'm not using it
With all of this done, we can now run the character count above on every input area change:
function lengthCheck() { var name = this.getAttribute("name"); var value = this.getAttribute("value"); if (value.length > 100) { console.log("Input " + name + " has too much text.") } } var inputs = document.querySelectorAll("input"); for (var i = 0; i < inputs.length; i++) { inputs[i].addEventListener("change", lengthCheck); }
Note how
lengthCheck uses
this to reference the input element that actually changed.
So far so good—but ideally the length check wouldn’t print to the console; it would add a warning to the web page itself. To do that, we’ll need to not only read from but also write to the DOM.
So far, we’ve only implemented read-only DOM methods. Now we need to write to the DOM. The full DOM API provides a lot of such methods, but for simplicity I’m going implementing only
innerHTML. That method works like this:
In other words,
innerHTML is a field on node objects, with a setter that is run when the field is modified. That setter takes the new value, which must be a string, parses it as HTML, and makes the new, parsed HTML nodes children of the original node.
Let's implement this, starting on the JavaScript side. JavaScript has the obscure
Object.defineProperty function to define setters:
Object.defineProperty(Node.prototype, 'innerHTML' { set: function(s) { call_python("innerHTML", this.handle, "" + s); } });
I’m using
"" + s to convert the new value of
innerHTML to a string. Next, we need to register the
innerHTML function:
class Browser: def parse(self, body): # ... self.js.export_function("innerHTML", self.js_innerHTML) def js_innerHTML(self, handle, s): elt = self.js_handles[handle] # ?
In
innerHTML, we'll need to parse the HTML string:
Here I'm adding a special
<__newnodes> tag at the start of the source because our HTML parser doesn't work right when you don't have a single root node.Unless you did that exercise, in which case you'll have to adjust. Of course we don't want that new node, just its children:
We need to update the parent pointers of those parsed child nodes because until we do that, they point to the old
<__newnodes> element. Finally, since the page changed, we need to lay it out again:
JavaScript can now modify the web page!
Let's go ahead and use this in our guest book server. Do you want people writing long rants in your guest book? I don't, so I'm going to put a 200-character limit on guest book entries.
First, let’s add a new paragraph
<p id=errors></p> after the guest book form. Initially this paragraph will be empty, but we'll write an error message into it if the paragraph gets too long.
Next, let's add a script to the page. That means a new line of HTML:
We also need to serve that new JavaScript file, so our little web server will now need to respond to the
/comment.js URL:
def handle_request(method, url, headers, body): if method == 'POST': # .. else: if url == '/comment.js': with open("comment.js") as f: return f.read() # ...
We can then put our little input length checker into
comment.js, with the
lengthCheck function modified like so to use
innerHTML:
p_error = document.querySelectorAll("#errors")[0]; function lengthCheck() { var value = this.getAttribute("value"); if (value.length > 200) { p_error.innerHTML = "Comment too long!" } } input = document.querySelectorAll("input")[0]; input.addEventListener("change", lengthCheck);
Try it out: write a long comment and you should see the page warning you that the comment is too long. By the way, we might want to make it stand out more, so let's go ahead and add another URL to our web server,
/comment.css, with the contents:
Now we tell the user that their comment is too long, but—oops!— the user can still ignore the error message, and submitting the guest book entry anyway.
So far, when an event is generated, the browser will run the handlers, and then also do whatever it normally does for that event. I’d now like JavaScript code to be able to cancel that default action.
There are a few steps involved. First of all, event handlers should receive an event object as an argument. That object should have a
preventDefault method. When that method is called, the default action shouldn't occur.
First of all, we'll need event objects. Back to our JS runtime:
function Event() { this.cancelled = false; } Event.prototype.preventDefault = function() { this.cancelled = true; }
Next, we need to pass the event object to handlers.
function __runHandlers(handle, type) { // ... var evt = new Event(); for (var i = 0; i < list.length; i++) { list[i](evt); } // ... }
After calling the handlers,
evt.cancelled tells us whether
preventDefault was called; let’s return return that to Python:
On the Python side,
event can return that boolean to its handler
Finally,
event’s called should check that return value and stop if it is
True. So in
handle_click:
A similar change happens in
submit_form:
There’s no action associated with the
change event on input areas, so we don't need to modify that.You can’t stop the browser from changing the value: it’s already changed when the event handler is run.
With this change,
comment.js can use a global variable to track whether or not submission is allowed:
allow_submit = true; function lengthCheck() { allow_submit = input.getAttribute("value").length <= 100; if (!allow_submit) { // ... } } form = document.querySelectorAll("form")[0]; form.addEventListener("submit", function(e) { if (!allow_submit) e.preventDefault(); });
Now it’s impossible to submit the form when the comment is too long.
Well… Impossible in this browser. But there are browsers that don't run JavaScript (like ours, one chapter back). So we should do the check on the server side also:
def add_entry(params): if 'guest' in params and len(params['guest']) <= 100: ENTRIES.append(params["guest"]) return show_comments()
Our browser has again grown by leaps and bounds: it now runs JavaScript applications on behalf of websites. Granted, it supports just four methods from the vast DOM API, but with enough time you could add all the methods real browsers provide. More importantly, a web page can now add functionality via clever script, instead of waiting for a browser developer to add it into the browser itself.
childrenDOM property.
Node.childrenreturns the immediate
ElementNodeThe DOM method
childNodesgives access to both elements and text. Feel free to implement it if you'd like… children of a node, as an array.
document.createElementcreates a new element, which can be attached to the document with the
appendChildand
insertBeforemethods on nodes; unlike
innerHTML, there’s no parsing involved. Implement all three methods.
Try to run an event handler when the user clicks on a link: you'll find that it's actually impossible. That's because when you click a link, the
elt returned by
find_element is the text inside the link, not the link element itself. On the web, this sort of quirk is handled by event bubbling: when an event is generated on an element, handlers are run not just on that element but also on its ancestors. Handlers can call
stopPropagation on the event object to, well, stop bubbling the event up the tree. Implement event bubbling. Make sure
preventDefault successfully prevents clicks on a link from actually following the link.
The
<canvas> element is a new addition in HTML 5; scripts can draw pictures on the
<canvas>, much like the Tk canvas we've been using to implement our browser. To use the
<canvas>, you first select the element in JavaScript; then call
canvas.getContext("2d") on it, which returns a thing called a “context”; and finally call methods like
fillRect and
fillText on that context to draw on the canvas. Implement the basics of
<canvas>, including
fillRect and
fillText. Canvases will need a custom layout object that store a list of drawing commands.
XMLHttpRequestobject allows scripts to make HTTP requests and read the responses. Implement this API, including the
addEventListener,
open, and
sendmethods. Beware that
XMLHttpRequestcalls are asynchronous: you need to finish executing the script before calling any event listeners on an
XMLHttpRequest.It is OK for the browser make the request synchronously, using our
requestfunction. That will require some kind of queue of requests you need to make and the handlers to call afterwards. Make sure
XMLHttpRequests work even if you create them inside event handlers.
|
https://browser.engineering/scripts.html
|
CC-MAIN-2019-51
|
refinedweb
| 4,326
| 65.42
|
Without slowing down my application by If anybody know a better alternative, please share, thanks in advance! In that case, you cannot guarantee how long time is needed to be sure that all background threads gets a chance of running. I changed getStatus to return torrent_status const&. have a peek here
Arbitrarily pausing a thread also means that whatever resources that thread has locked stay locked. You're proposing that a program (or the sum of all programs) should not exceed 95% in case the kernel can't run? Then, there's the fact that only one thread at a time per processor is actually running… Your question suggests to me that you want to dip into thread prioritization. BUT, the exception is only thrown when the thread is in waiting state.
John Ludlow says: December 3, 2010 at 8:36 am Is this theoretical application the primary thing the user is working with? Written by Microsoft MVP and leading WPF/Silverlight innovator Daniel Vaughan, this full-color guide... Phone 7.5 UnleashedKütüphanemYardımGelişmiş Kitap AramaE-Kitap satın al - ₺72,38Bu kitabı basılı olarak edininAmazon.co.ukidefixKütüphanede bulTüm satıcılar»Windows Phone 7.5 UnleashedDaniel If the task works in 4.95 seconds as opposed to 5.001, I really don't care. share|improve this answer edited Oct 7 '14 at 18:10 answered Oct 7 '14 at 16:20 pjc50 5,16911317 That video of the exploding AMD Duron is likely fake.
Sleep(0) is not recommended because it doesn't do what you expect-you should always use Sleep(1) to relinquish control to other threads. thanks alot Kumar. If task manager presented outstanding I/O requests, and page faults delta while making it difficult to discover CPU usage, all of a sudden people would focus on those as being the It seems that people are more worried about memory consumption these days but it's the same fallacy.
however, the window never receives any window messages (sent internally). How To Reduce Cpu Usage In C# Application For hash_value() I don't think an assert will be a problem, but for operator== an assert could break a compatibility. Leo says: December 3, 2010 at 8:47 am There is value in having reserves. How can messages get out of order (except of course for WM_QUIT, WM_PAINT and WM_TIMER, which are always delayed until there are no more messages), how can it lead to deadlock
It is the responsibility of the operating system to manage the hardware and prevent user programs from misusing it. I came across a problem in Thread.Sleep that if all threads becomes sequesntial instead of Parallel. Also, do not forget the fact that all non multi threaded windows applications WITH AN EVENT DRIVEN UI use an infinite loop with a sleep - awake - check if something Each ItemsControl can use VirtualizingStackPanel to ensure that it renders only the portion of the screen which is displayed rather than going to create the whole 100 thousand element on first
I am ok with not using sleep if only I need to send 1 SMS at a time, since its more of a "fire and forget" if its just one. Great article. :) Regards, Yogesh. C# Limit Cpu Usage Of Thread Animations in your application worsen this much more. C# Control Cpu Usage The next one I buy will be the M model.
Philippe Reply ↓ kumar said: May 8, 20095:25 pm Hey Eugene, thanks for the article it solved my problem partially. navigate here MikeCaron says: December 3, 2010 at 8:57 am "John": Is that guy kidding? "When I hit Ctrl-Alt-Delete, I see that the System Idle Process is hogging all the resources and chewing you updated the date 01 31 2008 in a file, but only wrote out 02 (feb), you now have an invalid file (02 31 2008 is an invalid date). Lean and neat apps does not.
Talk about stress. So the real cause is that what the Exception is and how to really resolve/handle this Exception. It kills your process once it's used so many seconds of CPU time! If you want to periodically perform some logic I recommend using a System.Timers.Timer object.
share|improve this answer edited Oct 7 '14 at 14:00 Cody Piersall 19019 answered Oct 7 '14 at 13:05 Joonas Pulakka 21.5k65490 3 and the OS may even enforce a cool Trying to divorce myself of this method, I naively thought I would make a synchronizer class which essentially is a System.Timers.Timer which will count at a certain sampleRate for a certain Why are you still trying to use these links in new posts? [So that the links will work once they fix the bug.
In this instance though, I am referring to an application balancing it's own load (for which it does indeed have an internal scheduler that provides hard-real time allocation of CPU within In particular, it provides no support for Windows message pumping, and this is something we will fill in next. Another question: Now that the cpu usage is minimal does the UI refresh/scroll smoothly or is it laggy like before(during transfer list updates)? The UI thread has a "monitor" which is implemented as a timer.
I must admit to not fully understanding all the intricacies of STA and MTA threads, but the discussion itself is quite enthralling. Here it is an example of using it: public class LoginClass { … private UserLogin login; /// /// Callback method from Close event of login window /// /// public void HandleLoginExit(bool I have a desktop machine which doesn't mind 100% spikes of a few seconds, or even a few minutes, but an hour or so (such as when transcoding video) will ultimately this contact form Daniel is a technical advisory board member of PebbleAge, a Swiss finance company specializing in business process management.
You shouldn't worry about your cpu breaking sooner. That means you could make a copy of it, so that changes in a copy should not affect original object and vice versa. Contributor sledgehammer999 commented May 15, 2014 I don't have time atm to read the diffs. (probably tomorrow) Accessing to data member of TorrentModelItem turns out to be even faster than having On a uniprocessor system this has no effect and you need to P/Invoke SwitchToThread.
If one is targeting a mobile platform, it may be desirable in some cases to allow users to select the desired animation frame rate, since some users may not be worried Contributor sledgehammer999 commented May 9, 2014 Yes, I've been thinking of ways to somehow cache the result of libtorrent::torrent_handle::status() between timer timeouts. Reply Sumit says: July 22, 2008 at 10:46 am I find Sleep is very useful in following case. -> Ur application run in the back ground say as a window service. Possibly we should have several queues for different kinds of alerts.
With regard to waiting for retry, where do you do this sleep? hard real time O/S). As future versions of the CLR and CLR hosts are implemented they will eventually implement threading without a direct dependence on unmanaged threads (e.g. I will just not say anything about time.
I wouldn't expect anyone to simply do anything I say without thinking about it and understanding it. I believe that the UI locking issues on my production app are due to the CPU usage spikes during rendering. If you run application now and start clicking the button you will notice that fully functional window is created every time you click, and every time on a new thread. And a dangerous one at that.
With a naive implementation of a process that uses 100% cpu resources it's all too easy to make your program or even your system seem sluggish and hanging. Reply PeterRitchie says: June 24, 2009 at 7:20 pm @Lee if it were me, I'd use System.Threading.Timer if the with a failed status to simply retry calling Send after every Use also mentioned in a comment above that you prefer Sleep(1) to Sleep(0) for being nice to other processes while running a CPU intensive app. I accidentally bought the "value" model when I meant to buy the "mainstream" model, but it still made a huge difference.
There may(!) have been a time, when you needed large (physical) blocks of contiguous RAM addresses, but these time (if they existed) should be long gone. It seems that you use the VS profiler tool, do you use this CPU tool?
|
http://juicecoms.com/cpu-usage/c-limit-cpu-usage-of-thread.html
|
CC-MAIN-2017-51
|
refinedweb
| 1,438
| 58.82
|
Bug Description
[Impact]
* The indicator menu for sound not displaying is a major user interface failure.
* The justification for making this upload is that the number of workarounds proposed are actually damaging to system integrity as well as allowing for shifts between desktop environment.
* This patch resolves a conflict that will allow the menu to display.
[Test Case]
* Install stock Xubuntu 13.10. The indicator menu for sound should fail to display when clicking on the sound icon.
[Regression Potential]
* There is a risk of further conflict between the gtk2 and gtk3 sound indicators. In previous releases the two versions were almost identical but this changed in Saucy (this is also the reason -gtk2 broke). In particular, there is a potential for the two indicators to use gsettings configuration keys in different ways which may lead to problems. Testing should be done on systems with both Unity and Xubuntu installed.
* While Xubuntu is working on landing gtk3 indicators for 14.04 the landing of such for 13.10 now would be a massive change requiring approval by potentially the Technical Board.
[Other Info]
* In general Xubuntu users have been distressed over not having the indicator sound menu available which makes this an issue we would like to resolve expeditiously.
* Xubuntu will need to adjust its website documentation slightly to note that users must select "Download updates while installing" during an installation from the LiveCD to ensure this fix is picked up to avoid a broken interface experience.
This bug has been reported on the Ubuntu ISO testing tracker.
A list of all reports related to this bug can be found here:
http://
I can confirm that this bug does exist.
I have also found that if you kill the currently running indicator-
Since the running process in both 13.04 and 13.10 is /usr/lib/
Thanks, Sean
For those looking for a temporary workaround, look at /usr/share/
Exec=/usr/
that appears to work
Editing indicator-
Also, falling back to using the Raring's binary also works.
indicator-
Still experiencing the issue with “indicator-sound” 12.10.2+
Marking 'Low' right now since easy workarounds exist.
Will the importance be raised as 13.10 nears release? The reason I ask is whether easy workarounds should include having users search through bug reports to find the "easy workarounds" that require editing system files?
I can understand that there are probably far more important issues to work on right now; I'm just trying to understand what an easy workaround includes. From a non-technical user's perspective who just wants something to work, I would rate this as medium.
https:/
Yes, I planned to raise the importance as release nears. I'm hoping it gets solved long before that, though.
I think technically, this bug is of high importance: https:/
You can't adjust sound, which is core functionality.
The workaround is easy only if you happen to be looking at this bug report. I suspect that by easy, the guide means that an uneducated user could find a workaround, just by playing around.
Please don't change the importance as the release nears. Please just set it correctly. Low means ignore potentially forever. High means, fix at least before release. Changing it will just confuse or surprise the dev.
I have been running with the patch that dtl131 described in message #5 for the last 3 days - when he alerted me to the fact that https:/
So, could anyone who has access please fix the package 'indicator-sound' with the one liner as described in the patch? I'll be happy to volunteer for QA duty. I can run tests and/or collect specified logs.
Richard
I just looked at my 13.04 server. Interestingly enough, after applying the above patch to /usr/share/
Note that the indicator-sound package containing the file needing the patch of message #5 was just re-released yesterday without the patch (scheduling issue?). I had to re-apply the patch.
The bluetooth indicator is also affected (see duplicate bug 1219938). Maybe the problem lies in the xfce4-indicator itself?
Status changed to 'Confirmed' because the bug affects multiple users.
@daniel: I don't think it is directly related to the xfce4 indicator applet - I'm testing gtk3/indicator-ng support from upstream, and with it the sound menu works fine, but bluetooth menu is still broken. So it is either unrelated bugs, or something fixed in indicator-sound and not indicator-
Actually, I'm not sure how the reporter of bug 1219938 even got the bluetooth indicator to appear in Xubuntu given that is has no gtk2 version.
I assume that it uses indicator-
Weird. In 13.10 bluetooth is a Unity service/
The bluetooth applet I use in XFCE is blueman-applet. It appears as an indicator but also does not display any options when clicked on. Only a small empty box appears under the indicator.
Here's the error message when I click on the indicator:
(blueman-
Ok - there's two things going on here.
First, when you get the bluetooth icon with an empty menu, that isn't indicator-
Second, indicator-bluetooth is also broken - but in this case it's so broken it doesn't appear at all. It is trying to create a menu of com.canonical.
@a-j-buxton: so I take it the bluetooth indicators should be separate bugs split off from this one?
@dtl131 https:/
indicator-bluetooth and indicator-sound I am not sure of - they could be the same bug or they could be different.
indicator-bluetooth is now working for me. It still produces the error about com.canonical.
Without comment #5 i would not have this possible fix
Possible solution:
Replace the Exec= line in /usr/share/
Exec=/bin/sh -c 'if [ -n "$(pidof xfce4-session)" ]; then /usr/lib/
This will make the change only affect the XFCE desktop environment so it will not effect the Unity/KDE/
The indicator-sound package was just re-released with the same bug. I had to use the patch in message #5 above to re-apply the work-around.
Version from dpkg = 12.10.2+
@Richard: Every time there's an update, it's going to overwrite the change. Put the package on hold to prevent updates:
echo "indicator-sound hold" | sudo dpkg --set-selections
Daniel
I realise that. Not trying to be a pest.
I just want the indicator-sound maintainer to understand that the package
is being rereleased for other reasons but unfixed w.r.t. to this bug and
the fix would be so simple. I don't mind reapplying the patch until a fix
is permanent.
On Sep 14, 2013 12:11 PM, "Daniel Letzeisen" <email address hidden>
wrote:
> @Richard: Every time there's an update, it's going to overwrite the
> change. Put the package on hold to prevent updates:
> echo "indicator-sound hold" | sudo dpkg --set-selections
>
> --
> You received this bug notification because you are subscribed to a
> duplicate bug report (1215852).
> https:/
>
> Title:
> indicator-sound no longer functions with xfce4-indicator
>
> To manage notifications about this bug go to:
> https:/
>
Richard, the suggestion in comment #5 is a workaround/hack for xfce users to use the old gtk2 sound indicator until this gets sorted out. It is not a suitable patch or fix by any means, since users of other desktop environments would be forced to use the old gtk2 indicator as well.
Seeing as how the icon shows up, but doesn't reflect the sound status or respond to sound changes, I've got a gut feeling it's not connecting to pulseaudio properly (but I could be way off base).
Hmm... what you've written here doesn't really make sense. You can only use the gtk2 indicator in the current xfce packages. There is absolutely no way to load gtk3 indicators without installing a custom version of several xfce components.
So whatever the problem is, it's a problem with the gtk2 indicator (because the gtk3 indicator works fine if you install those patches). Therefore your workaround is actually what needs to be done for the real fix. It just needs to be implemented in a way that does not impact other desktops.
So this is my final analysis:
The sound indicator has two parts: there is the part which gets loaded to the panel and displays the icons and menus, and then there is the dbus service which coordinates between the indicator and all the audio players. Both these parts exist in both the gtk2 and gtk3 version of the plugin. However, the gtk2 dbus backend is not normally used. The package does not include a service activation script so it can never get loaded automatically. The gtk2 package depends on the gtk3 package which installs a service activation script to start the gtk3 dbus backend.
In raring this worked fine: the two different dbus backends were interchangable so it did not matter which one was running. However, in saucy, the gtk3 indicator backend has been rewritten and the gtk2 one has not changed, so they are now out of sync. That is why it doesn't work.
The changes in the backend are very big - I think it would be difficult to port them over to the gtk2 indicator. The easy alternative is the workaround from comment 27, and a harder but more permanent fix is to bring xfce to gtk3 indicator support and dump the gtk2 one entirely.
I do think the issue is that the xfce4 panel is in gtk2, and the gtk2 sound indicator was written specifically to support xfce. see: https:/
Given what's in 1048217, I think comment #27 needs to be adjusted to work for lubuntu as well, and then it can be a proper fix. And it should also probably check against pidof xfce4-panel, since that is the relevant program, right?
If lubuntu is also affected this adjustment will handle it:
Exec=/bin/sh -c 'if [ -n "$(pidof xfce4-session)
about using xfce4-penel with pid does the panel start before the file is called that launches the sound indicator? or does the panel launch the sound indicator?
if the panel or the indicator applet is what calls sound indicator that would work fine
The part that matters (the dbus service) is launched using dbus activation. That means that when any program tries to access the dbus service at namespace "com.canonical.
Also, checking for the PID isn't the greatest idea if there are multiple user sessions. It might be better to check the XDG_CURRENT_DESKTOP environment variable.
true but "$XDG_CURRENT_
using xfce4-panel pid would only effect someone using multiple sessions and different DEs which would be limited to certain combinations for example Xubuntu and Lubuntu DEs would get along with each other but they would not get along with the others, but all the others would get along with the others
perhaps this will solve that issue with the workaround:
Exec=/bin/sh -c 'if [ -n "$(ps -U $USER | grep xfce4-panel) ]; then /usr/lib/
#5 worked for me also, but #85 doesn't for bluetoot with Headset. I found out that 'pulseaudio-
Maybe you will need to call 'pulseaudio -k' command after every restart.
#5 STOP WORKING after a "sudo apt-get update; sudo apt-get upgrade".
Bluetooth is working but, who cares when you cannot get a sound out of your laptop?
Cannot figure out how to downgrade to Raring applet.
So I will reinstall the hole system with Precise (or fedora xfce spin). The great "feature" they both have? You can listen to music and see a film !
you have to reapply #5
if the sound indicator packages updates w/out a fix you have to reapply it
there is another solution in #75 it should work better with multiple desktop environments installed and you have multiple users/sessions
Gaspar (#97),
You shouldn't have to do this but I would suggest either re-apply #5 manually or use the automation in #69. Do you really want to re-install and go through re-customizing your laptop all over again? Personally, I am using the automation route.
All,
Why is this major annoyance "unassigned" still? Shouldn't this be assigned to the indicator-sound package maintainer? The XFCE desktop *bunutu distributions are losing users without a fix..
Hi guys!
Better safe then sorry, so i thought i might remind that the sound
preferences for pulse are now under:
main menu => Audio Production => Mixer And Card Control
Perhaps your sound is routed to another device in the pulse control? It
sort of make sens if you can see the sound in the "VU" meter :)
yours,
Set
On 2013-11-23 14:34, Gaspar wrote:
>.1208204.sh
>.
>
--
Set Hallstrom
AKA Sakrecoer
http://
WARNING: Remember clear-text email is subject to mass surveillance
systems. Alone this information is useless. Our summed communications
are worth humanity.
Please keep in mind Internet is a boulevard in a crowded virtual city.
Privacy is found under the cloaks.
In response to comment #90:
I still observe the same issue on a fresh Xubuntu 14.04 amd64.
The difference to the Saucy release is that I can't apply the fix from comment #5, because I don't have /usr/share/
Just wanted to add to the list of people having this same issue. All three of my machines (two Xubuntu and one Ubuntu Studio) that I updated now don't have a functioning indicator on the sound. I am not keen to having to install a "workaround" that includes "holding" updates to keep the workaround in place. Much rather this be fixed permanently. Two of my friends that I got to switch from Windows to Xubuntu also now have the same problem and now they are doubting their decision. I can't see how this is remaining a low priority since this is so visual. I am very new to the Ubuntu world and have been most pleased with Xubuntu and Ubuntu Studio and so have my friends but this is not giving a good impression to them. Just saying.
@eqwalker
This is a high priority bug, you can see it at the top of this page
This command will implement the workaround
sudo wget http://
then logout and login
to verify it worked run this
md5sum /usr/share/
it should give you this:
ece5a3e0ad8dc32
Thank you for your quick response. That has worked. I will pass this command on to my friends for them to run in a terminal window. Glad to see the priority is high. As I have mentioned I am new to the linux world and quite leery of messing around with commands in a terminal window but simply copying and pasting from your command made it simple. Look forward to the permanent fix. With the release of Windows 8 and how many of my friends do not like it, now is the time to get people to switch. That is why I switched and am so far pleased. I hope to learn more as time goes. Thanks again.
In reply to comments #71, #72, #74 and #104:
The variable $(arch) on 32-bit systems returns the value "i686", not "i386", so the workarounds using it do not work if you are in 32-bit unity.
in that case lets make this long line another 25% longer
Exec=/bin/sh -c 'if [ -n "$(ps -U $USER | grep xfce4-panel)" ]; then /usr/lib/
@eqwalker updated for 32bit compatibility
sudo wget http://
verify with this
md5sum /usr/share/
3555d649a4fbd10
I tested this on both a 64bit and 32bit live disk of 13.10
i have tried all of these and none return i386 or x86_64, so if anyone knows a command that does i would like to know, i wanted to keep that Exec line simple but it is getting ridiculous
$(arch), $(uname -m) and $(dpkg --print-
Have rollbacked 3 computers to mint 15 (ubuntu 13.04) and get rid of this bug, it's a 13.10 feature. So my suggestion is a rollback of the affected packages to the 13.04 state. What has happened to the ubuntu quality, are we back into the "never change a running system" timeline?
This bug is on the agenda for discussion at the Xubuntu meeting to be held on Thursday, December 5 at 19:00 UTC on #xubuntu-devel in the Freenode IRC network (chat.freenode.
PPA with fixed package:
https:/
ppa:a-j-
This doesn't use the workaround from the bug report. It fixes it in a
way which is hopefully compatible with other desktops. It needs
testing though, on systems with both Xubuntu and Unity installed.
Alistair,
I can confirm that this indicator-
Thank you. Now I can start psychedelik.com radio without pissing off my cats! (-:
Hey Ubuntu Studio folks - please try this out, okay?
1. Make sure that the patch from message #5 (above), #69 (above), or wherever is *not* in effect.
E.g. With synaptic, re-install indicator-sound and indicator-sound-gtk from the repositories.
2. Verify that the audio widget in the upper-right corner isn't functioning as it ought to.
3. sudo add-apt-repository ppa:a-j-
4. sudo apt-get -y update
5. sudo apt-get -y dist-upgrade
6. Restart the desktop (E.g. sudo reboot)
Richard
This is a debdiff for the fix. It doesn't quite match what's on my ppa because I've edited the changelogs a bit. Version numbers/changelog will probably require further fixing anyway.
The attachment "Debdiff for the fix" just added Volti, an indicator for volume/sound and using alsamixer directly instead of the pulseaudio.
I like the volti "indicator" much better, as it is a classic volume (sound) icon with a very simple up/down bar, yet can be changed easily by simply hovering over it and rolling the mouse wheel.
Alsamixer is proven, Pulseaudio seems to have problems. I like to stick with what works. (Call me old-fashioned.)
Something this elementary (using sound on a system) shouldn't have any bugs, by the way.
I've uploaded this to the Saucy -proposed queue for review and also the same changes with a different version number to Trusty.
Hello TK, or anyone else affected,
Accepted indicator- hit by this bug on 2 xubuntu systems. One got pulseaudio yanked for various reasons, so the bug no longer applies to it. On the other one I just updated to the saucy-proposed version, which fixes the bug for me.
--Arek
I am confirming that patch is working.
Freshly installed Xubuntu 13.10 AMD64 on desktop. Enabled saucy-proposed repo, installed only 1 package:
Package: indicator-
Version: 12.10.0.
PC rebooted, sound is working now.
I removed the temporary PPAs provided in #110, added Saucy Proposed, reinstalled sound-indicator-gtk and sound-indicator, and rebooted. I can confirm that the patch is working.
work for me
Updating from saucy-proposed fixed the printing indicator on my machine (Xubuntu 13.10 amd64).
I enabled the saucy-proposed repo and installed 'indicator-
Is this also going into Ubuntu Studio? They have XFCE, and the same problem.
I installed indicator-
Okay, this has marinated for 7 days. Can we promote the fix or not?
The patch works for me too.
Does it NOT work för somebody?
Tested today on a new installation. Indicator now works great.
Unmute is working using menu, using keyboard specific keys (Thinkpad T500), using pavucontrol.
Regular users (not using proposed-updates) may use it now.
Never too late for a Xmas present :-)
Thx for the fix
Tested today on Ubuntu Studio and it did not work. I then appplied the action in comment 104 and then it displayed. I use Studio to broad cast 3 web shows and it is vital that it works since Jack will not work correctly and IDJC will cease
@grundair
The file provided by the package in proposed-updates is the same you can get after what is described in comment #4 and #104.
Hard to believe it is not working on your particular case, as anybody else seems ok.
As you said, you are using you PC to broadcast web shows, I was wondering if you logged off and on again ?
Indeed, it is mandatory to get the applet behaviour to become OK. I had to log off after updating the package.
You may be able to test without logging off, by simply adding a new Indicator applet, but I haven't tested it.
@openfred
no. the proposed fix has nothing to do with the workarounds described in #4 and #104 which are harmful.
Just upgraded from Xubuntu 13.04 to Xubuntu 13.10, and got the issue of the sound indicator not working. (64bit system.)
I did the workaround described in http://
It worked.
Just posted to point out that the upgrade from 13.04 to 13.10 is still broken for this.
I installed indicator-.
|
https://bugs.launchpad.net/ubuntu/+source/indicator-sound-gtk2/+bug/1208204
|
CC-MAIN-2014-10
|
refinedweb
| 3,509
| 63.39
|
Serial Monitor input for valve positioning TEST IND.IO
I'm sure this is just something easy that I don't know, but for testing purposes, I wanted to pass a 0-10VDC signal to a valve I am testing and I wanted to do it through the serial Monitor. I've played around and I can't get it to recognize anything I pass via the monitor. I do have SerialUSB.begin(9600) and while (!SerialUSB) in my setup portion of the code. I've also noticed that the window freezes after about three inputs. I'm sure its something fundamental that I am missing. Thanks!
I had this included in my code to capture input ANY INPUT, and I get nothing.
if (SerialUSB.available() > 0) {
// read the incoming byte:
incomingByte = SerialUSB.read();
// say what you got:
SerialUSB.print("I received: ");
SerialUSB.println(incomingByte, DEC);
}
That works! Thanks Tom! Had to come back and edit this. It works without anything to do with Analogread statements If you comment out these two lines, this works fine, but will not accept input if they're not commented out.
mAValue = Indio.analogRead(1);
myhumid = Indio.analogRead(2);
Could it be for the moment I am running it on USB power only? No 12 or 24V .......YEP! That's IT. I turned on my 12 volt wall wart and Voila, its working.
#include <Indio.h> //load Indio library
String inString = ""; // string to hold input
float lastvalvesetpoint = 0;
float valvesetpoint;
int myhumid;
int inputInt = 0;
float inputFloat = 0.0;
float temp;
int mAValue;
float sensorVal1, sensorVal2, sensorVal3, sensorVal4; //variables to hold your sensor data
char p;
float valvepot;
void setup() {
// Open serial communications and wait for port to open:
SerialUSB.begin(9600);
while (!SerialUSB) {
; // wait for SerialUSB port to connect. Needed for native USB port only
}
Indio.setADCResolution(16); // Set the ADC resolution. Choices are 12bit@240SPS, 14bit@60SPS, 16bit@15SPS and 18bit@3.75SPS.
Indio.analogReadMode(1, mA); // Set Analog-In CH1 to mA mode (0-20mA).
Indio.analogReadMode(2, V10);
Indio.analogReadMode(3, mA); // Set Analog-In CH3 to mA mode (0-20mA).
Indio.analogReadMode(4, V10); // Set Analog-In CH4 to mA mode (0-20mA).
Indio.analogWriteMode(1,V10);
// send an intro:
SerialUSB.println("\n\nString toInt():");
SerialUSB.println();
}
void loop() {
// Read SerialUSB input:
while (SerialUSB.available() > 0) {
int inChar = SerialUSB.read();
if (isDigit(inChar)) {
// convert the incoming byte to a char and add it to the string:
inString += (char)inChar;
}
// if you get a newline, print the string, then the string's value:
if (inChar == '\n') {
SerialUSB.print("Value:");
SerialUSB.println(inString.toInt());
SerialUSB.print("String: ");
SerialUSB.println(inString);
// clear the string for new input:
inString = "";
}
}
mAValue = Indio.analogRead(1);
myhumid = Indio.analogRead(2);
temp = ((mAValue*2)*1.8)+32; // convert mA to a temperature value (in celsius)...
delay(500);
Indio.analogWrite(1, valvepot, false);
}
Hi, i just tested below code and it works without problem, can you try please.
The Serial Monitor will show the ASCII value of the input, including NL (new line) and CR (carriage return) if your Serial Monitor is configured to do so; you can get rid of them by selecting 'no line ending'. If you need to read anything more than 1 char, look into the parseInt() function.
void setup() {
// put your setup code here, to run once:
SerialUSB.begin(9600);
while (!SerialUSB) {}
}
void loop() {
// put your main code here, to run repeatedly:
if (SerialUSB.available() > 0) {
byte incoming = SerialUSB.read();
SerialUSB.print("received: ");
SerialUSB.println(incoming,
|
https://industruino.com/forum/help-1/question/serial-monitor-input-for-valve-positioning-test-ind-io-682
|
CC-MAIN-2022-27
|
refinedweb
| 583
| 60.01
|
.
The question is whether we can continue to use the old package name for
backwards compatibility purposes. Have you asked Cloudera or the community
if anybody told them, "no, we want our old package name back." No, I bet
you didn't. I bet you saw com.cloudera and just generalized the issue into
"somebody else's namespace" without full detail or background, which the
community already had.
You mentioned slippery slope earlier. Don't you see you're already on it?
And this is the reason the Board stays out of technical decisions? Only the
community knows best. You're on that slope, attempting to apply *your*
technical mandates upon a project. But they know more than you.
-g
|
http://mail-archives.apache.org/mod_mbox/incubator-general/201202.mbox/%3CCABD8fLXcZkkHQ60wCbrZrHisBUWF0p0hn=3SJG+yrrt3NacSFQ@mail.gmail.com%3E
|
CC-MAIN-2015-06
|
refinedweb
| 120
| 69.38
|
okay i need some help with my program i keep geting errors everytime i fix something...i have many questions.. please dont just tell me what to fix, please explain it as well. but be aware im extreamely new to C++ so explain them ina way a newbie would understand =)
after i open it it shows intro screen then asks the player there name, i type in a name, and then instead of switching over and going on through the game.... the intro screen pops right back up asking there name again....
please help?!?
=(
here's my code... (I UPDATED IT)
Code:#include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; int Diceroll(); int Introscreen(); void Tryagain(); void Win(); int Totalbears; int Dicenumber; int Useranswer; int Totalcorrect; string PLAYAGAIN; string NAME; bool PLAY = true; int main() { srand((unsigned)time(NULL)); string PLAYAGAIN = "yes"; while (PLAYAGAIN == "yes") Introscreen(); while(PLAY) { Totalcorrect = 0; for (int iCOUNT=1; iCOUNT<11; iCOUNT++) { if (Useranswer==3) { Win(); } Diceroll(); cout<<"How many polar bears do you see around the ice holes?"<<endl; cin>>Useranswer; if (Useranswer == Totalbears) { cout<<"Correct! =D"<<endl; Totalcorrect++; } else { cout<<"Incorrect! The right answer was: "<<Totalbears<<endl; } system("pause"); Tryagain(); } } return 0; } void LOSE (string NAME) { //the losing screen cout<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"<< endl; cout<<"! !"<<endl; cout<<"! Sorry, !"<<endl; cout<<"! You Lose! !"<<endl; cout<<"! !"<<endl; cout<<"! !"<<endl; cout<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"<<endl<<endl; cout<<endl; cout<<"SORRY "<<NAME<< " YOU LOST"<<endl<<endl; cout<<"BETTER LUCK NEXT TIME"<<endl; } //the intoduction screen int Introscreen() { cout<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"<<endl; cout<<"! !"<<endl; cout<<"! !"<<endl; cout<<"! Ice and Dice !"<<endl; cout<<"! !"<<endl; cout<<"! !"<<endl; cout<<"%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"<<endl<<endl; cout<<endl; cout<<"Game details:"<<endl; cout<<"The name is in the game, and the game is in the name."<<endl; cout<<"and the name of the game is Polar Bears Around An Ice Hole."<<endl; cout<<"Some people call this Petals Around A Rose."<<endl<<endl; cout<<endl; cout<<"Wish to play? Please enter your name here:"<<endl; cin>>NAME; return 0; } int Diceroll() { Totalbears = 0; for (int numRoll = 1; numRoll<4; numRoll++) { Dicenumber=1+rand()%6; switch(Dicenumber) { case 1: { cout<<"*******"<<endl; cout<<"* *"<<endl; cout<<"* 0 *"<<endl; cout<<"* *"<<endl; cout<<"*******"<<endl; Totalbears = Totalbears+0; break; } case 2: { cout<<"********"<<endl; cout<<"* 0 *"<<endl; cout<<"* *"<<endl; cout<<"* 0 *"<<endl; cout<<"********"<<endl; Totalbears = Totalbears+0; break; } case 3: { cout<<"*******"<<endl; cout<<"* 0 *"<<endl; cout<<"* 0 *"<<endl; cout<<"* O *"<<endl; cout<<"*******"<<endl; Totalbears = Totalbears+2; break; } case 4: { cout<<"*********"<<endl; cout<<"* 0 0 *"<<endl; cout<<"* *"<<endl; cout<<"* 0 0 *"<<endl; cout<<"*********"<<endl; Totalbears = Totalbears+0; break; } case 5: { cout<<"*********"<<endl; cout<<"* O O *"<<endl; cout<<"* O *"<<endl; cout<<"* O O *"<<endl; cout<<"*********"<<endl; Totalbears = Totalbears+4; break; } case 6: { cout<<"********"<<endl; cout<<"* O O *"<<endl; cout<<"* O O *"<<endl; cout<<"* O O *"<<endl; cout<<"********"<<endl; Totalbears = Totalbears+0; break; } default: break; }//end of switch } return 0; } void Win () { cout<<"Congratulations, "<<NAME<<", You have won! =D"<<endl; } void Tryagain() { cout<<"Want to play again? (yes or no)"<<endl; cin>>PLAYAGAIN; if (PLAYAGAIN == "no") { PLAY = false; cout<<"Bye"<<endl; } if (PLAYAGAIN == "yes") { PLAY = true; cout<<"Okay!"<<endl; } }
|
https://cboard.cprogramming.com/cplusplus-programming/115483-please-help-im-new-cplusplus-im-getting-errors.html
|
CC-MAIN-2017-13
|
refinedweb
| 508
| 65.25
|
Developing Mobile Applications with Force.com and Sencha Touch - Part 2
Overview
In the first part of our series we introduced you to the Sencha Touch mobile framework and built the foundation for a simple mobile application hosted in a Visualforce page that displays lead data served from an Apex controller. We reviewed the basics of the Sencha class system and MVC data package by constructing model, view, controller and store components in Javascript.
In this second part of the series, we continue to enhance the features of the PocketCRM application as follows:
- Introduce event handling to manage screen transitions and respond to user actions and add some new controls and events to the Lead list.
- Build a form view for displaying, creating, updating, and deleting leads.
- Add event handling logic to manage screen transitions and data management for all data operations.
- Rebuild our Apex class to support Visualforce Remoting, and introduce the Sencha proxy component in our model to bind our JavaScript controller logic to the @RemoteAction methods in our Apex controller. We'll also add sync refresh and data entry validation logic.
Introducing Event Handling
We'll pick up where we left off and introduce the concept of event handling in Sencha Touch. We want the user to be able to navigate from the Lead list to Lead details in a form view as well as to be able to add new Leads. To do this, our app needs to respond to user interaction by capturing an event when the user taps a button or list item.
Fire up your development environment for the PocketCRM app that you built in Part 1 (if you're just tuning in to the series, go to Part 1 and build the first part of the app.). As a reminder, use Safari as a desktop emulator and development environment for your tracing and debugging.
You need to use the Safari Developer tools, such as the Web Inspector and Error Console, to see and trace client side output as you work with events. Launch Safari and open the console from the Develop menu Show Error Console item.
Step 1: Add Controls and Event Handling For View Transition
We're going to add a few new user interface controls in our list view that fire events to support our new functionality. First we'll turn on a feature of the list component that lets a user select an item and drill down to another view. The disclosure feature also renders an icon on the list item to act as the button for the user to tap to fire the associated event. Next we'll add a New button in the list view title bar, add a Sync button that resyncs data with the server on demand, and wire up event listeners for all three that call functions to write messages to the console, which proves the events are firing correctly.
Open the PocketCRM_APP Visualforce component and replace the `PocketCRM.view.LeadsList` with the following code:
/: [ { xtype: "toolbar", title: "PocketCRM", docked: "top", items: [ { xtype: 'spacer' }, { xtype: "button", text: 'New', ui: 'action', itemId: "newButton" } ] }, { xtype: "toolbar", docked: "bottom", items: [ { xtype: "button", iconCls: "refresh", iconMask: true, itemId: "syncButton" } ] }, { //The main list and its properties. xtype: "list", store: "Leads", itemId:"leadsList", onItemDisclosure: true, indexBar: true,>', }], listeners: [{ delegate: "#newButton", event: "tap", fn: "onNewButtonTap" }, { delegate: "#syncButton", event: "tap", fn: "onSyncButtonTap" }, { delegate: "#leadsList", event: "disclose", fn: "onLeadsListDisclose" }] }, onSyncButtonTap: function () { console.log("syncLeadCommand"); this.fireEvent("syncLeadCommand", this); }, onNewButtonTap: function () { console.log("newLeadCommand"); this.fireEvent("newLeadCommand", this); }, onLeadsListDisclose: function (list, record, target, index, evt, options) { console.log("editLeadCommand"); this.fireEvent('editLeadCommand', this, record); } });
The new code appears above. You'll notice we've modified the list view in a few ways. First we removed the titlebar and replaced it with top and bottom toolbar components. These are better suited to manage buttons that we add in two item collections. We then turned on the
onItemDisclosure property in the list component that will automatically display a disclosure icon on each item. Further, we provided an event to trigger a transition to the form view. Last, we turned on an
indexBar property that will display a vertical alpha index in the list for rapid navigation.
We added three listeners and their associated functions to fire events from the view for each associated user action. Down the road these events will be handled by the controller. As we haven't added that logic yet, when the events fire from the view, it's as if no one's listening. That's fine, there's no harm to add only the code to emit the events as Sencha lets you code logic to fire an event before you may have coded logic to process it; the class system is designed with loose coupling in mind. We will add the logic in the controller later to listen for the view events and act accordingly. In the meantime, firing these events here simply outputs messages to the console and verify that they are working.
After you have added the code, refresh your Visualforce page and make sure it displays without errors. You should now see a New button in the top toolbar and a Sync icon button on the bottom toolbar. Also, each item in the list should show the disclosure icon. When you tap each, you should see messages in the console that prove the events are firing.
Take care to include all commas and curly braces as needed or your JavaScript may break. It's best to change your code in small iterations and verify that everything works after each change rather than making lots of code changes before testing.
Step 2: Add A Lead Form View
Now that the list view event logic is in place, we're going to add a new form view to the application for creating and updating Leads. This view will also contain buttons to manage saving and deleting a lead record. It will aslo include a Back button to return to the list view. We'll also add listener logic and handler functions for each to emit the events which will eventually be processed in the controller.
Open the PocketCRM_APP Visualforce component and add the code for this new view beneath the
PocketCRM.view.LeadsList. The fields on the form match the Lead model schema including required indicators on the three required fields for the Leads object, namely "LastName", "Company", and "Status". The associated validation logic will be added later to the controller:
Ext.define("PocketCRM.view.LeadEditor", { extend: "Ext.form.Panel", requires: "Ext.form.FieldSet", alias: "widget.leadeditorview", config: { scrollable: 'vertical', items: [{ xtype: "toolbar", docked: "top", title: "Edit Lead", items: [ { xtype: "button", ui: "back", text: "Home", itemId: "backButton" }, { xtype: "spacer" }, { xtype: "button", ui: "action", text: "Save", itemId: "saveButton" }] }, { xtype: "toolbar", docked: "bottom", items: [ { xtype: "button", iconCls: "trash", iconMask: true, itemId: "deleteButton" }] }, { xtype: "fieldset", title: 'Lead Info', items: [ { xtype: 'textfield', name: 'FirstName', label: 'First Name' }, { xtype: 'textfield', name: 'LastName', label: 'Last Name', required: true }, { xtype: 'textfield', name: 'Company', label: 'Company', required: true }, { xtype: 'textfield', name: 'Title', label: 'Title' }, { xtype: 'selectfield', name: 'Status', label: 'Status', required: true, value: 'Open - Not Contacted', options: [ {text: 'Open - Not Contacted', value: 'Open - Not Contacted'}, {text: 'Working - Contacted', value: 'Working - Contacted'}, {text: 'Closed - Converted', value: 'Closed - Converted'}, {text: 'Closed - Not Converted', value: 'Closed - Not Converted'} ], }, ] }, { xtype: "fieldset", title: 'Contact Info', items: [ { xtype : 'textfield', name : 'Phone', label : 'Phone', component: {type: 'tel'} }, { xtype : 'textfield', name : 'Mobile', label : 'Mobile', component: {type: 'tel'} }, { xtype: 'emailfield', name: 'Email', label: 'Email Address' }, ] }, ], listeners: [ { delegate: "#backButton", event: "tap", fn: "onBackButtonTap" }, { delegate: "#saveButton", event: "tap", fn: "onSaveButtonTap" }, { delegate: "#deleteButton", event: "tap", fn: "onDeleteButtonTap" } ] }, onSaveButtonTap: function () { console.log("saveLeadCommand"); this.fireEvent("saveLeadCommand", this); }, onDeleteButtonTap: function () { console.log("deleteLeadCommand"); this.fireEvent("deleteLeadCommand", this); }, onBackButtonTap: function () { console.log("backToHomeCommand"); this.fireEvent("backToHomeCommand", this); } });
The
leadEditor view is a Form Panel component. Notice the
requires properties at the very beginning where we identify a dependency to the
Ext.form.FieldSet component from the Sencha library. The
requires property tells the Form Panel to pre-fetch any dependent Sencha library components upon instantiation. Also notice that we add both a top and bottom toolbar to contain action buttons.
Between the toolbars, the view will display
FieldSet components that let the lead fields be grouped logically. Each field is configured with an
xtype to identify what kind of field control displays, as well as a
name property that maps each control to a field in the Model schema. The
required property simply adds the display of an indicator after the field label. Take note of the Status field, which is an example of a
selectField, and the additional component property identifying telephone fields that control the display of the keyboard when users are entering phone numbers. You should read up on field configuration in the Sencha docs to learn all about the rich set of field types and configuration options available.
We'll finish by adding the listeners and associated event handling functions. Again, for now, these will simply cause messages to display in the console as no logic has yet been built in the controller to respond.
After you have added the code, refresh your Visualforce page and make sure it displays without error. You won't be able to navigate to the edit view from the list just yet since you haven't wired up what is necessary for transitions in the controller. You just want to insure that you haven't introduced any errors in the JavaScript.
Step 3: Add The Form View To the Application
Before we wire up the events, we must first configure the application to include the new form by telling the application to include the
LeadEditor view. We'll change the views property at the top of our application code to add it. Then we declare an instance of the new view and add it to the application’s viewport when launched. Your application component should now look like this:
Ext.application({ name: "PocketCRM", //Load the various MVC components into memory. models: ["Lead"], stores: ["Leads"], controllers: ["Leads"], views: ["LeadsList","LeadEditor"], //The application's startup routine once all components are loaded. launch: function () { //Instantiate your main list view for Leads. var leadsListView = { xtype: "leadslistview" }; var leadEditorView = { xtype: "leadeditorview" }; //Launch the primary fullscreen view and pass in the list view. Ext.Viewport.add([leadsListView, leadEditorView]); } });
Again, refresh your Visualforce page and just make sure it displays without errors.
Step 4: Add Controller Event Handling
Now we'll add logic to the controller to configure how views transition during navigation and to handle the transitions and user actions. We'll build out the config section of the controller to provide references to our view components so we can hear their events when emitted. We add refs and control properties inside the config section that provide this capability (being careful to follow each property with a comma).
Go find the controller component and change the config section to match this code:
config: { refs: { // We're going to lookup our views by alias. leadsListView: "leadslistview", leadEditorView: "leadeditorview", leadsList: "#leadsList" }, control: { leadsListView: { // The commands fired by the list container. syncLeadCommand: "onSyncLeadCommand", newLeadCommand: "onNewLeadCommand", editLeadCommand: "onEditLeadCommand" }, leadEditorView: { // The commands fired by the note editor. saveLeadCommand: "onSaveLeadCommand", deleteLeadCommand: "onDeleteLeadCommand", backToHomeCommand: "onBackToHomeCommand" } } },
The refs configuration allows each of our view components to be selected by their alias, but the selector can also find components by xtype, id, class, or DOM type. Once a view component ref is configured, we can use it in the subsequent control section to associate a local function with any view events fired. The framework also conveniently provides a getter method on each ref to allow instantiating a local var to access the referenced component's properties and functions; we'll see this used below in the event handling functions.
Again, refresh your Visualforce page and just make sure it displays without errors.
Step 5: Configure View Transitions
We need to define how our views will transition as we navigate from the list to the form and back. While Sencha Touch supports many kinds of transitions, we'll choose a simple left-right slide between our list and form. Add properties for each transition beneath the config section, along with functions to activate each view. Notice in the
activateLeadeditor function that a record is passed as an argument. When editing, this will contain the record being acted on; when adding, this will contain an empty record.
Here's the code that should be beneath the config section:
slideLeftTransition: { type: 'slide', direction: 'left' }, slideRightTransition: { type: 'slide', direction: 'right' }, //View Transition Helper functions activateLeadEditor: function (record) { var leadEditorView = this.getLeadEditorView(); leadEditorView.setRecord(record); Ext.Viewport.animateActiveItem(leadEditorView, this.slideLeftTransition); }, activateLeadsList: function () { Ext.Viewport.animateActiveItem(this.getLeadsListView(), this.slideRightTransition); },
Again, refresh your Visualforce page to make sure it displays without errors.
Step 6: Add Controller Event Handling Functions
Add the remaining controller functions to manage the sync, new, edit, save, delete, and back events. Note the functions that contain logic to prepare and/or pass the appropriate Lead data for processing, as well as transitioning to the appropriate view. The delete function includes a confirmation message prompt for the user, and the save function includes validation logic.
Add the following code beneath the transition code from above:
onSyncLeadCommand: function () { console.log("onSyncLeadCommand"); //Get a ref to the store and remove it. var leadsStore = Ext.getStore("Leads"); //Resync the proxy, reload and activate the list. leadsStore.sync(); leadsStore.load(); this.activateLeadsList(); }, onNewLeadCommand: function () { console.log("onNewLeadCommand"); //Set a default value for the Status selectfield. var newLead = Ext.create("PocketCRM.model.Lead", { Status: "Open - Not Contacted" }); this.activateLeadEditor(newLead); }, onEditLeadCommand: function (list, record) { console.log("onEditLeadCommand"); this.activateLeadEditor(record); }, onSaveLeadCommand: function () { console.log("onSaveLeadCommand"); //Update the field values in the record. var leadEditorView = this.getLeadEditorView(); var currentLead = leadEditorView.getRecord(); var newValues = leadEditorView.getValues(); this.getLeadEditorView().updateRecord(currentLead); //Check for validation errors. var errors = currentLead.validate(); if (!errors.isValid()) { var msg = ''; errors.each(function(error) { msg += error.getMessage() + '<br/>'; }); console.log('Errors: ' + msg); Ext.Msg.alert('Please correct errors!', msg, Ext.emptyFn); currentLead.reject(); return; } //Get a ref to the store. var leadsStore = Ext.getStore("Leads"); //Add new record to the store. if (null == leadsStore.findRecord('id', currentLead.data.id)) { leadsStore.add(currentLead); } //Resync the proxy and activate the list. leadsStore.sync(); this.activateLeadsList(); }, onDeleteLeadCommand: function () { console.log("onDeleteLeadCommand"); //Get a ref to the form and its record. var leadEditorView = this.getLeadEditorView(); var currentLead = leadEditorView.getRecord(); //Get a ref to the store and remove it. var leadsStore = Ext.getStore("Leads"); leadsStore.remove(currentLead); //Resync the proxy and activate the list. leadsStore.sync(); this.activateLeadsList(); }, onBackToHomeCommand: function () { console.log("onBackToHomeCommand"); this.activateLeadsList(); },
Refresh your Visualforce page and make sure it displays without error. Tapping the New button should now bring up an empty form with a default status selected. Tapping the disclose icon on a list item should navigate to the form populated with the selected lead data. And tapping the Sync button will refresh the list. On the form, tapping the Back button should return you to the list, but the Save and Delete buttons won't work properly just yet. Notice the icons for the Sync and Delete buttons; they come from the framework's rich icon library.
Step 7: Add Apex Remoting
You might recall that we created logic to fetch the list of leads from your Salesforce.com org via an Apex controller using standard Visualforce data binding. We simply bind a public Apex getter method to the data property in our Store component, which looks like this in the code below:
Ext.define("PocketCRM.store.Leads", { extend: "Ext.data.Store", requires: "Ext.data.proxy.LocalStorage", config: { model: "PocketCRM.model.Lead", //Fetch the data from the custom Apex controller method //which will return a simple list of Leads as JSON on load. data: {!Leads}, autoLoad: true, pageSize: 50, //Create a grouping; be certain to use a field with content or you'll get errors! groupField: "Status", groupDir: "ASC", //Create additional sorts for within the Group. sorters: [{ property: 'LastName', direction: 'ASC'}, { property: 'FirstName', direction: 'ASC'}] } });
When the JavaScript in the Visualforce component is rendered by the Force.com application server, the data binding expression is replaced with the full JSON data string containing an
ArrayList[] of lead records as served up by the Apex controller.
Data binding is a simple and powerful way to bind data to our Sencha app for display, but it only works in one direction. Now that we want to add full CRUD capability, we need to swap it with something more sophisticated for data transport.
We'll introduce the data proxy, another Sencha component that is part of the data package in the class system. It integrates with both model and store and supports a variety of connection types to push and pull data from either a local data store or backend server.
Many mobile apps are built to use REST Web Service API calls for the transport layer, and the proxy supports it as well. However, with Salesforce it is important to keep in mind that there is a limit on the number of API calls that can be made in a 24-hour period, which scales by licensed seats. As our JavaScript is hosted in a Visualforce page running on the Salesforce.com servers, we have the advantage of leveraging an alternate transport technology — Visualforce JavaScript Remoting with an Apex controller. Not only is this technology fast and efficient, there are no call limits imposed.
There are a number of proxy types provided by the framework. They support a variety of technologies, including REST API calls using JSON or JSONP, and there is also a version to support local storage. We're going to use a server side direct proxy to call Apex @RemoteAction methods.
However, before we add the proxy, we must redesign the Apex controller and build out the
@RemoteAction methods to bind to the proxy API. Open the
PocketCRMController Apex class and replace the existing code with the following:
public with sharing class PocketCRMLeadController{ public PocketCRMLeadController(){} //======================================================================== //INNER CLASSES //These support data request/response transport for remoting. //======================================================================== // One of the parameters supplied by the DirectProxy read method. public class QueryRequest { Integer start; Integer recordCount; List<Map<String, String>> sortParams; Public QueryRequest() { start = 1; recordCount = 1; } Public QueryRequest(Integer pStart, Integer pRecordCount) { start = pStart; recordCount = pRecordCount; } } // The server response expected by the ExtJS DirectProxy API methods. public class Response { public Boolean success; public String errorMessage; public List<SObject> records; public Integer total; Response() { records = new List<SObject>(); success = true; } } //======================================================================= //PUBLIC CRUD REMOTE ACTION METHODS CALLED BY THE SENCHA PROXY //======================================================================= @RemoteAction public static Response Query(QueryRequest qr){ Response resp = new Response(); List<Lead> LeadList; try {; } @RemoteAction public static Response Edit(List<Lead> LeadData){ return updateLeadList(LeadData); } @RemoteAction public static Response Add(List<Lead> LeadData){ return insertLeadList(LeadData); } @RemoteAction public static Response Destroy(List<Lead> LeadData){ return deleteLeadList(LeadData); } //======================================================================= //PRIVATE HELPER METHODS //======================================================================= private static List<Lead> getAllLeads(){ return [SELECT FirstName ,LastName ,Company ,Title ,Phone ,Email ,Status FROM Lead LIMIT 50]; } private static Response insertLeadList(List<Lead> LeadData){ Response resp = new Response(); resp.success = true; try { INSERT LeadData; } catch (Exception e) { resp.success = false; resp.errorMessage = 'Insert failed: ' + e.getMessage(); } return resp; } private static Response updateLeadList(List<Lead> LeadData){ Response resp = new Response(); resp.success = true; try { UPDATE LeadData; } catch (Exception e) { resp.success = false; resp.errorMessage = 'Update failed: ' + e.getMessage(); } return resp; } private static Response deleteLeadList(List<Lead> LeadData){ Response resp = new Response(); resp.success = true; try { DELETE LeadData; } catch (Exception e) { resp.success = false; resp.errorMessage = 'Deletion failed: ' + e.getMessage(); } return resp; } }
Other than a default no-argument constructor, the controller class contains three sections of code.
The first section of Apex code contains two inner classes that support the proxy calls from Sencha. The
QueryRequest class must match the structure of the JSON object sent on the request by the Sencha proxy for the read operation. It must contain any info required by the
@RemoteAction method called. We use the default properties primarily to support paging and batch size, but later we can add additional properties to support anything required by our Apex methods. An example might be a value to perform filtering on the list of records returned; we'll see how they map to the proxy below.
The Response object wraps information that the proxy expects to be returned after a call is made to any of the
@RemoteAction methods. It contains properties to indicate success or failure and to pass back a list of records being fetched.
The second section of Apex code contains four public static methods decorated with the
@RemoteAction annotation. These are the methods mapped to the Sencha proxy's CRUD actions, and each returns a Response object with results of the called method.
The third section of Apex code contains helper methods which are called by the
@RemoteAction methods to manage the CRUD logic. Not included here is the unit test class, but that code is available with the final project on GitHub. Remember that it is always a wise practice to develop your Apex tests as you build your code.
Step 8: Adjusting the Model and Adding a Data Proxy
Now that the Apex controller is in place, we can add our proxy to the model. The proxy maps each of the four basic CRUD operations (read, create, update, and destroy) to the associated
@RemoteAction method on the Apex controller in its API property configuration. In addition, it allows us to configure the data format for a reader and writer, and in our case we'll use JSON for our data transport.
We've tweaked the model in a number of ways, so it should be entirely replaced, (including the new proxy code,) with the following:
//The Lead model will include whatever fields are necssary to manage. Ext.define("PocketCRM.model.Lead", { extend: "Ext.data.Model", config: { idProperty: 'Id', fields: [ { name: 'Id', type: 'string', persist: false}, { name: 'Name', type: 'string', persist: false }, { name: 'FirstName', type: 'string' }, { name: 'LastName', type: 'string' }, { name: 'Company', type: 'string' }, { name: 'Title', type: 'string' }, { name: 'Phone', type: 'string' }, { name: 'Email', type: 'string' }, { name: 'Status', type: 'string' } ], validations: [ { type: 'presence', field: 'LastName', message: 'Enter a last name.' }, { type: 'presence', field: 'Company', message: 'Enter a company.' }, { type: 'presence', field: 'Status', message: 'Select a status.' } ], //Bind each CRUD functions to a @RemoteAction method in the Apex controller proxy: { type: 'direct', api: { read: PocketCRMLeadController.Query, create: PocketCRMLeadController.Add, update: PocketCRMLeadController.Edit, destroy: PocketCRMLeadController.Destroy }, limitParam: 'recordCount', // because "limit" is an Apex keyword sortParam: 'sortParams', // because "sort" is a keyword too pageParam: false, // we don't use this in the controller, so don't send it reader: { type: 'json', rootProperty: 'records', messageProperty: 'errorMessage' }, writer: { type: 'json', root: 'records', writeAllFields: false, // otherwise empty fields will transmit // as empty strings, instead of "null"/not present allowSingle: false, // need to always be an array for code simplification encode: false // docs say "set this to false when using DirectProxy" } } }, });
All the magic is in the proxy and how it maps to the Apex controller. Proxies are an advanced concept, totally customizable and very powerful, but you should at least have a basic understanding of how they work under the hood. You’ll want to pay particular attention to how their properties map to the inner classes defined in the Apex controller.
Using the Web Inspector developer tool from Safari, you can trace the proxy request when the sync operation is executed. The sync event fires a load of the list component, which in turn fires the read proxy action to call the
Query @RemoteAction method on the Apex controller. You can inspect below the JSON request payload sent to the Salesforce remoting service:
The action and method properties identify the controller class and the method, and the data packet will contain all key value pairs necessary to make a call; notice the start of 0 and the recordCount of 50 set by the pageSize property in the store. These are the parameters that must be included in the attribute structure of the
QueryRequest inner class in your controller which is passed as an argument to the
Query method.
... limitParam: 'recordCount', // maps to QueryRequest.recordCount ... } (Apex) public class QueryRequest { ... Integer recordCount; ...
Above you can see the
recordCount key mapped to the
recordCount attribute on the Apex class. The start parameter, included automatically by the proxy, identifies the first record to fetch for a page of data. The
recordCount parameter, a custom parameter name for the
limitParam config, controls the fetched page size. (Our paging logic will be incomplete, and we’ll address it in a subsequent post.)
You can add your own custom parameters to include in the data packet by adding another proxy config item named extraParams, and setting one or more key value pairs to include in the passed data using the
setExtraParams() proxy method. Remember that you will need to extend the attribute structure of the
QueryRequest inner class to capture and marshall any extra params that you add.
The
QueryResult structure is only used for the read operation when calling the Apex
Query method. The other CRUD operations (create, update, and destroy) simply send a JSON
ArrayList[] containing the records and fields to act on. Designed for maximum efficiency, the proxy passes only those fields actually entered for a new record, or updated in an edit process. For example, if only the LastName field is changed on an edit, only that field and the Id are passed for the record like this:
{"action":"PocketCRMLeadController","method":"Edit","data":[[{"LastName":"Rogers","Id":"00Q5000000TXUh7EAH"}]],"type":"rpc","tid":8,"ctx":{"csrf":"RJwzNCf17ZNm_6plAMNqSGf5xEWfwVJcR4CPtjMVb4a2g38HryRgL0jyVfAn2GNyUSd.PHPwsl5sptP607AXKgFvCnGIKGLnvExkZV9ILTLCHMNdIjTHsdKYMwVYe2JNSfnZ8THOvpEld6_.px3lKp3rcx_q7NAX1oClG13LQCYR1BY_","vid":"06650000000D9rZ","ns":"","ver":25}}
In the model we've replaced the FullName field with the Name field from the Salesforce Lead schema, which effectively provides the same data. We also removed the derived calculation for a blank Status field as it will always exist in Salesforce records. (It's a required field.) Last we added a validation section to insure presence of the same three fields required in the Salesforce Lead UI. These validations work in concert with logic in the `onSaveLeadCommand()` function added to our Sencha controller.
onSaveLeadCommand: function () { console.log("onSaveLeadCommand"); ... //Check for validation errors. var errors = currentLead.validate(); if (!errors.isValid()) { var msg = ''; errors.each(function(error) { msg += error.getMessage() + '<br/>'; }); console.log('Errors: ' + msg); Ext.Msg.alert('Please correct errors!', msg, Ext.emptyFn); currentLead.reject(); return; } ...
This validation feature used above checks for any errors on the records processed from the form and displays all error messages as defined in the Model for any missing values on the three required fields.
validations: [ { type: 'presence', field: 'LastName', message: 'Enter a last name.' }, ...
We need to go back to our JavaScript controller and make a few more changes down near the bottom of the component. You can leave the original code alone for the launch section, it should remain like this:
// Base Class functions. launch: function () { console.log("launch"); this.callParent(arguments); //Load up the Store associated with the controller and its views. console.log("load Leads"); var leadsStore = Ext.getStore("Leads"); leadsStore.load(); },
But we will need to add a listener in the init section to capture any Apex exceptions passed back to the proxy. This is an alternate way to add a listener, which in this case is actually configured on the Proxy but added here in the controller. We get a reference to the proxy from the store using its
getProxy() method, and then call the proxy's
addListener() method.
Add the following code:
init: function() { this.callParent(arguments); console.log('); } }); },
Refresh your Visualforce page and make sure it displays without error.
Step 9: Adjusting Our Proxy To Work With Visualforce Remoting
There's just one more thing we must do before we're finished. Visualforce remoting relies on server side JavaScript libraries running on the Salesforce.com server. At the time of this writing, there is a slight workaround needed for our Sencha direct server proxy to work with the Salesforce remoting feature. We're going to add two additional JavaScript extensions at the bottom of the main JavaScript block. These are standalone JavaScript statements; don't position them inside any particular Sencha component!
The first adds a method on our proxy's Query call to provide a function that will provide args necessary for remoting:
//Adjust our read method to add a function that Touch expects to see to get Arguments. PocketCRMLeadController.Query.directCfg.method.getArgs = function (params, paramOrder, paramsAsHash) { console.log('getArgs: ' + params.data); return [params] }
The second adds an override to an existing Sencha Touch function to manage request callbacks in a slightly different manner for the Salesforce.com remoting service:
Ext.data.proxy.Direct.prototype.createRequestCallback = function(request, operation, callback, scope){ var me = this; return function(data, event){ console.log('createRequestCallback: ' + operation); me.processResponse(event.status, operation, request, data, callback, scope); }; };
Now it's time to save your code once again, hold your breath, and restart the app. Run your app through all the features and functions to be sure everything is working. If not, or if there are errors, debug using the Safari Error Console and Web Inspector. These tools are invaluable when debugging JavaScript applications and you need to master them if you'll be doing any serious JavaScript related application development. Right now is a great time to start.
Summary
So let's recap what we've accomplished:
- We added controls and event handling on our list view for the new, disclose, and sync user actions and view transitions.
- We added a new form view, again with all controls and and event handling for save, delete and back.
- We added references, event handling, and validation logic in the controller, and configured logic for view transitions.
- We rebuilt our Apex controller class with
@RemoteActionmethods and built a new data proxy into the Sencha model. We made sure to include inner classes to map to the proxy's request and response data packets, and we reviewed a bit of how the proxy works under the covers. We also added a proxy listener in the controller to help handle any exceptions returned from Apex.
- Finally, we added some bridge functions to allow our Sencha proxy to work properly with Visualforce JavaScript Remoting.
Closure
In coming iterations, we'll explore search, paging, and other features of the framework. In the meantime, I'd like to give a shout out to Jorge Ramon (AKA: the MiamiCoder) for his great online tutorials that really helped me get a leg up on the Sencha Touch framework; I provided a link to his website in Part 1.
I have referenced much of the event handling and controller patterns from his tutorials, and I highly suggest you spend some time with them if you really want to learn more about Sencha Touch. His code will look quite familiar after working through this tutorial. Jorge has also recently published a new book on the Sencha Touch framework which is available online, and has additional tutorials and books on other frameworks as well which you can see at
I'd also like to extend a big thank you to my associate Jeff Trull, who has worked extensively integrating Force.com with the Sencha ExtJS and Touch frameworks. He was my scout working through the integration of the server side direct data proxy with Visualforce JavaScript Remoting. You can follow his work and see some of his sample code at his Github project repostory here:.
Also, you’ll want to check out the latest version of the Sencha Architect 2.0 developer tools which allow you to build a Touch application in a drag and drop studio environment.
If you are planning to go to Salesforce's Dreamforce, Ted Patrick from Sencha's Developer Relations will be giving talks on building mobile apps with Sencha and Force.com tomorrow, September 18th. Find out more, here.
There are 9 responses. Add yours.
Kazuhiro Kotsutsumi2 years ago
... which I do my best and translate
Extremely long.
Don Robins2 years ago
Sorry for messy code formatting; the indentation of comments should show lined up with the associated logic. Please take care when you copy the code to properly indent the comments and code blocks together for maximum readability.
Kazuhiro Kotsutsumi2 years ago
I translated it into Japanese.
Provision: Japan Sencha User Group
Jorge Ramon2 years ago
Thank you for the mention, Don. I’m happy that my tutorials helped you. Nice work!
Jorge
MiamiCoder.com
Richard Shergold2 years ago
Don, thanks for this, this is really useful. I have a question regarding listeners, controllers and events. I like the way that you have (for example) a listener function in a view which uses fireEvent to fire an event. Thanks again for the article.
Don Robns2 years ago
Richard…The Sencha folk will likely advise to follow practices as per architect’s code generation. I have not looked closely at what you describe (yet), but the key is keeping your view and controller as decoupled as possible. Whatever works best to promote the practice of _not_ being too dependent upon anything from the view itself other than the action being fired. We want the controller to be responding to the action regardless of the view that emits it as there may be many. I followed this pattern also to be able to test that the buttons work without the controller even built yet which would be harder without the listeners. Perhaps someone else will chime in here and pick up the thread, you can also post the general question on the Sencha forums. So glad you found it all useful.
Ken Brewer2 years ago
Very performant, and I like the way it integrates with Apex - although I ran into several issues getting the code from Part 1 and 2 to work. I got a Salesforce error on the external references and had do download and add as resources - other problem the control code would not compile in part 2 because of a reference to getLeads - I added the function to the example to get it to run again, but gave up getting full CRUD. If you could add a link to a working source in GIT or somewhere it would be greatly appreciated .
Don Robins2 years ago
Ken - if you were not using Safari as a browser, (perhaps you’re using Chrome or Mozilla,) the links to the Sencha libraries won’t work as they are not on a secure server. That would explain needing to put them in static resources. You should be able to paste the Apex final controller code, but will have to completely remove the data binding expression to “{!leads}” in the store. Commenting it out won’t work. Once you replace the store with the new proxy and connect the new Apex controller, full CRUD should work; I’ve built from pasting the code which is why I’m confident. However, the code was to be posted in a zipfile (rather than on Git) after Dreamforce, and I’ll find out where it is available. Glad you find it of interest! What you may find is that once you get used to the patterns, you can build mobile apps incredibly fast against your Force.com org. Please let us know if you build out projects, and how they work out. Thanks!
Don Robins2 years ago
There is an error in the article above - I did not clearly indicate that in the Store you MUST comment out or remove the line that sets the ‘data’ configuration to the Apex controller data binding:
\\data: {!Leads},
This binding, which previously received the JSON from the Apex controller getter mtehod getLeads(), is replaced by an autoload process provided by the new proxy added to the model.
Comments are Gravatar enabled. Your email address will not be shown.Commenting is not available in this channel entry.
|
http://www.sencha.com/blog/developing-mobile-applications-with-forcecom-and-sencha-touch-part-2/
|
CC-MAIN-2014-15
|
refinedweb
| 5,977
| 53.71
|
On 29/01/2018 14:03, Michal Privoznik wrote: > On 01/26/2018 04:07 AM, John Ferlan wrote: >> >> >> On 01/18/2018 11:04 AM, Michal Privoznik wrote: >>> This is a definition that holds information on SCSI persistent >>> reservation settings. The XML part looks like this: >>> >>> <reservations enabled='yes' managed='no'> >>> <source type='unix' path='/path/to/qemu-pr-helper.sock' mode='client'/> >>> </reservations> >>> >>> If @managed is set to 'yes' then the <source/> is not parsed. >>> This design was agreed on here: >>> >>> >>> >>> Signed-off-by: Michal Privoznik <mpriv...@redhat.com> >>> --- >>> docs/formatdomain.html.in | 25 +++- >>> docs/schemas/domaincommon.rng | 19 +-- >>> docs/schemas/storagecommon.rng | 34 +++++ >>> src/conf/domain_conf.c | 36 +++++ >>> src/libvirt_private.syms | 3 + >>> src/util/virstoragefile.c | 148 >>> +++++++++++++++++++++ >>> src/util/virstoragefile.h | 15 +++ >>> .../disk-virtio-scsi-reservations-not-managed.xml | 40 ++++++ >>> .../disk-virtio-scsi-reservations.xml | 38 ++++++ >>> .../disk-virtio-scsi-reservations-not-managed.xml | 1 + >>> .../disk-virtio-scsi-reservations.xml | 1 + >>> tests/qemuxml2xmltest.c | 4 + >>> 12 files changed, 348 insertions(+), 16 deletions(-) >>> create mode 100644 >>> tests/qemuxml2argvdata/disk-virtio-scsi-reservations-not-managed.xml >>> create mode 100644 tests/qemuxml2argvdata/disk-virtio-scsi-reservations.xml >>> create mode 120000 >>> tests/qemuxml2xmloutdata/disk-virtio-scsi-reservations-not-managed.xml >>> create mode 120000 >>> tests/qemuxml2xmloutdata/disk-virtio-scsi-reservations.xml >>> >> >> Before digging too deep into this... >> >> - I assume we're avoiding <disk> iSCSI mainly because those >> reservations would take place elsewhere, safe assumption? > > I believe so, but I'll let Paolo answer that. The way I understand > reservations is that qemu needs to issue 'privileged' SCSI commands and > thus for regular SCSI (which for purpose of this argument involves iSCSI > emulated by kernel) either qemu needs CAP_SYS_RAWIO or a helper process > to which it'll pass the FD and which will issue the 'privileged' SCSI > commands on qemu's behalf.
Yes. There are two reasons for QEMU to access the helper. First, in order to be able to issue the command without CAP_SYS_RAWIO. Second, in order to access /dev/mapper/control and issue the command to all targets in a multipath setup. iSCSI in kernel, including multipath over iSCSI is included. iSCSI in userspace does not need qemu-pr-manager because QEMU 1) can just send the command down a TCP socket without needing CAP_SYS_RAWIO 2) does not support multipath for iSCSI in userspace. >> - What about using lun's from a storage pool (and what could become >> your favorite, NPIV devices ;-)) >> >> <disk type='volume' device='lun'> >> <driver name='qemu' type='raw'/> >> <source pool='sourcepool' volume='unit:0:4:0'/> >> <target dev='sda' bus='scsi'/> >> </disk> > > These should work too with my patches (not tested though - I don't have > any real SCSI machine). > >> - What about <hostdev>'s? >> >> <hostdev mode='subsystem' type='scsi'> >> >> but not iSCSI or vHost hostdev's. I think that creates the SCSI >> generic LUN, but it's been a while since I've thought about the >> terminology used for hostdev's... > > I think these don't need the feature since qemu can access the device > directly. They actually need the feature, but it can be added later. >> And finally... I assume there is one qemu-pr-manager (qemu.conf changes >> eventually)... Eventually there's magic that allows/adds per domain >> *and* per LUN some socket path. If libvirt provided it's generated via >> the domain temporary directory; however, what's not really clear is how >> that unmanaged path really works. Need a virtual whiteboard... > > So, in case of unmanaged path, here are the assumptions that my patches > are built on: > > 1) unmanaged helper process (UHP) is spawned by somebody else's than > libvirtd (hence unmanaged) - it doesn't have to be user, it can be > systemd for instance. > > 2) path to UHP's socket has to be labeled correctly - libvirt doesn't > touch that > > 3) in future, when UHP dies, libvirt will NOT spawn it again. It's > unmanaged after all. It's user/sysadmin responsibility to spawn it > again. Correct. > Now, for the managed helper process (MHP) the assumptions are: > > 1) there's one MHP per domain (all SCSI disks in the domain share the > same MHP). > > 2) the MHP runs as root, but is placed into the same CGroup, mount > namespace as qemu process it serves > > 3) MHP is lives and dies with the domain it is associated with. Correct, with the caveat that QEMU must provide the MHP state and death event for this to be complete. Thanks, Paolo > The code might be complicated more than needed - it is prepared to have > one MHP per disk rather than domain (should we ever need it). Therefore > instead of storing one pid_t, we store them in a hash table where more > can be stored. > > Michal > -- libvir-list mailing list libvir-list@redhat.com
|
https://www.mail-archive.com/libvir-list@redhat.com/msg157373.html
|
CC-MAIN-2018-39
|
refinedweb
| 785
| 56.96
|
Posted 24 August 2012 - 02:46 PM
Posted 24 August 2012 - 03:01 PM
even though I used delay functions after and before glutSwapBuffers.
Posted 24 August 2012 - 03:31 PM
even though I used delay functions after and before glutSwapBuffers.
... this statement makes me very uneasy. It makes me suspect you are doing something wrong; like, say, putting some kind of sleep() or busy-wait before and after swapping. Which probably isn't what you really want to do.
#include <GL/glew.h> #include <GL/freeglut.h> #pragma comment(lib, "glew32.lib") #include <iostream> using namespace std; void display(void); void reshape(int w, int h); int main(int argc, char **argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB); glutInitWindowSize(1366, 768); glutCreateWindow("Tests"); glutFullScreen(); if( glewInit() != GLEW_OK){ cout << "Failed to initilize GLEW" << endl; return -1; } glutIdleFunc(display); glutReshapeFunc(reshape); glutDisplayFunc(display); glutMainLoop(); return 0; } void display(void) { GLclampf c = glutGet(GLUT_ELAPSED_TIME)/300.0; c = fmodf(c, 1.0f); glClearColor(c, 0.0f, 0.0f, 0.0f); glClear(GL_COLOR_BUFFER_BIT); glFlush(); //glutSwapBuffers(); } void reshape(int w, int h) { glViewport(0, 0, w, h); }
Posted 25 August 2012 - 05:18 PM
Posted 25 August 2012 - 06:33 PM
Posted 25 August 2012 - 08:21 PM
The code looks fine. It is probably some system issue. BTW, what OS, gpu are you using. Do you have the latest graphics drivers?
Posted 26 August 2012 - 05:55 AM
Posted 26 August 2012 - 09:07 AM
Edited by Erik Rufelt, 26 August 2012 - 09:08 AM.
Posted 26 August 2012 - 09:19 AM.
|
http://www.gamedev.net/topic/630217-fullscreen-mode-not-working-with-signle-buffer/?forceDownload=1&_k=880ea6a14ea49e853634fbdc5015a024
|
CC-MAIN-2016-50
|
refinedweb
| 258
| 66.94
|
PGU - Phil's pyGame Utilities - 0.10.6
A collection of handy modules and scripts for PyGame.
Peter Rogers
(petros)
Links
Releases
PGU - Phil's pyGame Utilities 0.5 — 7 Oct, 2005
PGU - Phil's pyGame Utilities 0.1.0pre — 24 Jul, 2005
PGU - Phil's pyGame Utilities 0.10.1 — 24 Feb, 2006
PGU - Phil's pyGame Utilities 0.10.2 — 13 Mar, 2006
PGU - Phil's pyGame Utilities 0.3 — 25 Aug, 2005
PGU - Phil's pyGame Utilities 0.9 — 1 Dec, 2005
PGU - Phil's pyGame Utilities 0.1.0 — 4 Aug, 2005
PGU - Phil's pyGame Utilities 0.6 — 24 Oct, 2005
PGU - Phil's pyGame Utilities 0.7 — 19 Nov, 2005
PGU - Phil's pyGame Utilities 0.16 — 16 Mar, 2011
PGU - Phil's pyGame Utilities 0.10.3 — 7 Apr, 2006
PGU - Phil's pyGame Utilities 0.10.6 — 25 Mar, 2007
PGU - Phil's pyGame Utilities 0.10.5 — 1 Sep, 2006
PGU - Phil's pyGame Utilities 0.10 — 11 Feb, 2006
PGU - Phil's pyGame Utilities 0.12.2 — 1 Mar, 2009
PGU - Phil's pyGame Utilities 0.12.1 — 23 Feb, 2009
PGU - Phil's pyGame Utilities 0.14 — 3 Jan, 2011
Pygame.org account Comments
Zhangyrmath 2011-06-12 01:20:44
good!I'll have a try on that
Happyfanatic 2012-04-08 19:51:17
I downloaded PGU to use the iso engine. The example code makes reference to a set of "tilevid tutorials" They are not included in the download; I couldn't find them on the homepage, or by google search. Anyone know if these exist anymore?
beginner 2012-04-18 01:07:21
class TestDialog(gui.Dialog):
def __init__(this):
title = gui.Label("Some Dialog Box")
label = gui.Label("The number now is ")
gui.Dialog.__init__(this, title, label)
how can i add a global variable inside the label ?? I cannot do something like :
class TestDialog(gui.Dialog): def __init__(this): global s title = gui.Label("Some Dialog Box") label = gui.Label("
The number now is", s) gui.Dialog.__init__(this, title, label)
where every time i click a button s increases
Magnus D 2012-10-28 21:22:38
When clicking the close button on the example windows, I do not succeed to close any of them. I am using Python3. Can someone help? I am reffering to the examples that ship with the package itself.
rob00 2013-01-11 03:19:38
>>>from pgu import gui
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python32\lib\site-packages\pgu\gui\__init__.py", line 21, in <module>
from .container import Container
File "C:\Python32\lib\site-packges\pgu\gui\container.py", line 57
except StyleError,e:
SyntaxError: invalid syntax
Floriusin 2014-12-26 13:20:46
Just go into pgu/gui/container.py and in update() edit "except StyleError,e:" to "except StyleError as e:" and then reinstall
fjkdasilva 2013-07-17 16:42:34
It is not clear how one gets access to values returned from PGU apps in a pygame program. Can anyone help?
Bir Bikram Dey 2014-01-01 21:39:51
I am not sure how to even install this to windows.
Is it me or pygame is not windows friendly :(
canine828 2016-02-27 22:45:14
Pygame is Windows friendly. I have Windows on my school laptop (my parents won't let me put Linux on it), and it works pretty well. Just install Python, open the command prompt, and type C:\Python27\python.exe C:\path\to\the\pge\setup\python\file\setup.py install
Or add C:\Python27 and C:\Python27\Scripts to your Path, open a command prompt, CD to the folder with your PGE setup.py file, and type python setup.py install
:D
Anony 2014-09-20 22:25:38
How to install and use this exactly?
canine828 2016-02-27 22:42:15
This is good, but there should be a clean simple Oxygen-ish theme built in. The last thing I want to do is rifle through my filesystem, find out that it's all generated by Qt, and use screenshots to make the gui.
Stam Kaly 2016-07-02 14:33:18
If you get error:
Traceback (most recent call last):
File "./setup.py", line 84, in <module>
main()
File "./setup.py", line 33, in main
os.path.walk('data', visit, installdatafiles)
AttributeError: 'module' object has no attribute 'walk'
You can delete ".path" in "os.path.walk('data', visit, installdatafiles)"
|
http://www.pygame.org/project-PGU+-+Phil's+pyGame+Utilities-108-661.html
|
CC-MAIN-2017-39
|
refinedweb
| 755
| 78.04
|
Certificates are represented by the
ec_cert_t type, and are created by
ec_cert_create(). All certificates must be freed once they are no longer required using
ec_cert_destroy().
If a certificate has been saved using
ec_ctx_save(), then it will be destroyed automatically once it is removed, overwritten, or the context it was saved to is destroyed.
ec_cert_t *ec_cert_create(time_t valid_from, time_t valid_until);
Create a new certificate, and return a pointer to it. Returns NULL on failure.
valid_from and
valid_until define the certificate's validity period - if the validity period does not fall entirely within the valitity period of its signer, then the timestamp which violates this constraint will be adjusted to match that of the signer.
Timestamps are handled as seconds since 1970-01-01 00:00:00. The current time can be obtained using
time() (see
time.h).
Certificates created using this function must be destroyed using
ec_cert_destroy() when they are no longer required.
#include <ec.h> #include <time.h> ... time_t from = time(NULL); time_t until = from + (86400 * 365); //one year ec_cert_t *c = ec_cert_create(from, until); ...
ec_cert_t *ec_cert_copy(ec_cert_t *c);
Copy a certificate. Returns a new copy of
c, or NULL on failure.
#include <ec.h> ... ec_cert_t *c2 = ec_cert_copy(c1); if(c == NULL) { //failed to copy certificate } ...
void ec_cert_destroy(ec_cert_t *c);
Destroy a certificate previously created with
ec_cert_create().
#include <ec.h> ... ec_cert_destroy(c); ...
void ec_cert_strip(ec_cert_t *c, int what);
Strip unwanted data from a certificate, specified by
when. Possible flags are listed below:
#include <ec.h> ... ec_cert_strip(c, EC_STRIP_SECRET | EC_STRIP_RECORD); ...
ec_err_t ec_cert_sign(ec_cert_t *c, ec_cert_t *signer);
Sign a certificate using another certificate. Returns a nonzero error code on failure.
The signer must have a valid secret key available, and both certificates must pass the following checks prior to signing:
ec_cert_check(NULL, c, EC_CHECK_CERT); ec_cert_check(NULL, signer, EC_CHECK_CERT | EC_CHECK_SECRET);
If the certificate's validity falls outside that of the signer, the appropriate timestamp on the certificate will be adjusted to match that of the signer.
#include <ec.h> ... if(ec_cert_sign(c, signer) != 0) { //signing succeeded } ...
ec_err_t ec_cert_check(ec_ctx_t *ctx, ec_cert_t *c, int flags);
Ensure that a certificate passes a given set of tests. Returns a nonzero error code on failure.
All tests which require a valid trust chain to be present must also provide a context where the trust chain may be found. Tests which apply only to the certificate may pass
NULL instead.
The
flags parameter is used to set which tests are run, according to the following table. Checks are run in the order that they are listed here.
1 Context is not required if the certificate is self-signed.
2
EC_CHECK_CHAIN always passes if
EC_CERT_TRUSTED is set on the certificate.
#include <ec.h> ... if(ec_cert_check(ctx, c, EC_CHECK_CERT | EC_CHECK_ROLE) != 0) { //certificate passes the defined checks } ...
ec_id_t ec_cert_id(ec_cert_t *c);
Get a unique ID for a certificate. This ID is based on the certificate's public key, and will not change if the certificate is modified by e.g. signing, adding records etc.
This ID is used for things like retrieving a certificate from a context store, identifying a signer, etc.
#include <ec.h> ... ec_id_t id = ec_cert_id(c); ...
ec_record_t *ec_cert_records(ec_cert_t *c);
Get the records list for a certificate. Returns NULL if there are no records present.
#include <ec.h> ... ec_record_t *list = ec_cert_records(c); if(list == NULL) { //no records present } ...
ec_err_t ec_cert_lock(ec_cert_t *c, char *password);
Encrypt a certificate's secret key using a password. Returns zero on success, or a nonzero error code otherwise.
If the secret key is encrypted successfully, EC_CERT_CRYPTSK will be set.
#include <ec.h> ... if(ec_cert_lock(c, "mySuperSecretPassword") != 0) { //unable to encrypt secret key } ...
ec_err_t ec_cert_unlock(ec_cert_t *c, char *password);
Decrypt a certificate's secret key using a password. Returns zero on success, or a nonzero error code otherwise. If the secret key is not encrypted, then this function will take no action and return zero anyway.
If the secret key is decrypted successfully, then EC_CERT_CRYPTSK will be cleared.
Note that using an incorrect password is not considered an error, but the resulting secret key will be unusable, and any attempts to sign something with it will fail.
#include <ec.h> ... if(ec_cert_unlock(c, "mySuperSecretPassword") != 0) { //unable to decrypt secret key } ...
|
https://libec.erayd.net/chapters/certificates.html
|
CC-MAIN-2019-09
|
refinedweb
| 695
| 66.84
|
When extending the subranges, the reaching-def may be an undefs. When
extending such kind of subrange, it will try to search for the reaching
def first. If the reaching def is an undef and we did not provide 'Undefs',
The findReachingDefs() will fail with message:
"Use of $noreg does not have a corresponding definition on every path:
LLVM ERROR: Use not jointly dominated by defs."
So we computeSubRangeUndefs() and pass the result to extendToIndices().
$noreg doesn't have liveness?
Can you reduce this any further? -run-pass=none will also compact the register numbers
Typo passs in commit message
I am not sure what you are really asking here. I know the assert message is a little bit misleading. The reason it output $noreg is we are passing 0 to argument 'PhyReg' of LiveRangeCalc::extend() in LiveIntervals::extendToIndices(). When assert happens, we are trying to extend a subrange of register %90. The offending subrange has a def point in one of bb.4 predecessor chain, so it has liveness in this path. but in another predecessor chain 4->27->1->0, it only has one undef point in bb.0.
I just tried to remove each one of the most blocks containing instructions in MIR, I failed to trigger the crash after removing them. If you have any good idea to simplify further, I can try it. Some more notes: The test case is already a much simplified version than original failure IR with 100+ basic blocks. I have tried removing each basic block in IR before and it would cause problem disappear. The problem is hard to trigger, it also depends on the order of coalescing work. For example, if I reorder the blocks, the problem may disappear because the coalescing of registers will be different then.
address some review comments from Matt
I've reduced coalescer cases by dumping the MIR at intermediate points during the coalescer. Presumably not every step is relevant to get to the problem
further reduce .mir with intermediate result from coalescer.
further reduce .mir to trigger the issue. @arsenm Could you take a look?
|
http://reviews.llvm.org/D87744
|
CC-MAIN-2020-40
|
refinedweb
| 352
| 65.52
|
You e writing an interactive console program, and you want to get line-based input from the user. You present the user with a prompt, and he types some data before hitting enter.
Instead of reading standard input all at once, read it a line at a time with gets or readline.
This method populates a data structure with values obtained from user input:
def confirmation_hearings questions = [[What is your name?, :name], [How old are you?, :age], [Why would you like to be Secretary of the Treasury?, :why]] answers = questions.inject({}) do |answers, qv| question, value = qv print question + answers[value] = gets.chomp answers end puts "Okay, you e confirmed!" return answers end confirmation_hearings # What is your name? # <= Leonard Richardson # How old are you? # <= 27 # Why would you like to be Secretary of the Treasury? # <= Mainly for the money # Okay, you e confirmed! # => {:age=>"26", :why=>"Mainly for the money", :name=>"Leonard Richardson"}
Most console programs take their input from command-line switches or from a file passed in on standard input. This makes it easy to programatically combine console programs: you can pipe cat into grep into last without any of the programs having to know that they e connected to each other. But sometimes its more user-friendly to ask for input interactively: in text-based games, or data entry programs with workflow.
The only difference between this technique and traditional console applications is that you e writing to standard output before you e completely done reading from standard input. You can pass an input file into a program like this, and itll still work. In this example, a Ruby program containing the questionnaire code seen in the Solution is fed by an input file:
$ ./confirmation_hearings.rb < answers # => What is your name? How old are you? Why would you like to be # Secretary of the Treasury? Okay, you e confirmed!
The program works, but the result looks differenteven though the standard output is actually the same. When a human is running the program, the newline created when they hit enter is echoed to the screen, making the second question appear on a separate line from the first. Those newlines don get echoed when they e read from a file.
The HighLine library requires that you install a gem ( highline), but it makes sophisticated line-oriented input much easier. You can make a single method call to print a prompt, retrieve the input, and validate it. This code works the same way as the code above, but its shorter, and it makes sure you enter a reasonable age for the question "How old are you?"
require ubygems require highline/import def confirmation_hearings answers = {} answers[:name] = ask(What is your name? ) answers[:age] = ask(How old are you? , Integer) { |q| q.in = 0..120 } answers[:why] = ask(Why would you like to be Secretary of the Treasury? ) puts "Okay, you e confirmed!" return answers end confirmation_hearings # What is your name? # <= Leonard Richardson # How old are you? # <= twenty-seven # You must enter a valid Integer. # ? # <= 200 # Your answer isn within the expected range (included in 0..120) # ? # <= 27 # …
|
https://flylib.com/books/en/2.44.1/getting_input_one_line_at_a_time.html
|
CC-MAIN-2019-39
|
refinedweb
| 517
| 66.74
|
All of dW
-----------------
AIX and UNIX
Information Mgmt
Lotus
Rational
Tivoli
WebSphere
-----------------
Java technology
Linux
Open source
SOA & Web services
Web development
XML
-----------------
dW forums
-----------------
alphaWorks
-----------------
All of IBM
Detecting Java leaks using IBM Rational Application Developer 6.0
Document options requiring JavaScript are not displayed
Connect to your technical community
Help us improve this content
Level: Intermediate
Satish Chandra Gupta (satish.gupta@in.ibm.com), Programmer, RAD/PurifyPlus, Rational Software, IBMRajeev Palanki (rpalanki@in.ibm.com), Level 3 Java Support, IBM
16 Aug 2005.
Elusive
bandits: what are Java memory leaks?
If the term Java™ memory leak seems like a misnomer to you, rest
assured that you are not alone; after all, you were promised that Garbage Collection
(GC) in Java will relieve you from the mundane duties of allocating, tracking,
and freeing the heap memory. Indeed, the promise has been delivered, so it is
reasonable -- and to quite an extent correct -- for you to conclude that there
will be no memory leaks in your Java program. However, the catch is that GC
can take care of only typical heap management problems.
Think about your experience with C/C++ (or any other non-GC language for that
matter). What are typical heap management problems in C/C++? Two of the most
famous ones are: memory leaks and dangling pointers. Listing 1 shows a simple example with both errors. In this example, interestingly, by themselves methods foo and main seem to be error-free, but together they manifest both a memory leak and a dangling pointer. First, method foo overwrites pi
with a new allocation, and all pointers to the memory chunk allocated in main
are lost, leading to a memory leak. Then foo frees
up what it has allocated, but pi still holds the address (it is not nullified).
In main, after calling foo,
when pi is used, it is referring to memory that has
been freed, so pi is a dangling pointer.
foo
main
pi
int *pi;
void foo() {
pi = (int*) malloc(8*sizeof(int)); // oops, memory leak of 4 ints
// use pi
free(pi); // foo() is done with pi
}
void main() {
pi = (int*) malloc(4*sizeof(int));
foo();
pi[0] = 10; // oops, pi is now a dangling pointer
}
In Java, you will never have a dangling pointer, because the GC will
not reclaim a heap chunk if there are any references to it. Nor will you have
a C/C++ type memory leak because GC will reclaim the heap chunk only
if there is no reference to it. Then, what. A simple example
is shown in Listing 2.
The LeakExample class has three methods: slowlyLeakingVector,
leakingRequestLog, and noLeak.
The slowlyLeakingVector has a wrong condition in
the second for loop, due to which one String object
leaks in every iteration. Instead of String, if it
was a database record with significant size, this slow leak can result in a
non-responding application running out of memory fairly quickly. The leakingRequestLog
represents a very common case where an incoming request is kept in a hash table
till it is completed. Except in this example, the programmer has forgotten to
remove it from the hash table once the request is done. Over a period of time,
the hash table will have plenty of entries, which will result in hash-clashes
as well as a large portion of heap occupied by useless hash entries. Both of
these are very common cases resulting into Java memory leaks.
slowlyLeakingVector
leakingRequestLog
noLeak
String
Instinctively, you may think that the locations of highest memory allocation
result in leaks. However, it may not be true. For example, the noLeak
method allocates a lot of memory, but all of it gets garbage collected. On the
other hand, the other two methods don't allocate that much memory, but are causing
memory leaks.
import java.io.IOException;
import java.util.HashSet;
import java.util.Random;
import java.util.Vector;
public class LeakExample {
static Vector myVector = new Vector();
static HashSet pendingRequests = new HashSet();
public void slowlyLeakingVector(int iter, int count) {
for (int i=0; i<iter; i++) {
for (int n=0; n<count; n++) {
myVector.add(Integer.toString(n+i));
}
for (int n=count-1; n>0; n--) {
// Oops, it should be n>=0
myVector.removeElementAt(n);
}
}
}
public void leakingRequestLog(int iter) {
Random requestQueue = new Random();
for (int i=0; i<iter; i++) {
int newRequest = requestQueue.nextInt();
pendingRequests.add(new Integer(newRequest));
// processed request, but forgot to remove it
// from pending requests
}
}
public void noLeak(int size) {
HashSet tmpStore = new HashSet();
for (int i=0; i<size; ++i) {
String leakingUnit = new String("Object: " + i);
tmpStore.add(leakingUnit);
}
// Though highest memory allocation happens in this
// function, but all these objects get garbage
// collected at the end of this method, so no leak.
}
public static void main(String[] args) throws IOException {
LeakExample javaLeaks = new LeakExample();
for (int i=0; true; i++) {
try { // sleep to slow down leaking process
Thread.sleep(1000);
} catch (InterruptedException e) { /* do nothing */ }
System.out.println("Iteration: " + i);
javaLeaks.slowlyLeakingVector(1000,10);
javaLeaks.leakingRequestLog(5000);
javaLeaks.noLeak(100000);
}
}
}
IRAD,
the super cop: Java leak detection using IRAD
Since you now know that Java memory leak is not a misnomer, and you
have seen examples of such leaks, it is natural to ask how these leaks can be
identified in Java applications. IBM® Rational® Application Developer
(IRAD) can identify potential leaks by analyzing heap dumps. A heap dump is
the state of heap memory at a given point in time, and IRAD has the ability
to profile an application and collect heap dumps. Alternatively, you can import
heap dumps with tools (IBM® Text, IBM® PHD, IBM® SVC, HPROF) taken
on various platforms (see Resource [1] for how to collect
heap dumps using IBM JVM). IRAD can then analyze these heap dumps and find Java
leaks. This section will explain how to collect or import heap dumps, do leak
analysis, and understand the results. IRAD is an Eclipse-based tool, and most
Java developers will find its GUI familiar and easy to use.
Collecting
evidence: we call them heap dumps
Before collecting heap dumps, make sure that the IBM® Agent Controller
is running. It is packaged and gets installed with IRAD. It usually runs as
a service (see Resource [2] for more details on the
IBM Agent Controller).
As mentioned previously, heap dumps can be collected by profiling a program,
using these steps in the Profiling dialog.
LeakExample
Probing
the past: importing heap dumps
Alternatively, you might want to analyze heap dumps taken in customer environments.
You can import these heap dumps through the Import wizard using these steps.
Getting
on the trail: doing leak analysis
Once you have collected or imported the heap dumps, you can analyze them
for leaks by clicking the Analyze for Leak button shown in Figure
4. It will bring up the Leak Analysis dialog, in which you should
select two heap dumps, set the threshold value to 1, and click
the OK button. IRAD will perform leak analysis and bring up the
Leak Candidate view. Figure 5 shows the
Leak Candidate view with leaks in the LeakExample
program (Listing 2). IRAD found that there
are two potential leak candidates: first is a Vector
in LeakExample accumulating String,
and the second is a HashMap.
Vector
HashMap
The
great chase: browsing the Object Reference Graph
IRAD allows you to browse the Object Reference Graph (ORG) in a heap
dump. If you click a leak candidate in the Leak Candidate view,
it will bring up the ORG with a highlighted path characterizing the
leak. Figure 6 shows a screen shot with leak
candidates and the ORG for a program named simpleleaker. For example,
if you click the second leak candidate (that is, simpleleaker
class having a Vector that is leaking String
objects), IRAD will bring up the ORG with the path from simpleleaker
to Vector to String
highlighted. This is very helpful for non-trivial programs having
complex object containment and ownership. By looking at this path,
you can start from the class that is the root of the leak (simpleleaker
or LeakExample) and trace down to the object
that is leaking. The following sections of this article will examine
various characteristics of a leak candidate.
simpleleaker
Modus
operandi: understanding leak analysis results
Now that you know how to use IRAD to find memory leaks in your
Java application, we can discuss how to interpret the results. IRAD's
leak analysis identifies Leak Regions.
A Leak Region is a collection of objects that characterizes a potential
memory leak. A Leak Region consists of a Leak Root, a Container,
an Owner Chain, and Leaking Units (see Figure
7). A Leak Root is the object at the head of a data structure
that is leaking in one or more ways (in other words, a Leak Root
can be part of multiple Leak Regions). In our example, for the second
leak candidate, the leak root is an object of type LeakExample.
A container is the object that owns all leaked objects in the region
(in our example it is HashMap). A container
is typically one of the collection classes such as Vector,
List, Hash,
and so on. The Owner Chain is the path from Leak Root to Container.
The Leaking Unit is the type of the leaked objects (in our example
it is HashMap$Entry).
List
Hash
HashMap$Entry
In the Leak Candidate view, each Leak Candidate represents a Leak
Region. By understanding the constituents of a Leak Region, you
can examine the relationships of classes and identify the code that
is accumulating leaking units.
Figure 5 shows the Leak Candidate
View with columns representing Root of leak, Container
type, and What's leaking (unit type). The Owner Chain
can be identified in the Object Reference Graph view (Figure
6). The Leak Candidate view also shows Number of leaks,
Objects leaked, and Bytes leaked. The Number of
leaks is the count of all objects of the Leaking Unit type that
are held in the Container. These objects may in turn refer to other
objects (leak content). The Objects leaked and Bytes leaked
represent the number and size of objects in the leak content.
IRAD detects potential memory leaks by identifying a collection
of objects that exhibit unbound growth. The programming constructs
such as object pools exhibiting similar behavior. An object pool
consists of a predefined number of objects. When an object is needed,
it is borrowed from the pool, and when the need is over, it is returned
to the pool. An object allocation happens only when it is requested
for the first time, later it is reused, and never garbage collected.
It is a very powerful technique to avoid excessive overhead of object
creation and garbage collection, and widely used for maintaining
network or database connection pools. IRAD will identify these also
as potential memory leaks. We suggest that you take the first heap
dump such that caches and object pools are active to avoid these
false positives. Also, if you conclude that a leak candidate belongs
to an object pool, ignore it and move on to fixing the next leak
candidate.
Testimonies:
experiences of the IBM JVM L3 support group
The Java leak detection technology is based on Leakbot (see Resource
[5] for more details), technology invented in IBM® Research
Labs. The results are highly accurate, and can even detect very
slow leaks. In this section we share some of the experiences from
the IBM JVM L3 support group, which receives several issues related
to memory leaks in customer applications. L3 engineers were using
HeapRoots (Resource [6]) to browse and
query the heap dumps based on various parameters such as object
id, sub-tree size, and heap occupancy. Based on the skill of the
engineer and complexity of the case, the engineer would usually
spend a few hours to a day, manually analyzing heap dumps to identify
leaks. IRAD has automated this process. Programmers can do other
tasks while RAD is doing leak analysis, thus ensuring a much quicker
turnaround and significant savings in developer time.
We selected a set of cases that represented the whole spectrum
of complexity (heap dumps having 100,000 to 22 million objects).
The test cases encompass different kinds of heap dumps (IBM Text
and IBM PHD) on various platforms (AIX, Linux, and Windows). Table
1 shows characteristics of these cases. Each test case consists
of a pair of heap dumps. We noted object count, reference count
(number of instances where an object contains reference to another
object), and size of each heap dump. We performed leak analysis
using a 2.52 GHz Intel Pentium machine with 2 GB RAM, running Windows
XP.
The time taken by IRAD depends on the number of objects and references
in the heap dumps. Typically in a development environment, a heap
dump has between a hundred thousand and a million objects. IRAD
takes half a minute to 5 minutes for these cases. The heap dumps
from production environments contain a few million objects. One
of the biggest heap dumps with the JVM L3 group has around 22 million
objects. RAD took 2.5 hours to do the leak analysis. Without RAD,
it would have taken an L3 engineer a couple of days to identify
the leaks. Also, since it is machine time instead of developer time,
L3 engineers found RAD very useful that freed them to do other tasks
and reduce costs.
Table 1. Various
customer cases handled by IBM JVM L3 Support team
Prevent
the crime: leak detection during the Development Phase
It is said that prevention is better than cure. You can surely
use IRAD to fix Java leak problems in production systems, but dividends
will be higher if you incorporate Java leak detection into your
Development and Testing phase. For every operation, at logical break
points, you should take heap dumps, and analyze them for leaks.
For example, in a banking system, there will be account opening
operation, deposit operation, withdrawal operation. For each such
operations, you should take heap dumps at the beginning and at the
end, and do leak analysis on the pair. Essentially, you should take
heap dumps along all control paths that are exercised in your testing,
and do leak analysis on all pairs of consecutive heap dumps. In
this way, you can detect Java leaks during system development rather
than post deployment.
And then there were none...
Resources
About the authors).
Rajeev Palanki is an engineer with the IBM JVM support group in Bangalore, India. He has extensive experience in debugging Java memory leaks. He has co-authored the Java Diagnostics guide, a number of developerWork articles, and an IBM Redbook. He holds a B.E. from Government Engineering College in Bhopal, India.
Rate this page
Please take a moment to complete this form to help us better serve you.
Did the information help you to achieve your goal?
Please provide us with comments to help improve this page:
How useful is the information?
IBM, Rational, Rational PurifyPlus are trademarks
or registered trademarks of IBM Corporation in the United States, other countries,
or both. Java and all Java-based marks are trademarks
or registered trademarks of Sun Microsystems, Inc. in the United States, other
countries, or both. Other company, product or service
names may be the trademarks or service marks of others. Other company, product, or service names may be
trademarks or service marks of others.
|
http://www.ibm.com/developerworks/rational/library/05/0816_GuptaPalanki/
|
crawl-002
|
refinedweb
| 2,567
| 61.67
|
Hey I have some code in Python which is basically a World Object with Player objects. At one point the Players all get the state of the world and need to return an action. The calculations the players do are independent and only use the instance variables of the respective player instance.
while True:
#do stuff, calculate state with the actions array of last iteration
for i, player in enumerate(players):
actions[i] = player.get_action(state)
for
The most straightforward way is to use multiprocessing.Pool.map (which works just like
map):
import multiprocessing pool = multiprocessing.Pool() def do_stuff(player): ... # whatever you do here is executed in another process while True: pool.map(do_stuff, players)
Note however that this uses multiple processes. There is no way of doing multithreading in Python due to the GIL.
Usually parallelization is done with threads, which can access the same data inside your program (because they run in the same process). To share data between processes one needs to use IPC (inter-process communication) mechanisms like pipes, sockets, files etc. Which costs more resources. Also, spawning processes is much slower than spawning threads.
Other solutions include:
A big issue comes when your have to share data between the processes/threads. For example in your code, each task will access
actions. If you have to share state, welcome to concurrent programming, a much bigger task, and one of the hardest thing to do right in software.
|
https://codedump.io/share/wKL5mtkDwPve/1/easiest-way-to-parallelise-a-call-to-map
|
CC-MAIN-2016-50
|
refinedweb
| 241
| 57.77
|
Hi there fellows. In this post I am going to take you on an adventure with python sockets. They are the real backbones behind web browsing. In simpler terms there is a server and a client. We will deal with the client first. So lets first begin by importing the socket library and making a simple socket.
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Here we made a socket instance and passed it two parameters. The first parameter is AF_INET and the second one is SOCK_STREAM. AF_INET refers to the address family ipv4. ipv6 requires something different but we won’t be focusing on it. Secondly the SOCK_STREAM means connection oriented TCP protocol. Now we will connect to a server using this socket.
Connecting to a server:
Well firstly let me tell you that if any error occurs during the creation of a socket then a socket.error is thrown and secondly we can only connect to a server by knowing it’s ip. You can find the ip of the server by doing this in the command prompt or the terminal:
$ ping
You can also find the ip using python:
import socket ip = socket.gethostbyname('') print ip
So lets begin with writing our script. In this script we will connect with google. Here’s the code for it:
import socket # for socket import sys try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) print "Socket successfully created" except socket.error as err: print "socket creation failed with error %s" %(err) # default port for socket port = 80 try: host_ip = socket.gethostbyname('') except socket.gaierror: # this means could not resolve the host print "there was an error resolving the host" sys.exit() # connecting to the server s.connect((host_ip,port)) print "the socket has successfully connected to google \ on port == %s" %(host_ip)
Now save this script and then run it. You will get something like this in the terminal:
Socket successfully created the socket has successfully connected to google on port == 173.194.40.19
So what did we do here ? First of all we made a socket. Then we resolved google’s ip and lastly we connected to google. This was not useful for us though so lets move on. So now we need to know how can we send some data through a socket. For sending data the socket library has a
sendall function. This function allows you to send data to a server to which the socket is connected and server can also send data to the client using this function. Now lets make a simple server-client program to see all of this in action and hopefully it will make your concepts more clear.
Making a server :
First of all let me explain a little bit about a server. A server has a
bind() method which binds it to a specific ip and port so that it can listen to incoming requests on that ip and port. Next a server has a
listen() method which puts the server into listen mode. This allows the server to listen to incoming connections. And lastly a server has an
accept() and
close() method. The accept method initiates a connection with the client and the close method closes the connection with the client. Now lets begin making our simple()
So what are we doing here ? First of all we import socket which is necessary. Then we made a socket object and reserved a port on our pc. After that we binded our server to the specified port. Passing an empty string means that the server can listen to incoming connections from other computers as well. If we would have passed
127.0.0.1 then it would have listened to only those calls made within the local computer. After that we put the server into listen mode. What does
5 mean ? It means that 5 connections are kept waiting if the server is busy and if a 6th socket trys to connect then the connection is refused. Lastly we make a while loop and start to accept all incoming connections and close those connections after a thank you message to all connected sockets. Now we have to program a client.
Making a client :
Now we need something with which a server can interact. We could tenet to the server like this just to know that our server is working. Type these commands in the terminal:
# start the server $ python server.py # keep the above terminal open # now open another terminal and type: $ telnet localhost 12345
After typing those commands you will get the following output in your terminal:
# in the server.py terminal you will see # this output: Socket successfully created socket binded to 12345 socket is listening Got connection from ('127.0.0.1', 52617) # In the telnet terminal you will get this: Trying ::1... Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Thank you for connectingConnection closed by foreign host.
This output shows that our server is working. Now lets make our()
The above script is self explanatory but still let me explain to the beginners. First of all we make a socket object. Then we connect to localhost on port 12345 (the port on which our server runs) and lastly we receive data from the server and close the connection. Was that difficult ? I hope not. Now save this file as client.py and run it from the terminal after starting the server script:
# start the server: $ python server.py Socket successfully created socket binded to 12345 socket is listening Got connection from ('127.0.0.1', 52617) $ python client.py Thank you for connecting
I hope this intro to sockets in python was digestible for beginners. In my server and client script I have not included exception handling as it would have boggled the beginners. Now I hope that you have a solid understanding about the working of sockets in python. However there’s a lot more to it. For further study i recommend the Official python docs and this article on binary tides. If you liked this post then don’t forget to share it on facebook, tweet it on twitter and follow our blog.
You might also like:
*) *args and **kwargs in python explained
*) Making a url shortener in python
*) 10 inspirations for your next python project
26 thoughts on “Python socket network programming”
Thank you, I’ve been struggling to understand network programming for last 2 days and this is the best and clearest explanation I found on the web.
Hi Michal I am glad to hear that 🙂
Awesome post… I understood everything you posted
can you please help we with below, don’t need entire script but just helping hands
I am trying something like,
1. fetch some strings from files and check those patterns in incoming packets on port 80
2. If patterns found, output like,
Source: IP
Pattern:
URL:
Example:
Source: 198.12.45.87
Pattern: /cgi-bin
URL:
something like,
pack = s.rec(1024) for incoming packets on port 80
and then each packets captured,
if (“pattern” in pack):
print “[Source IP: , Pattern: , URL: “)
I will try to reply you once I make it.
Right here is the perfect blog for anyone who really wants to understand this topic.
You realize so much its almost hard to argue with you (not that
I really will need to…HaHa). You definitely put a fresh spin on
a topic that’s been written about for decades.
Great stuff, just wonderful!
Fine way of describing, and good post to take facts about my presentation topic, which i am going to convey in university.
dude, you saved me.
can you please give me a tip on how can i send a file from server to client.
Hi, great tutorial and very well explained, thankyou!
However I get this error:
s.bind((”, port))
OSError: [WinError 10048] Only one usage of each socket address (protocol/network address/port) is normally permitted
Anyone got any ideas?
thank you, i was having a problem regarding closing the server socket, seems like i cannot use the port more than once for the server
You can use it more than once but you can not use in two separate programs at the same time. i.e only one server should be running at any given time. For running the second server along with the first one you need to change the port. I am not sure if this answered your question or not. Feel free to reply me if it has not. 🙂
Hi can you suggest some changes in the above procedure for IPv6 implementation…
Please explain Multi-threading.
Hey thanks so much!
Great for beginners! 🙂
Reblogged this on Power to Build and commented:
Socket programming in Python?! Visit below link for a Nice post!
Can you explain, why we bind the socket to 12345, but the client connects to 52***…
I am trying to connect linux machines via telnet. I am able to connect to it and execute the commands (For Ex: “ls”), but I am not able to get the output of “ls” when I try to print it. Using exit I am closing the connection, then only I am able to read all the contents and print on my console.
Can anyone please tel me, how can I fetch the results without closing the connection and execute more commands by using same telnet connection.
This is the best python socket program help I could find
I had succeeded to set connection into my local browser and works fine… But how do I close the localhost connections? my browser still connected after I close the script .
Great blog you put up. Very informative. However id like to ask you about something else. Is it possible to apply that to two different computers ex connected in LAN. Would it be possible to run a server script and a client script in a server pc and client pc, respectively? And also id like to know if its possible to check if a certain pc is connected to a network or now by any python networking scripts? Thank you for your patience in reading this. Let me know about your answer
Nice set of tutorial. I like how you explain these topic using common language and terms, You to do not assume that the reader knows technical terms. When basically takes away that whole purpose of a beginner`s tutorial. I would suggest that next you do one on
#1 Factories
#2 Generators
#3 Iterators
#4 Tuples
#5 Sequences
#6 List
Those are topics ( in the of least understood to somewhat understood) that have baffled me in the 16 years that I have been dabbling in python.
|
https://pythontips.com/2013/08/06/python-socket-network-programming/
|
CC-MAIN-2019-30
|
refinedweb
| 1,790
| 73.68
|
Plugin Patches item #3258009, was opened at 2011-03-29 12:17
Message generated for change (Settings changed) made by kog13
You can respond by visiting:
Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: None
Group: None
>Status: Closed
>Resolution: Accepted
Priority: 5
Private: No
Submitted By: WuJiayi (wingser)
Assigned to: Nobody/Anonymous (nobody)
Summary: Javasidekick completion for members in super class
Initial Comment:
This patch will help to popup a completion while input a dot after a field or a method which inherited from the base class.
For example:
public class a extends java.io.DataInputStream
{
public void dosth()
{
in.| //We could popup a completion for in here.
}
}
----------------------------------------------------------------------
>Comment By: Damien (kog13)
Date: 2011-04-14 16:46
This should be added in the new 3.1.2 release. You may need to verify the
bug with extending a full class name, but it should at least work if you
import the class and use the shortened name.
----------------------------------------------------------------------
You can respond by visiting:
Plugin Central Submission item #3286816, was opened at 2011-04-14 16:43
Message generated for change (Tracker Item Submitted) made by kog13
You can respond by visiting:
Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: None
Group: None
Status: Open
Priority: 5
Private: No
Submitted By: Damien (kog13)
Assigned to: Nobody/Anonymous (nobody)
Summary: JavaSideKick 3.1.2
Initial Comment:
{{{ JavaSideKick 3.1.2
Source: Source code is in SVN with the tag javasidekick-3-1-2 (no SVN release numbers, please)
Announcement: Added support for completion in inherited fields and methods
Requires Java 1.5.0
Requires jEdit 04.03.99.00
Required plugins:
eclipseicons.EclipseIconsPlugin 1.0
CommonControlsPlugin 1.2
sidekick.SideKickPlugin 1.0
errorlist.ErrorListPlugin 1.9
Optional plugins:
SuperAbbrevsPlugin 0.32
projectviewer.ProjectPlugin 3.0.0
Short Description: SideKick to browse java, javacc, and property files.
Long Description: <html>
<p>.
</p>
<p>
In addition to java files, JavaSideKick also handles javacc files (.jj and .jjt)
and java property files.
</p>
</html>
}}}
----------------------------------------------------------------------
You can respond by visiting:
|
https://sourceforge.net/p/jedit/mailman/jedit-devel/?viewmonth=201104&viewday=14
|
CC-MAIN-2018-05
|
refinedweb
| 375
| 54.32
|
Somehow, despite living in a country where strong mobile and wifi networks are commonplace, I still regularly find myself confronted with apps asking me to refresh the screen, or try my previous action again. Often, this can be anticipated; I know that as I walk away from my flat in the morning, at some point my phone will drop off the wifi and reconnect to the mobile network.
If I was using an app attempting to connect to a server, then the request might not get through. This isn’t always the case, and my connection is solid for the vast majority of the time. However, when it isn’t, it can be a frustrating experience.
This is very much a first world problem, I know. It may seem tedious, or overkill, to worry about such small disconnects and error states in an app, but it is a significant problem both for new apps and those aimed at a global audience. If a new application is focused on gaining traction in a crowded marketplace, every moment counts. If users experience frustration, or are prevented from doing what they want to do, that’s a reason to uninstall and find something else.
Then there’s the rest of the world to consider. While many of us enjoy high-speed mobile networks and wifi everywhere we go, technology continues its incessant march around the globe. The next billion users, however, will not have the privilege of existing super-fast 4G networks, with many of them still relying on GSM and EDGE. Despite continuing investments, these infrastructures take years to build, so if we want to create apps for such users, we need to build them for the network they have now, not the one they will have in a few years.
Graph from the Ericsson Mobility Report 2016 displaying current and estimated mobile network subscriptions
So how do we develop apps that combat this problem? A user’s network is not something an app developer can control. Nor is it something that can be predicted. As such, the only real way to protect a user against connectivity problems is to never assume they will have strong connectivity in the first place. Most apps already implement this in a fairly simple way; there may be a check to ensure the user has an active connection before any network communication. If this is not available, it typically results in a ‘check your connection’ screen or a message informing the user they have no connection and should therefore try again later.
The problem with this solution is that the burden of fixing the issue now lies with the user. Their device might only have been disconnected for a second, which means they can retry straight away. At other times, they may experience connection issues for several minutes, leaving them stuck as they are forced to retry over and over again. On other occasions, the user might not even be aware of the problem, leading them to blame the app rather than the network.
WhatsApp demands a network sacrifice in order to update your avatar, please select and crop your image again
Some apps therefore incorporate a more intensive approach: registering with the system’s ConnectivityManager framework. This allows the app to register a broadcast receiver, which is notified of changes in connectivity as they happen. The app can thereby manage its own queue of tasks and handle waiting for a successful connection.
Unfortunately, this is a really bad approach. Not only is it expensive to run an app in the background, listening for connectivity; there is likewise no way to filter these broadcasts down. As such, any app that receives connectivity updates must receive all of them; low connectivity, disconnected, reconnected, etc.
This is so wasteful that, as of the release of Android 7.0 (Nougat), apps can no longer register for connectivity broadcasts in their manifest files, so must be active when listening. Therefore, assuming the old adage of ‘Google giveth and Google taketh away’ is true, what support does Android have for managing network tasks now that ConnectivityManager is out of the picture? In Android 5.0 Lollipop, Google added an API called Job Scheduler, which allows an app to schedule various types of jobs against the framework that guarantees these jobs will be completed.
Job Scheduler is a different way of looking at background tasks, as it doesn’t execute work based on time, but instead based on the current system conditions. This allows the system to perform actions such as batching jobs together, persisting jobs over device resets, scheduling jobs for later, running jobs once connected to a network or power, and even being aware of devices’ current memory pressure for balancing intensive tasks.
When introducing a new way of looking at background tasks, however, we also need to consider how we keep data in sync and the user informed. Job Scheduler relies a lot on the principle of acting locally and syncing globally, whereby data models are persistent, updated from external sources, and utilising callbacks to keep the user's state up-to-date.
For instance, as Job Scheduler guarantees that the job will be executed, when a user performs a task we can update the locally stored data on the device and notify the UI before we even begin the background work. To the user, it appears the request was instantaneous and the UI has already updated.
We can then perform the work in the background, and any amendments to this data can be made later during the task, even if the amendment involves rolling back the changes due to a failure. Doing this keeps the UI snappy and responsive, but it does come with some caveats like increased difficulty when it comes to managing errors and requirements on design and architecture.
Act Locally, Sync Globally
- Yigit Boyar, Android Toolkit Developer
Those responsible for design and architecture need to be involved and aware of such issues when building an app using these principles, as it is not simply down to the developers’ implementation. Rather, the way the data models are architectured must be considered, as must the design of the user interface. It is important to ensure the data can be created and stored locally, for instance. This may require a variable indicating the current synced status. Designers must also be aware of the flow the data will take and what information the user should actually see relating to this state.
Now that we’ve discussed the benefits of Job Scheduler, the question remains as to how we actually go about implementing it. The following example takes the idea of an automated home chatbot (because the best apps are those that smash two concepts together) where users can communicate in a chat-style interface with their home devices, such as lighting and the wifi router. This allows a fairly simple UI, which displays the chain of messages along with the state a message is currently in.
On Android, there are many ways to implement Job Scheduler. As mentioned above, the native API is only available on Android 5.0 (Lollipop) and above. However included in Google Play Services is an API called “GCM Network Manager” which performs many of the same tasks and supports all the way back to Android 2.2 (Froyo). In addition to this, there are several libraries that act as wrappers around the GCM Network Manager and Job Scheduler, including Firebase Job Dispatcher, Evernote Android Job, and Android Priority Job Queue.
As opposed to a straight up native approach, this example uses the Android Priority Job Queue library by Yigit Boyar to implement Job Scheduling. There are several reasons for this, including maintaining compatibility. Priority Job Queue uses Job Scheduler when available. However, when the operating system is older than Android 5.0, it will switch to Network Manager, provided Google Play Services is available. When it isn’t, it can instead make use of Alarm Manager.
In addition, while the native Job Scheduler is intended for tasks that can be deferred indefinitely, Priority Job Queue is designed to be used for all background tasks. It gives developers a greater amount of control over functionality such as persisting jobs across restarts, queuing jobs to run sequential and prioritising jobs against each other. These benefits led me to use this library, as opposed to any other approach, and allowed all background tasks to use the Job Queue instead of Async tasks or services.
/** * {@link Job} used to send messages and receive responses */ public class SendMessageJob extends BaseJob { private static final String TAG = SendMessageJob.class.getSimpleName(); private static final int PRIORITY = 1; private Message mMessage; /** * Creates a new {@link Job} to send a {@link Message}, it sets up the Job to require a network * connection, persists it across app closes and resets, and sets a tag. * * This constructor also checks the network connection to set the correct sync status. This check * is unnecessary but used here to update the UI in this example to show users the message will * send once the connection has been reestablished. * * @param context {@link Context} * @param message {@link Message} to send */ public SendMessageJob(Context context, Message message) { super(new Params(PRIORITY) .requireNetwork() // Prevent the job from executing without a network connection .persist() // Persist this job across app closures and device resets .addTags(TAG) // The TAG is used for identification and can be used for cancelling or querying jobs ); mMessage = message; if (CommonUtils.isNetworkConnected(context)) { mMessage.setSyncStatus(SyncStatus.PENDING); } else { mMessage.setSyncStatus(SyncStatus.SEND_ONCE_CONNECTED); } } /** * onAdded is called once the {@link Job} has been scheduled and serialized to disk, guaranteeing * that this {@link Job} will run. */ @Override public void onAdded() { ProviderUtils.insertOrUpdateMessage(getApplicationContext().getContentResolver(), mMessage); } /** * The actual method that should to the work. * It should finish w/o any exception. If it throws any exception, * {@link #shouldReRunOnThrowable(Throwable, int, int)} will be called to * decide either to dismiss the job or re-run it. * * @throws Throwable Can throw and exception which will mark job run as failed */ @Override public void onRun() throws Throwable { ContentResolver contentResolver = getApplicationContext().getContentResolver(); mMessage.setSyncStatus(SyncStatus.SENDING); ProviderUtils.insertOrUpdateMessage(contentResolver, mMessage); try { // Fake network latency Thread.sleep(1000); } catch (Exception e) { Timber.e("Thread sleep interrupted"); } // If the message contains fail, act like the job was cancelled for the example if (mMessage.getMessage().toLowerCase().contains("fail")) { onCancel(-1, null); return; } Response response = mAutoHomeAPI.sendMessage(mMessage).execute(); if (response.isSuccessful()) { mMessage.setSyncStatus(SyncStatus.SENT); ProviderUtils.insertOrUpdateMessage(contentResolver, mMessage); ProviderUtils.insertOrUpdateMessage(contentResolver, response.body()); } else { mMessage.setSyncStatus(SyncStatus.FAILED); ProviderUtils.insertOrUpdateMessage(contentResolver, mMessage); } } /** * Called when a job is cancelled. * * @param cancelReason Reason the job was cancelled * @param throwable The exception that was thrown from the last execution of {@link #onRun()} */ @Override protected void onCancel(int cancelReason, @Nullable Throwable throwable) { mMessage.setSyncStatus(SyncStatus.FAILED); ProviderUtils.insertOrUpdateMessage(getApplicationContext().getContentResolver(), mMessage); } /** * If {@code onRun} method throws an exception, this method is called. * * @param throwable The exception that was thrown from {@link #onRun()} * @param runCount The number of times this job run. Starts from 1. * @param maxRunCount The max number of times this job can run. Decided by {@link #getRetryLimit()} * * @return A {@link RetryConstraint} to decide whether this Job should be tried again or not and * if yes, whether we should add a delay or alter its priority. Returning null from this method * is equal to returning {@link RetryConstraint#RETRY}. */ @Override protected RetryConstraint shouldReRunOnThrowable(@NonNull Throwable throwable, int runCount, int maxRunCount) { return RetryConstraint.createExponentialBackoff(runCount, 1000); } }
So what’s actually going on here? When a user clicks the send button in the UI, the job constructor is run, which sets up the Job parameters. These include ‘requireNetwork’, which indicates the job can run only when there’s an internet connection, and ‘persist’, which guarantees the job will eventually run even after device reboots etc.
Right after the Job has been synchronised to disk, since a dependency injector has been defined, the Retrofit API is injected into the Job (see the BaseJob class), which allows us to access the mocked Auto Home API. Following this, almost immediately the onAdded method is called, indicating a Job has been accepted. It is here where we can inform the UI to display the message data to the user, with the “Pending” or “Waiting for connection” sync status.
Once all the conditions as defined by the Jobs constructor have been met (which in this case means Internet connection is available) the onRun method is called, which contains the actual work of this job, and naturally gets executed in the background.
Once the conditions are met, the Job Queue is then responsible for continually calling the onRun method until it either completes successfully or reaches a retry limit. In the example, the onRun method simply calls through to a Mocked Retrofit API, which adds a few delays, then creates a response message. onRun then adds this response to the data store.
If an exception is thrown in onRun, then the shouldReRunOnThrowable method gets called, informing the job whether it should be retried or not. If this method returns false, or all retry attempts have failed, then the onCancel method gets called. Here, the data is updated to reflect the fact the message was unable to send. We can also use this method to remove the message from the database, and inform the user etc.
Finally there is the matter of storing and persisting data. On Android, the Context class is easily considered a God object. It provides information about the app environment, access to resources and classes, as well as a whole lot more. Context is often used to store data, whether that be through the app’s shared preference, accessing a file, or accessing a database.
However Contexts are also responsible for a wide variety of memory leaks in Android apps, as they are often passed around a system, held in objects and background tasks, outliving their own lifecycle. Fortunately, Android Priority Job Queue also handles this for us by providing an instance of the Application Context at any point during the job’s execution.
There are many ways to persist data and update the UI on Android, such as ORM databases, EventBus, or even RxJava/RxAndroid. For this example, however, the messages are stored in a SQLite database, wrapped in a Content Provider. This allows direct access to the data by getting the Content Resolver from the provided Applications Context. Using a Content Provider was useful in this example for several reasons - firstly because with access to context, it is trivial to access a Content Resolver that handles executing database queries, including insert and update; and secondly because of the Content Observer capabilities.
Content Observers, classes that can be registered with a Content Provider, listen for updates to the underlying data. As such, in this example, the main fragment creates and registers an observer for the Messages table.
Whenever we update anything on this table (using the Content Provider), this class receives a callback which then notifies the RecyclerViews adapter to update the data displayed to the user. Since the observer is registered and unregistered in the Fragments onStart and onStop methods respectively, it also means that the callback does not need to worry about the state of the Fragment, if it’s alive, or even if it’s attached to an activity.
/** * {@link ContentObserver} to update the {@link RecyclerView} with the updated {@link Message} data */ private class MessageObserver extends ContentObserver { /** * Creates a content observer. * * @param handler The handler to run {@link #onChange} on, or null if none. */ MessageObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { this.onChange(selfChange, null); } /** * Retrieve the latest {@link Message} data from the database and update the {@link MessageAdapter} * @param selfChange True if this is a self-change notification * @param uri {@link Uri} of the changed content, or null if unknown */ @Override public void onChange(boolean selfChange, Uri uri) { if (uri == null) return; Cursor cursor = getContext().getContentResolver().query(uri, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { Message msg = ProviderUtils.cursorToMessage(cursor); mMessageAdapter.updateMessage(msg); } if (cursor != null) { cursor.close(); } mRecyclerview.scrollToPosition(mMessageAdapter.getItemCount() - 1); } }
Using Job Scheduler is not bulletproof. It won’t suddenly fix all the problems associated with networking, asynchronous tasks, and the Android lifecycle, and it actually makes informing users about errors even more difficult. But it’s a start, and one that decouples application logic away from activities and fragments, provides a clear system for dealing with network communication, and avoids using Async Tasks and dealing with their life cycle.
It’s also worth noting that there is a whole lot more to Job Scheduler than networking; this post barely scratches the surface. Android has been making steps towards locking down how Android apps behave in the background for a while now, and Android 8.0 (O) looks to continue this trend. Job Scheduler and similar services are the replacements, designed to be smarter and more coordinated with the system as a whole, aiming to improve Android performance and battery life.
As always, there is still a lot of room for improvement and a long way to go. But the source code can be found my gitlab repository (get in touch if you want access), or you can use the app in your browser here. Comments and pull requests are welcome.
If you found this topic interesting, and want to know how to maximise the benefits of Job Scheduler with functionality such as live data observables and SQLite database ORMs, check out the "Architecture Components" talks from Google I/O 2017.
Did you know that Android O lets users group notifications into a notification channel?
|
https://www.hedgehoglab.com/blog/android-development-connection-issues
|
CC-MAIN-2020-05
|
refinedweb
| 2,939
| 51.28
|
Asm.js, universal compatibility to applications
This subset of JavaScript defined by Mozilla gives apps and games nearly the speed of native code.
It was thought for a long time in the interest of a virtual machine in the browser to compile different languages and make them work on all operating systems. This idea took shape thanks to Mozilla developers, and Asm.js is implemented in SpiderMonkey in 2013.
It is not a real bytecode but a subset of JavaScript that is compiled and optimized for speed. It is operational in Firefox. The asm.js code is compiled AOT (Ahead Of Time), produces a reusable code unlile JavaScript which is compiled JIT (Just In Time).
We can compile various statically typed languages to LLVM bitcode, then use Emscriptem to convert it to Asm.js. The original code is already optimized, it produces faster JavaScript and Asm.js also brings speed to two times slower than binary but ten times faster than JavaScript.
An entire application can be converted into Asm.js or only a library from another language to be used in a JavaScript program .
With game developer Epic, Mozilla has implemented the 3D engine Unreal Engine 3 in Asm.js. This led to V8 developers to optimize the JavaScript compiler of Chrome and Node.js for Asm.js. Opera also has optimization for Asm.js code.
Microsoft, though, has announced the implementation of Asm.js in Windows 10 and for this, works with Mozilla.
Asm.js code since the last optimizations in December 2013 provides 1.5 times the execution time of native code to run the same program.
The new Edge browser from Microsoft, implements Asm.js, with the help of Mozilla. This has been commented by the firm in this post: Bringing Asm.js to Chackra in Microsoft Edge.
Features
From C to LLVM bitcode to Asm.js
Asm.js is compatible with JavaScript, and provides no additional function but to be validated and compiled the code must only contain the subset defined by the specification.
- Asm.js code is compiled to native code but the compiled code remains in place and is reused if the source is not changed.
- The code works on any browser but faster when Asm.js is implemented.
- This is a typed language without declaration. All the variables have a type that is assigned at compile time but not explicitly stated by the programmer.
- Annotations are statements that give a type and a default value to variables, especially when they are arguments of functions or return values. This has the form x = x | 0, the default value is 0 and the type is an integer.
- Strings are processed as memory areas.
- The only valid standard library are Math and stdlib.
- The specification does not mention objects.
- An array generic type ArrayBufferView, whose derive several numeric types.
- DOM access is not performed in Asm.js, but in common JavaScript. It is not accelerated.
- It has no garbage-collector. The code generator manages the memory allocation. It is expected to be included later.
- A module is defined like a function, whose the first line in the body is "use asm"; It contains other functions. It may be used in the standard JavaScript.
- Dynamic compilation such as eval does is possible. So the code can grow dynamically.
- It is intended to allow the storage of the generated code for a unique compilation on the first run.
One can benefit from the Asm.js language only by compiling a statically typed language because it is on this point that Asm.js get its speed. A dynamic language should rather be compiled to regular JavaScript to run in the browser.
Asm.js vs. Native Client vs. WebAssembly
Which solution should you prefer, Asm.js, or NaCl, ie programs compiled to LLVM bitcode running also in their browser?
A program under NaCl works in the browser but must be compiled for each operating system. So the author must provide multiple versions, that is not the case for Asm.js which works the same in any system.
Knowing that Mozilla does not want to implement NaCl, that excludes it from Firefox, and apparently from Internet Explorer as well.
Asm.js works automatically, since a JS compiler already exists in each browser. We know how to optimize it and it takes only a few minor changes to work on V8 or other JIT (Just-In-Time) and AOT (Ahead-Of-Time).
The announcement of WebAssembly in June 2015, obsoletes NaCl, as it will be supported by all browsers, while NaCl is only by Chrome. But this is not the case of Asm.js with which it will coexist. In fact, the wasm code will be similar to Asm.js initially before diverging. Wasm may be converted into Asm.js to run on older browsers. It may also be used in modules in JavaScript or Asm.js.
Example of code
The strlen function is defined and the letters of a string are displayed.
JavaScript:
function strlen(ptr) { var curr = ptr; while(MEM8[curr] != 0) curr++; return (curr - ptr); } var ptr = "demo"; var len = strlen(ptr); for(var i = 0; i < len; i++) { document.write(ptr[i]); }
Asm.js:
function strlen(ptr) { ptr = ptr | 0; var curr = 0; curr = ptr; while (MEM8[curr]|0 != 0) { curr = (curr + 1) | 0; } return (curr - ptr) | 0; } var ptr = "demo"; var len = strlen(ptr) | 0; for(var i = 0; i < len; i++) { document.write(ptr[i]); }
I can not guarantee that document.write is valid asm.js, it is there for the demonstration.
Emscriptem with the option ASM_JS=1 produces Asm.js code rather than JavaScript.
Documents
- Specification.
- Bananabench. Demo of 3D in the browser.
- Monster Madness (video). A commercial 3D game ported to Asm.js (within one week) with Emscriptem because it was writen in C++, fully functional, running in the browser!
- Asm.js AOT compilation. How is built the compiler, in depth. For compiler writers only.
- Slide show. From C++ to Asm.js via Emscriptem.
- A game made with asm.js. Video. Games are made with Unity or in C and converted to run in a browser, therefore on any OS!
|
https://www.scriptol.com/programming/asm-js.php
|
CC-MAIN-2020-16
|
refinedweb
| 1,027
| 69.07
|
#include <tk.h> Atom Tk_InternAtom(tkwin, name) CONST char * Tk_GetAtomName(tkwin, atom)
These procedures are similar to the Xlib procedures XInternAtom and XGetAtomName. Tk_InternAtom returns the atom identifier associated with string given by name; the atom identifier is only valid for the display associated with tkwin. Tk_GetAtomName returns the string associated with atom on tkwin's display. The string returned by Tk_GetAtomName is in Tk's storage: the caller need not free this space when finished with the string, and the caller should not modify the contents of the returned string. If there is no atom atom on tkwin's display, then Tk_GetAtomName returns the string ``?bad atom?''.
Tk.
|
http://www.linuxmanpages.com/man3/Tk_InternAtom.3.php
|
crawl-003
|
refinedweb
| 109
| 50.57
|
This page presents C++ code for computing the inverse of the normal (Gaussian) CDF. The emphasis, however, is on the process of writing the code. The discussion points out some of the things people are expected to pick up along the way but may never have been taught explicitly.
This page develops the code in the spirit of a literate program. The code will be developed in small pieces, then the final code presented at the bottom of the page. This page is not actually a literate program but it strives to serve the same purpose.
Problem statement
Basic solution
Numerical issues
Take away
Complete code
Problem statement
We need software to compute the inverse of the normal CDF (cumulative density function). That is, given a probability p, compute x such that Prob(Z < x) = p where Z is a standard normal (Gaussian) random variable. We don’t need high precision; three or four decimal places will suffice.
Basic solution
We can look up an algorithm that will essentially compute what we need. But there is some work to do in order to turn the algorithm we find into working code.
The first place to look for approximations to statistical functions is Abramowitz and Stegun or A&S at it is fondly known. Formula 26.2.23 from A&S is given below.
A&S describes the formula above as a “rational approximation for xp where Q(xp) = p.” In A&S notation, Q is the CCDF (complementary cumulative distribution function) for a standard normal. Also, A&S says that the approximation is good for 0 < p ≤ 0.5. The reported absolute error in the approximation is less than 4 × 10-4, so the accuracy is sufficient. We have two immediate problems. First, we want to invert the CDF, not the CCDF. Second, we need an algorithm for 0 < p < 1 and not just for p < 0.5.
Let F(x) be the CDF of a standard normal and let G(x) be the corresponding CCDF. We want to compute the inverse CDF, F-1(p), but A & S gives us a way to compute G-1(p). Now for all x, F(x) + G(x) = 1. So if G(x) = 1-p then F(x) = p. That means that
F-1(p) = G-1(1-p)
and so our first problem is solved. If p ≥ 0.5, 1 – p ≤ 0.5 and so the approximation from A&S applies. But what if p < 0.5?
Since the standard normal distribution is symmetric about zero, the probability of being greater than x is the same as the probability of being less than -x. That is, G(x) = p if and only if F(-x) = p. So x = G-1(p) if and only if x = -F-1(p). Thus
F-1(p) = -G-1(p).
We can use the above formula to compute F-1(p) for p < 0.5.
Numerical issues
The first step in applying the formula from A&S is to transform p into
sqrt(-2.0*log(p)). So for p < 0.5 we compute
t = sqrt(-2.0*log(p)) and evaluate the ratio of polynomials for approximating G-1(p) and flip the sign of the result. For p ≥ 0.5, we compute
t = sqrt(-2.0*log(1-p)). If
RationalApproximation is the function to evaluate the ratio of polynomials, the code for computing F-1 starts as follows.
if (p < 0.5) { // F^-1(p) = - G^-1(p) return -RationalApproximation( sqrt(-2.0*log(p)) ); } else { // F^-1(p) = G^-1(1-p) return RationalApproximation( sqrt(-2.0*log(1-p)) ); }
Writing the code for
RationalApproximation is easy. However, we introduce a technique along the way. We could evaluate a polynomial of the form a + bx +cx2 + dx3 by computing
a + b*x + c*x*x + d*x*x*x
but we could save a few cycles using Horner's method to evaluate the polynomial as
((d*x + c)*x + b)*x + a.
The time savings isn't much for a low-order polynomial. On the other hand, Horner's rule is easy to apply so it's a good habit to always use it to evaluate polynomials. It could make a difference in evaluating high-order polynomials in the inner loop of a program.
Using Horner's rule, our code for
RationalApproximation is as follows.
double RationalApproximation(double t) { const double c[] = {2.515517, 0.802853, 0.010328}; const double d[] = {1.432788, 0.189269, 0.001308}; return t - ((c[2]*t + c[1])*t + c[0]) / (((d[2]*t + d[1])*t + d[0])*t + 1.0); }
Take away
Here's a summary of a couple things this code illustrates.
- Abramowitz and Stegun is a good place to start when looking for information about statistical functions.
- Horner's method of evaluating polynomials is simple and runs faster than the most direct approach.
If you want to learn more about literate programming, I recommend Donald Knuth's book Literate Programming.
Complete code
Here we present the final code with some input validation added. We also include some code to test/demonstrate the code for evaluating F-1.= - G^-1(p)
#include <cmath> #include <sstream> #include <iostream> #include <iomanip> #include <stdexcept> double LogOnePlusX(double x); double NormalCDFInverse(double p); double RationalApproximation(double t); void demo(); double RationalApproximation(double t) { // Abramowitz and Stegun formula 26.2.23. // The absolute value of the error should be less than 4.5 e-4. double c[] = {2.515517, 0.802853, 0.010328}; double d[] = {1.432788, 0.189269, 0.001308}; return t - ((c[2]*t + c[1])*t + c[0]) / (((d[2]*t + d[1])*t + d[0])*t + 1.0); } double NormalCDFInverse(double p) { if (p <= 0.0 || p >= 1.0) { std::stringstream os; os << "Invalid input argument (" << p << "); must be larger than 0 but less than 1."; throw std::invalid_argument( os.str() ); } // See article above for explanation of this section. if (p < 0.5) { // F^-1(p) = - G^-1(p) return -RationalApproximation( sqrt(-2.0*log(p)) ); } else { // F^-1(p) = G^-1(1-p) return RationalApproximation( sqrt(-2.0*log(1-p)) ); } } void demo() { std::cout << "\nShow that the NormalCDFInverse function is accurate at \n" << "0.05, 0.15, 0.25, ..., 0.95 and at a few extreme values.\n\n"; double p[] = { 0.0000001, 0.00001, 0.001, 0.05, 0.15, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 0.85, 0.95, 0.999, 0.99999, 0.9999999 }; // Exact values computed by Mathematica. double exact[] = { -5.199337582187471, -4.264890793922602, -3.090232306167813, -1.6448536269514729, -1.0364333894937896, -0.6744897501960817, -0.38532046640756773, -0.12566134685507402, 0.12566134685507402, 0.38532046640756773, 0.6744897501960817, 1.0364333894937896, 1.6448536269514729, 3.090232306167813, 4.264890793922602, 5.199337582187471 }; double maxerror = 0.0; int numValues = sizeof(p)/sizeof(double); std::cout << "p, exact CDF inverse, computed CDF inverse, diff\n\n"; std::cout << std::setprecision(7); for (int i = 0; i < numValues; ++i) { double computed = NormalCDFInverse(p[i]); double error = exact[i] - computed; std::cout << p[i] << ", " << exact[i] << ", " << computed << ", " << error << "\n"; if (fabs(error) > maxerror) maxerror = fabs(error); } std::cout << "\nMaximum error: " << maxerror << "\n\n"; } int main() { demo(); return 0; }
|
http://www.johndcook.com/blog/normal_cdf_inverse/
|
CC-MAIN-2015-14
|
refinedweb
| 1,203
| 67.65
|
Frank Kieviet
This blog is continued on
A few months ago I decided to look at a different place to host my blog. I compared Google's blogger and wordpress, and finally decided to go with the former.
The full URL is: .
Posted at
10:00AM Mar 17, 2009
by Frank Kieviet in Sun |
Permalink:
JavaOne!
Posted at
10:46AM May 21, 2008
by Frank Kieviet in Sun |
Permalink:
Server side Internationalization made easy
Last year I wrote a blog entry on my
gripes with Internationalization in Java for server side
components. Sometime in January I built a few utilities for JMSJCA that makes
internationalization for server side components a lot easier. To make
it available to a larger audience, I added the utilities to the tools
collection on.
What do these utilities do?
Generating resource bundles automatically
The whole point was that when writing Java code, I would like to
keep internationalizable texts close to my Java code. Rather than in
resource bundles, I prefer to keep texts in my Java code so that:
- While coding, you don't need to keep switching between a Java file and a resource bundle.
- No more missing messages because of typos in error identifiers; no more obsolete messages in resource bundles
- You can easily review code to make sure that error messages make sense in the context in which they appear, and you can easily check that the arguments for the error messages indeed match.
In stead of writing code like this:
sLog.log(Level.WARNING, "e_no_match_w_pattern", new Object[] { dir, pattern, ex}, ex);
Prefer code like this:
sLog.log(Level.WARNING, sLoc.t("E131: Could not find files with pattern {1} in directory {0}: {2}"
, dir, pattern, ex), ex);
Here's a complete example:
public class X {
Logger sLog = Logger.getLogger(X.class.getName());
Localizer sLoc = Localizer.get();
public void test() {
sLog.log(Level.WARNING, sLoc.t("E131: Could not find files with pattern {1} in directory {0}: {2}"
, dir, pattern, ex), ex);
}
}
Hulp has an Ant task that goes over the generated classes and extracts these phrases and writes them to a resource bundle. E.g. the above code results in this resource bundle:
# DO NOT EDIT
# THIS FILE IS GENERATED AUTOMATICALLY FROM JAVA SOURCES/CLASSES
# net.java.hulp.i18ntask.test.TaskTest.X
TEST-E131 = Could not find files with pattern {1} in directory {0}\: {2}
To use the Ant task, add something like this to your Ant script,
typically between <javac>
and <jar>:
<taskdef name="i18n" classname="net.java.hulp.i18n.buildtools.I18NTask" classpath="lib/net.java.hulp.i18ntask.jar"/>
<i18n dir="${build.dir}/classes" file="src/net/java/hulp/i18ntest/msgs.properties" prefix="TEST" />
How does the Ant task know what strings should be copied into the
resource bundle? It uses a regular expression for that. By default it
looks for strings that start with a single alpha character, followed by
three digits followed by a colon, which is this regular expression: [A-Z]\d\d\d: .*.
Getting messages out of resource bundles
With the full English message in the Java code, how is the proper
localized message obtained? In the code above, this is done in this
statement:
sLoc.t("E131: Could not find files with pattern {1} in directory {0}: {2}", dir, pattern,.:
public static class Localizer extends net.java.hulp.i18n.LocalizationSupport {
public Localizer() {
super("TEST");
}
private static final Localizer s = new Localizer();
public static Localizer get() {
return s;
}
}
The class name should be Localizer so that the Ant task
can be extended later to automatically detect which packages use which
resource bundles.
The class name should be Localizer so that the Ant task
can be extended later to automatically detect which packages use which
resource bundles.
Using the compiler to enforce internationalized code
It would be nice if the compiler could force internationalized
messages to be used. To do that, Hulp includes a wrapper around java.util.logging.Logger that
only takes objects of class LocalizedString
instead of just String.
The class LocalizedString
is a simple wrapper around String.
The Localizer class
produces these strings. By avoiding using java.util.logging.Logger
directly, and instead using net.java.hulp.i18n.Logger
the compiler will force you to use internationalized texts. Here's a
full example:
public class X {
net.java.hulp.i18n.Logger sLog = Logger.getLogger(X.class);
Localizer sLoc = Localizer.get();
public void test() {
sLog.warn(sLoc.x("E131: Could not find files with pattern {1} in directory {0}: {2}"
, dir, pattern, ex), ex);
}
}
Logging is one area that requires internationalization, another is
exceptions. Unfortunately there's no general approach to force
internationalized messages in exceptions. You can only do that if you
define your own exception class that takes the LocalizedString in the
constructor, or define a separate exception factory that takes this
string class in the factory method.
Download
Go to
to download these utilities. The jars (the Ant
task and utilities)
are also hosted on the Maven
repository on java.net.
Posted at
04:32PM Oct 07, 2007
by Frank Kieviet in Sun |
Permalink:
Using Nested Diagnostics Contexts in Glassfish_13<<
Posted at
11:49AM Sep 30, 2007
by Frank Kieviet in Sun |
Permalink:
JavaOne)
Posted at
10:01AM May 15, 2007
by Frank Kieviet in Sun |
Permalink:
JavaOne / memory leaks revisited...
Memory."
Posted at
09:56PM May 02, 2007
by Frank Kieviet in Sun |
Permalink:
Using Resource Adapters outside of EE containers at
08:03PM Feb 04, 2007
by Frank Kieviet in Sun |
Permalink:
JMSJCA, a feature rich JMS Resource Adapter, is now a java.net project.
Posted at
10:22AM Jan 21, 2007
by Frank Kieviet in Sun |
Permalink:
Logless transactions.
Posted at
11:58AM Jan 15, 2007
by Frank Kieviet in Sun |
Permalink:
Short note: Running Java CAPS on Java SE 6
Today Java SE 6 was
released. It comes with many new features and cool tools. One of them
being jmap as described in a previous log on permgen
exceptions. The Integration Server is not officially supported on
SE 6 yet. However, if you want to run the Java CAPS integration server
on SE 6, this is what you can do:
- Install JDK 6 somewhere, e.g. c:\java
- Install the IS somewhere, e.g. c:\logicalhost
- Rename c:\logicalhost\jre to c:\logicalhost\jre.old
- Copy c:\java\jre1.6.0 to c:\logicalhost\jre
- Copy c:\java\jdk1.6.0\lib\tools.jar to c:\logicalhost\jre\lib
- Copy c:\logicalhost\jre\bin\javaw.exe to c:\logicalhost\jre\bin\is_domain1.exe
- Copy c:\logicalhost\jre\bin\javaw.exe to c:\logicalhost\jre\bin\ isprocmgr_domain1.exe
- Edit c:\logicalhost\is\domains\domain1\config\domain.xml and comment out these lines:
<!--
<jvm-options>-Dcom.sun.org.apache.xalan.internal.xsltc.dom.XSLTCDTMManager=com.sun.org.apache.xalan.internal.xsltc.dom.XSLTCDTMManager</jvm-options>
<jvm-options>-Dorg.xml.sax.driver=com.sun.org.apache.xerces.internal.parsers.SAXParser</jvm-options>
<jvm-options>-Djavax.xml.parsers.DocumentBuilderFactory=com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl</jvm-options>
<jvm-options>-Dcom.sun.org.apache.xerces.internal.xni.parser.XMLParserConfiguration=com.sun.org.apache.xerces.internal.parsers.XIncludeParserConfiguration</jvm-options>
<jvm-options>-Djavax.xml.transform.TransformerFactory=com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl</jvm-options>
<jvm-options>-Djavax.xml.parsers.SAXParserFactory=com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl</jvm-options>
<jvm-options>-Djavax.xml.soap.MessageFactory=com.sun.xml.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl</jvm-options>
<jvm-options>-Djavax.xml.soap.SOAPFactory=com.sun.xml.messaging.saaj.soap.ver1_1.SOAPFactory1_1Impl</jvm-options>
<jvm-options>-Djavax.xml.soap.SOAPConnectionFactory=com.sun.xml.messaging.saaj.client.p2p.HttpSOAPConnectionFactory</jvm-options>
-->
i.e. add <!-- before and add --> after these lines.
Also comment out this line:
<!-- <jvm-options>-server</jvm-options>-->
After these changes you can run the Integration Server with Jave SE 6. These are not “official” recommendations (as mentioned, there’s no support for SE 6 just yet); also the lines commented out are optimizations, that need to be re-established for SE 6 tet, so don’t do any performance comparisons just yet.
Posted at
10:41PM Dec 11, 2006
by Frank Kieviet in Sun |
Permalink:
Moving out of people management at
03:59PM Dec 03, 2006
by Frank Kieviet in Musings |
Permalink:
Using java.util.logging in BEA Weblogic
Some.
Posted at
02:16PM Nov 16, 2006
by Frank Kieviet in Sun |
Permalink:
More on... How to fix the dreaded "java.lang.OutOfMemoryError: PermGen space" exception (classloader leaks).
Posted at
10:29PM Nov 15, 2006
by Frank Kieviet in Sun |
Permalink:
How to fix the dreaded "java.lang.OutOfMemoryError: PermGen space" exception (classloader leaks)_54<<_55<<_56<<
Clicking on the classloader link brings up the following screen:
Scrolling down, I see Reference Chains from Rootset / Exclude weak refs . Clicking on this link invokes the code that I modified; the following screen comes up:
.
Posted at
04:10PM Oct 19, 2006
by Frank Kieviet in Sun |
Permalink:
Classloader leaks: the dreaded "java.lang.OutOfMemoryError: PermGen space" exception
Did"); } }Try to redeploy this little sample a number of times. I bet this will eventually fail with the dreaded java.lang.OutOfMemoryError: PermGen space error. If you like to understand what's happening, read on._63<<
-_64<<_65<<_66<<.
Posted at
11:40AM Oct 16, 2006
by Frank Kieviet in Sun |
Permalink:
Transactions, disks, and performance at
10:30PM Oct 11, 2006
by Frank Kieviet in Sun |
Permalink:
A free course in Java EE (link)
I found this note in my mail::
If you have anybody who wants to learn Java EE programing through hands-on style using NetBeans, please let them about this course.
Posted at
12:24PM Sep 18, 2006
by Frank Kieviet in Sun |
Permalink:
Funny videos from SunWho knew... Sun makes pretty funny commercials. See here: Sun videos. While you're there, also take a look at Project LookingGlas... impressive stuff!
Posted at
02:05PM Sep 14, 2006
by Frank Kieviet in Sun |
Permalink:
Testing connection failures in resource adapters
In a previous blog (see J2EE JCA Resource Adapters: Poisonous pools) I talked about the difficulty to detect faulty connections to the external system (EIS) that the Resource Adapter is interfacing with. A common cause of connection failures is simply connection loss. In my previous blog I detailed the problems of detecting connection loss in the RA and presented a number of ways to address this problem.
What I didn't discuss is how you can build unit tests so that you
can easily test connection failures and connection failure recovery.
That is the topic of this blog.
What is it that I will be looking at? Say that you have a resource
adapter that connects to an external system (EIS) using one or more
TCP/IP connections. The failure I want to test is that of a simple
connection drop. This can happen if the EIS is rebooted, crashes, or
simply because the network temporarily fails (e.g. someone stumbles
over a network cable).
An automated way to induce failures
How would you manually test this type of failure? You could simply
kill the EIS, or unplug the network connection. Simple and effective,
but very manual. What I prefer is an automated way so that I
can include test failures in an automated unit test suite. Here's
a way to do that:
use a port-forwarder proxy. A port forwarder proxy is a process that
listens on a particular port. Any time a connection comes in on that
port, it will create a new connection to a specified server and port.
Bytes coming in from the client are sent to the server unmodified.
Likewise, bytes coming in from the server are sent to the client
unmodified. The
client is the RA in this case; the server is the EIS. Hence, the port
-forwarder proxy sits between the Resource Adapter and the EIS.
A failure can be induced by instructing the port-forwarder proxy to
drop all the connections. To simulate a transient failure, the
port-forwarder proxy should then again accept connections and forward
them to the EIS.
Here is an example of how this port-forwarder proxy can be used in a
JUnit test. Let's say that I'm testing a JMS resource adapter. Let's
say that I'm testing the RA in an application server: I have an MDB
deployed in the application server that reads JMS messages from one
queue (e.g. Queue1) and forwards them to a different queue (e.g.
Queue2). The test would look something like this:
- start the port-forwarder proxy; specify the server name and port number that the EIS is listening on
- get the port number that proxy is listening on
- generate a connection URL that the RA will use to connect to the EIS; the new connection URL will have the proxy's server name and port number rather than the server name and port number of the EIS
- update the EAR file with the new connection URL
- deploy the EAR file
- send 1000 messages to Queue1
- read these 1000 message from Queue2
- verify that the port-forwarder has received connections; then tell the port-forwarder to kill all active connections
- send another batch of 1000 messages to Queue1
- read this batch of 1000 messages from Queue2
- undeploy the EAR file
As you can see I'm assuming in this example that you are using an
embedded resource adapter, i.e. one that is embedded in the EAR file.
Ofcourse you can also make this work using global resource adapters;
you just need a way to automatically configure the URL in the global
resource adapter.
A port forwarder in Java
My first Java program I ever wrote was a port-forwarder proxy
(Interactive Spy). I'm not sure when it was, but I do remember that
people just started to use JDK 1.3. In that version of the JDK there
was only blocking IO available. Based on that restriction a way to
write a port-forwarder proxy is to listen on a port and for each
incoming connection create two threads: one thread exclusively reads
from the client and sends the bytes to the server; the other thread
reads from the server and sends the bytes to the client. This was not a
very scalable or elegant solution. However, I did use this solution
successfully for a number of tests in the JMS test suite at SeeBeyond
for the JMS Intelligent Queue Manager in Java CAPS (better known to
engineers as STCMS). However, when I was developing the connection
failure tests for the JMSJCA Resource Adapter for JMS, I ran into these
scalability issues, and I saw test failures due to problems in the test
setup rather than to bugs in the application server, JMSJCA or STCMS.
A better approach is to make use of the non-blocking NIO
capabilities in JDK 1.4. For me this was the opportunity to explore the
capabilities of NIO. The result is a relatively small class that fully
stands on its own; I pasted the source code of the resulting class
below. The usual restrictions apply: this code is provided "as-is"
without warranty of any kind; use at your own risk, etc. I've omitted
the unit test for this class.
This is how you use it: instantiate a TCPProxyNIO passing it the
server name and port number of the EIS. The proxy will find a port to
listen on in the range of 50000. Use getPort() to find out what the
port number is. The proxy now listens on that port and is ready to
accept connections. Use killAllConnections()
to kill all connections. Make sure to destroy the proxy after use:]
*/
package com.stc.jmsjca.test.core;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Semaphore;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A proxy server that can be used in JUnit tests to induce connection
* failures, to assure that connections are made, etc. The proxy server is
* setup with a target server and port; it will listen on a port that it
* chooses itself and delegates all data coming in to the server, and vice
* versa.
*
* Implementation: each incoming connection (client connection) maps into
* a Conduit; this holds both ends of the line, i.e. the client end
* and the server end.
*
* Everything is based on non-blocking IO (NIO). The proxy creates one
* extra thread to handle the NIO events.
*
* @author fkieviet
*/
public class TcpProxyNIO implements Runnable {
private static Logger sLog = Logger.getLogger(TcpProxyNIO.class.getName());
private String mRelayServer;
private int mRelayPort;
private int mNPassThroughsCreated;
private Receptor mReceptor;
private Map mChannelToPipes = new IdentityHashMap();
private Selector selector;
private int mCmd;
private Semaphore mAck = new Semaphore(0);
private Object mCmdSync = new Object();
private Exception mStartupFailure;
private Exception mUnexpectedThreadFailure;
private boolean mStopped;
private static final int NONE = 0;
private static final int STOP = 1;
private static final int KILLALL = 2;
private static final int KILLLAST = 3;
private static int BUFFER_SIZE = 16384;
/**
* Constructor
*
* @param relayServer
* @param port
* @throws Exception
*/
public TcpProxyNIO(String relayServer, int port) throws Exception {
mRelayServer = relayServer;
mRelayPort = port;
Receptor r = selectPort();
mReceptor = r;
new Thread(this, "TCPProxy on " + mReceptor.port).start();
mAck.acquire();
if (mStartupFailure != null) {
throw mStartupFailure;
}
}
/**
* Utility class to hold data that describes the proxy server
* listening socket
*/
private class Receptor {
public int port;
public ServerSocket serverSocket;
public ServerSocketChannel serverSocketChannel;
public Receptor(int port) {
this.port = port;
}
public void bind() throws IOException {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.configureBlocking(false);
serverSocket = serverSocketChannel.socket();
InetSocketAddress inetSocketAddress = new InetSocketAddress(port);
serverSocket.bind(inetSocketAddress);
}
public void close() {
if (serverSocketChannel != null) {
try {
serverSocketChannel.close();
} catch (Exception ignore) {
}
serverSocket = null;
}
}
}
/**
* The client or server connection
*/
private class PipeEnd {
public SocketChannel channel;
public ByteBuffer buf;
public Conduit conduit;
public PipeEnd other;
public SelectionKey key;
public String name;
public PipeEnd(String name) {
buf = ByteBuffer.allocateDirect(BUFFER_SIZE);
buf.clear();
buf.flip();
this.name = "{" + name + "}";
}
public String toString() {
StringBuffer ret = new StringBuffer();
ret.append(name);
if (key != null) {
ret.append("; key: ");
if ((key.interestOps() & SelectionKey.OP_READ) != 0) {
ret.append("-READ-");
}
if ((key.interestOps() & SelectionKey.OP_WRITE) != 0) {
ret.append("-WRITE-");
}
if ((key.interestOps() & SelectionKey.OP_CONNECT) != 0) {
ret.append("-CONNECT-");
}
}
return ret.toString();
}
public void setChannel(SocketChannel channel2) throws IOException {
this.channel = channel2;
mChannelToPipes.put(channel, this);
channel.configureBlocking(false);
}
public void close() throws IOException {
mChannelToPipes.remove(channel);
try {
channel.close();
} catch (IOException e) {
// ignore
}
channel = null;
if (key != null) {
key.cancel();
key = null;
}
}
public void listenForRead(boolean on) {
if (on) {
key.interestOps(key.interestOps() | SelectionKey.OP_READ);
} else {
key.interestOps(key.interestOps() &~ SelectionKey.OP_READ);
}
}
public void listenForWrite(boolean on) {
if (on) {
key.interestOps(key.interestOps() | SelectionKey.OP_WRITE);
} else {
key.interestOps(key.interestOps() &~ SelectionKey.OP_WRITE);
}
}
}
/**
* Represents one link from the client to the server. It is an association
* of the two ends of the link.
*/
private class Conduit {
public PipeEnd client;
public PipeEnd server;
public int id;
public Conduit() {
client = new PipeEnd("CLIENT");
client.conduit = this;
server = new PipeEnd("SERVER");
server.conduit = this;
client.other = server;
server.other = client;
id = mNPassThroughsCreated++;
}
}
/**
* Finds a port to listen on
*
* @return a newly initialized receptor
* @throws Exception on any failure
*/
private Receptor selectPort() throws Exception {
Receptor ret;
// Find a port to listen on; try up to 100 port numbers
Random random = new Random();
for (int i = 0; i < 100; i++) {
int port = 50000 + random.nextInt(1000);
try {
ret = new Receptor(port);
ret.bind();
return ret;
} catch (IOException ignore) {
// Ignore
}
}
throw new Exception("Could not bind port");
}
/**
* The main event loop
*/
public void run() {
// ===== STARTUP ==========
// The main thread will wait until the server is actually listening and ready
// to process incoming connections. Failures during startup should be
// propagated back to the calling thread.
try {
selector = Selector.open();
// Acceptor
mReceptor.serverSocketChannel.configureBlocking(false);
mReceptor.serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (Exception e) {
synchronized (mCmdSync) {
mStartupFailure = e;
}
}
// ===== STARTUP COMPLETE ==========
// Tha main thread is waiting on the ack lock; notify the main thread.
// Startup errors are communicated through the mStartupFailure variable.
mAck.release();
if (mStartupFailure != null) {
return;
}
// ===== RUN: event loop ==========
// The proxy thread spends its life in this event handling loop in which
// it deals with requests from the main thread and from notifications from
// NIO.
try {
loop: for (;;) {
int nEvents = selector.select();
// ===== COMMANDS ==========
// Process requests from the main thread. The communication mechanism
// is simple: the command is communicated through a variable; the main
// thread waits until the mAck lock is set.
switch (getCmd()) {
case STOP: {
ack();
break loop;
}
case KILLALL: {
PipeEnd[] pipes = toPipeArray();
for (int i = 0; i < pipes.length; i++) {
pipes[i].close();
}
ack();
continue;
}
case KILLLAST: {
PipeEnd[] pipes = toPipeArray();
Conduit last = pipes.length > 0 ? pipes[0].conduit : null;
if (last != null) {
for (int i = 0; i < pipes.length; i++) {
if (pipes[i].conduit.id > last.id) {
last = pipes[i].conduit;
}
}
last.client.close();
last.server.close();
}
ack();
continue;
}
}
//===== NIO Event handling ==========
if (nEvents == 0) {
continue;
}
Set keySet = selector.selectedKeys();
for (Iterator iter = keySet.iterator(); iter.hasNext();) {
SelectionKey key = (SelectionKey) iter.next();
iter.remove();
//===== ACCEPT ==========
// A client connection has come in. Perform an async connect to
// the server. The remainder of the connect is going to be done in
// the CONNECT event handling.
if (key.isValid() && key.isAcceptable()) {
sLog.fine(">Incoming connection");
try {
Conduit pt = new Conduit();
ServerSocketChannel ss = (ServerSocketChannel) key.channel();
// Accept
pt.client.setChannel(ss.accept());
// Do asynchronous connect to relay server
pt.server.setChannel(SocketChannel.open());
pt.server.key = pt.server.channel.register(
selector, SelectionKey.OP_CONNECT);
pt.server.channel.connect(new InetSocketAddress(
mRelayServer, mRelayPort));
} catch (IOException e) {
System.err.println(">Unable to accept channel");
e.printStackTrace();
// selectionKey.cancel();
}
}
//===== CONNECT ==========
// Event that is generated when the connection to the server has
// completed. Here we need to initialize both pipe-ends. Both ends
// need to start reading. If the connection had not succeeded, the
// client needs to be closed immediately.
if (key != null && key.isValid() && key.isConnectable()) {
SocketChannel c = (SocketChannel) key.channel();
PipeEnd p = (PipeEnd) mChannelToPipes.get(c); // SERVER-SIDE
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">CONNECT event on " + p + " -- other: " + p.other);
}
boolean success;
try {
success = c.finishConnect();
} catch (RuntimeException e) {
success = false;
if (sLog.isLoggable(Level.FINE)) {
sLog.log(Level.FINE, "Connect failed: " + e, e);
}
}
if (!success) {
// Connection failure
p.close();
p.other.close();
// Unregister the channel with this selector
key.cancel();
key = null;
} else {
// Connection was established successfully
// Both need to be in readmode; note that the key for
// "other" has not been created yet
p.other.key = p.other.channel.register(selector, SelectionKey.OP_READ);
p.key.interestOps(SelectionKey.OP_READ);
}
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">END CONNECT event on " + p + " -- other: " + p.other);
}
}
//===== READ ==========
// Data was received. The data needs to be written to the other
// end. Note that data from client to server is processed one chunk
// at a time, i.e. a chunk of data is read from the client; then
// no new data is read from the client until the complete chunk
// is written to to the server. This is why the interest-fields
// in the key are toggled back and forth. Ofcourse the same holds
// true for data from the server to the client.
if (key != null && key.isValid() && key.isReadable()) {
PipeEnd p = (PipeEnd) mChannelToPipes.get(key.channel());
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">READ event on " + p + " -- other: " + p.other);
}
// Read data
p.buf.clear();
int n;
try {
n = p.channel.read(p.buf);
} catch (IOException e) {
n = -1;
}
if (n >= 0) {
// Write to other end
p.buf.flip();
int nw = p.other.channel.write(p.buf);
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">Read " + n + " from " + p.name + "; wrote " + nw);
}
p.other.listenForWrite(true);
p.listenForRead(false);
} else {
// Disconnected
if (sLog.isLoggable(Level.FINE)) {
sLog.fine("Disconnected");
}
p.close();
key = null;
if (sLog.isLoggable(Level.FINE)) {
sLog.fine("Now present: " + mChannelToPipes.size());
}
p.other.close();
// Stop reading from other side
if (p.other.channel != null) {
p.other.listenForRead(false);
p.other.listenForWrite(true);
}
}
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">END READ event on " + p + " -- other: " + p.other);
}
}
//===== WRITE ==========
// Data was sent. As for READ, data is processed in chunks which
// is why the interest READ and WRITE bits are flipped.
// In the case a connection failure is detected, there still may be
// data in the READ buffer that was not read yet. Example, the
// client sends a LOGOFF message to the server, the server then sends
// back a BYE message back to the client; depending on when the
// write failure event comes in, the BYE message may still be in
// the buffer and must be read and sent to the client before the
// client connection is closed.
if (key != null && key.isValid() && key.isWritable()) {
PipeEnd p = (PipeEnd) mChannelToPipes.get(key.channel());
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">WRITE event on " + p + " -- other: " + p.other);
}
// More to write?
if (p.other.buf.hasRemaining()) {
int n = p.channel.write(p.other.buf);
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">Write some more to " + p.name + ": " + n);
}
} else {
if (p.other.channel != null) {
// Read from input again
p.other.buf.clear();
p.other.buf.flip();
p.other.listenForRead(true);
p.listenForWrite(false);
} else {
p.close();
key = null;
if (sLog.isLoggable(Level.FINE)) {
sLog.fine("Now present: " + mChannelToPipes.size());
}
}
}
if (sLog.isLoggable(Level.FINE)) {
sLog.fine(">END WRITE event on " + p + " -- other: " + p.other);
}
}
}
}
} catch (Exception e) {
sLog.log(Level.SEVERE, "Proxy main loop error: " + e, e);
e.printStackTrace();
synchronized (mCmdSync) {
mUnexpectedThreadFailure = e;
}
}
// ===== CLEANUP =====
// The main event loop has exited; close all connections
try {
selector.close();
PipeEnd[] pipes = toPipeArray();
for (int i = 0; i < pipes.length; i++) {
pipes[i].close();
}
mReceptor.close();
} catch (IOException e) {
sLog.log(Level.SEVERE, "Cleanup error: " + e, e);
e.printStackTrace();
}
}
private PipeEnd[] toPipeArray() {
return (PipeEnd[]) mChannelToPipes.values().toArray(
new PipeEnd[mChannelToPipes.size()]);
}
private int getCmd() {
synchronized (mCmdSync) {
return mCmd;
}
}
private void ack() {
setCmd(NONE);
mAck.release();
}
private void setCmd(int cmd) {
synchronized (mCmdSync) {
mCmd = cmd;
}
}
private void request(int cmd) {
setCmd(cmd);
selector.wakeup();
try {
mAck.acquire();
} catch (InterruptedException e) {
// ignore
}
}
/**
* Closes the proxy
*/
public void close() {
if (mStopped) {
return;
}
mStopped = true;
synchronized (mCmdSync) {
if (mUnexpectedThreadFailure != null) {
throw new RuntimeException("Unexpected thread exit: " + mUnexpectedThreadFailure, mUnexpectedThreadFailure);
}
}
request(STOP);
}
/**
* Restarts after close
*
* @throws Exception
*/
public void restart() throws Exception {
mChannelToPipes = new IdentityHashMap();
mAck = new Semaphore(0);
mStartupFailure = null;
mUnexpectedThreadFailure = null;
mReceptor.bind();
new Thread(this, "TCPProxy on " + mReceptor.port).start();
mStopped = false;
mAck.acquire();
if (mStartupFailure != null) {
throw mStartupFailure;
}
}
/**
* Returns the port number this proxy listens on
*
* @return port number
*/
public int getPort() {
return mReceptor.port;
}
/**
* Kills all connections; data may be lost
*/
public void killAllConnections() {
request(KILLALL);
}
/**
* Kills the last created connection; data may be lost
*/
public void killLastConnection() {
request(KILLLAST);
}
/**
* Closes the proxy
*
* @param proxy
*/
public void safeClose(TcpProxyNIO proxy) {
if (proxy != null) {
proxy.close();
}
}
}
Other uses of the port-forwarding proxy
What else can you do with this port-forwarding proxy? First of all,
its use is not limited to outbound connections: ofcourse you can also
use it to test connection failures on inbound connections. Next,
you can also use it to make sure that connections are infact being made
the way that you expected. For example, the CAPS JMS server can use
both SSL and non SSL connections. I added a few tests to our internal
test suite to test this capability from JMSJCA. Here, just to make sure
that the test itself works as expected, I'm using the proxy to find out
if the URL was indeed modified and that the connections are indeed
going to the JMS server's SSL port. Similary, you can also use the
proxy to count the number connections being made. E.g. if you want to
test that connection pooling indeed works, you can use this proxy and
assert that the number of connections created does not exceed the
number of connections in the pool.
Missing components
In the example I mentioned updating the EAR file and automatically
deploying the EAR file to the application server. I've created tools
for those too so that you can do those things programmatically as well.
Drop me a line if you're interested and I'll blog about those too.
Posted at
03:59PM Sep 10, 2006
by Frank Kieviet in Sun |
Permalink:
SeeBeyond was acquired by Sun a year ago. What changed.
Posted at
12:49PM Aug 27, 2006
by Frank Kieviet in Musings |
Permalink:
.
Posted at
10:56PM Aug 26, 2006
by Frank Kieviet in Sun |
Permalink:
JMS request/reply from an EJB
Sometimes.
Posted at
04:35PM Aug 13, 2006
by Frank Kieviet in Sun |
Permalink:
J2EE JCA Resource Adapters: Poisonous pools
Introduction
Posted at
10:33PM Jul 31, 2006
by Frank Kieviet in Sun |
Permalink:
J2EE JCA Resource Adapters: The problem with XAResource wrappers.
Posted at
04:35PM Jul 23, 2006
by Frank Kieviet in Sun |
Permalink:
Resource adapters at JavaOneAt JavaOne 2006 I gave the presentation "Developing J2EE Connector Architecture Resource Adapters". I did that together with Sivakumar Thyagarajan. He works in Sun's Bangalore office.
That he works there, while I work in Monrovia California... that's one of the interesting things about working at Sun: it's very international. Sun has people in all corners of the world. Last week I was on a phone call with perhaps 20 other people, and 12 of them were from other countries.
I talked to Sivakumart a few times on the phone before JavaOne, but met him only face to face for the first time at JavaOne. That's also one of the nice things about JavaOne: you get to meet people face to face you otherwise only talk with on the phone.
The presentation went pretty well, and the audience agreed: at the end of the presentation all audience members can fill in an evaluation form. Here are the feedback results
If you're interested, here's some more information:
JavaOne session information of "Developing J2EE Connector Architecture Resource Adapters"
Slide presentation "Developing J2EE Connector Architecture Resource Adapters"
I've recorded the presentation on my MP3 player:
Audio presentation of "Developing J2EE Connector Architecture Resource Adapters" (.wav)
Audio presentation of "Developing J2EE Connector Architecture Resource Adapters" (.mp3)
Posted at
10:43PM Jul 22, 2006
by Frank Kieviet in Sun |
Permalink:
Next: JCA Resource adaptersAt Sun I'm responsible for the application server and the JMS server that are shipping as part Java CAPS. As such I've been involved quite a bit in resource adapters (Java Connector Architecture, or JCA).
All this serves as an introduction to some more technical blogs on resource adapters.
Posted at
09:59PM Jul 22, 2006
by Frank Kieviet in Sun |
Permalink:
Automatic log translationWhy would I want to translate logs from one locale to another?
Say that I were to build a product, and I do a nice job to make it internationalizable. The product is a success, and it is localized into various languages. Next, a customer in a far-away place sends an email complaining about the server failing to start up. For my convenience, he attached the log file to it. Since I did a good job writing decent error and logging messages, I expect it to be no problem to diagnose what's going wrong. But oops, since I did such a nice job internationalizing the product, the log is in some far-away language, say Japanese! Now what?
Let me give exemplify the example. Let's say that the log contains this entry:
(F1231) Bestand bestelling-554 in lijst bestellingen kon niet geopend worden: (F2110) Een verbinding metLooks foreign to you? (It doesn't to me, but I would have great problems if this example were in Japanese).
server 35 kon niet tot stand gebracht worden.
Fortunately, through the error codes, we could make an attempt to figure out what it says by looking up the error codes. However, if there are many log entries, this becomes a laborious affair. Would it be possible to obtain an English log file without tedious lookups and guess work?
I think there are a few different approaches to this problem:
- always create two log files: an English one and a localized one.
- store the log in a language-neutral form, and use log viewers that render the log in a localized form
- try to automatically "translate" the localized log file into English
try {The exception message is already localized when it is thrown. E.g. in the catch-block, there is already no language neutral message anymore. It would have been nice if there were a close cousin to the Object.toString() method: one that takes the locale: toString(Locale) and if the Exception class would take an Object instead of limiting itself to a String.
...
throw new Exception(msgcat.get("F2110: Could not establish connection with server {0}", serverid));
} catch (Exception e) {
String msg = msgcat.get("F1231: Could not open file {1} in directory {0}: {2}", dir, file, ex);
throw new IOException(msg, ex);
}
In a previous product where I had more control over the complete codebase, I approaches this problem by introducing a specialized text class that supported the toString(Locale) method, and Exception classes that could return this text class. This solution was also ideal for storing text in locale-neutral form in a database, so that different customers could view the data in different locales.
There is a kludgy work-around: we could change the msg.get() method so that it returns a String that is locale neutral rather than localized. A separate method would convert the locale neutral String into a localized String, e.g. msg.convert(String, Locale). This method would have to be called any time a String would be prepared for viewing, e.g. in the logging for a localized log.
In the products that I am currently working on, these approaches to support locale-neutral strings are not feasible because they would require widespread. So let's take a look at option 3.
Given the resource bundle
F1231 = Bestand {1} in lijst {0} kon niet geopend worden: {2}and
F2110 = Een verbinding met de server {0} kon niet tot stand gebracht worden.
F1231 = Could not open file {1} in directory {0}: {2}let's see if there is a way to automatically translate the message
F2110 = Could not establish connection with server {0}
(F1231) Bestand bestelling-554 in lijst bestellingen kon niet geopend worden: (F2110) Een verbinding metinto
server 35 kon niet tot stand gebracht worden.
(F1231) Could not open file bestelling-554 in directory bestellingen: (F2110) Could not establish aI think it is possible to build a tool that can do that. The tool would read in all known resource bundles (possibly by pointing it to the installation image, after which the tool would scan all jars to exttact all resource bundles), and translate them into regular expressions. It would have to be able to recognize error codes (e.g. \([A..Z]dddd\) ) and use these to successively expand the error message into its full locale neutral form. In the example, the neutral form is:
connection with server 35.
[F1231, {0}=bestellingen, {1}=bestelling-554, {2}=[F2110, {0}=35]]The neutral form then can be easily converted into the localized English form.
Posted at
05:50PM Jul 16, 2006
by Frank Kieviet in Sun |
Permalink:
Internationalization of logging and error messages for the server side (cont'd)In Thursday's entry I proposed that a tool is needed to make it easier to internationalize sources where the English error messages are kept in the source file, and the foreign language messages are in resource bundles.
Let's talk about this tool. There are a few different approaches to go about this tool. As Tim Foster remarked in his comments, it's possible to parse the source code. This approach is doable, especially when existing tools are used (Tim mentioned.
Another approach is to parse the compiled byte code. Using tools like BCEL, it's fairly simple to read a .class file, and extract all the strings in there. It could easily be run on the finished product: just add some logic to go over the installation image, find all jars, and then iterate over all .class files in the jars.
Fortunately the compiler makes a string that is split up over multiple lines in the source into one:
String msg = msgcat.get("F1231: Could not open file {1}"is found in the .class file as:
+ " in directory {0}: {2}", dir, file, ex);
F1231: Could not open file {1} in directory {0}: {2}So it's simple to extract strings from a .class file. But how can we discern strings that represent actual error messages from other strings? Error messages can be discerned from other strings because they start with an error message number. The error message number should follow a particular pattern. In the example
String msg = msgcat.get("F1231: Could not open file {1} in directory {0}: {2}", dir, file, ex);the pattern (regular expression) is
[A-Z]dddd\:Note that a similar trick would have been used when parsing source code, unless some logic is applied to find only those strings thar are used in particular constructs, like calling methods on loggers, or constructors of exceptions. This can quickly become very complicated because often log wrapper classes are used instead of java.util.Loggers.
This is also the answer to a question that I didn't pose yet: in the following code,
String msg = msgcat.get("F1231: Could not open file {1} in directory {0}: {2}", dir, file, ex);how does the msgcat object localize messages? It does that by extracting the error code from the message (F1231) applying the same regular expression, or by splitting the string on the colon. In either case, it's important to have a convention on how the error message looks like or is embedded into the message.
throw new IOException(msg, ex);
Next problem: how to re-localize an existing log so that an American support engineer can read a log from his product that was created on a Japanese system?
Posted at
03:45PM Jul 15, 2006
by Frank Kieviet in Sun |
Permalink:
Internationalization of logging and error messages for the server side (cont'd)
I ended my previous blog with "Isn't there a better way"? Well...
how would I like to use error messages in Java
source code? I would simply want to write something like this:
String msg = msgcat.get("F1231: Could not open file {1} in directory {0}: {2}", dir, file, ex);The advantages are clear:
throw new IOException(msg, ex);
- No switching to a different file to add the error message
- The error message is visible right there in the source code -- easy to review!
- It's easy to see that the arguments in {0}, {1} are correct
How is this source file internationalized? We need a tool! The tool will
- locate all error messages in the code base
- generate properties files for all desired languages if they don't exist
- print out a list of all properties files that need to be localized
msgs_en_US.propertiesand
# AUTOMATICALLY GENERATED# DO NOT EDIT
# com.stc.jms.server.SegmentMgr
F1231 = Could not open file {1} in directory {0}: {2}
msgs_nl_NL.properties
# com.stc.jms.server.SegmentMgr
# F1231 = Could not open file {1} in directory {0}: {2}
# ;;TODO:NEW MESSAGE;;F1231 =
so that a human translator can easily add the translations to the foreign properties files. As you can see, it includes the location (Java class) where the message was encountered.
msgs_nl_NL.propertiesOfcourse the tool would have a way of handling if you would change the error message in the source code. The translated properties file would look like this:
# com.stc.jms.server.SegmentMgr
# F1231 = Could not open file {1} in directory {0}: {2}
F1231 = Bestand {1} in lijst {0} kon niet geopend worden: {2}
msgs_nl_NL.propertiesAny ideas on how to build this tool?
# com.stc.jms.server.SegmentMgr
# F1231 = File {1} in directory {0} could not be opened: {2}
# F1231 = Could not open file {1} in directory {0}: {2}
# ;;TODO: MESSAGE CHANGED;;
F1231 = Bestand {1} in lijst {0} kon niet geopend worden: {2}
Posted at
11:30PM Jul 13, 2006
by Frank Kieviet in Sun |
Permalink:
Internationalization of logging and error messages for the server sideThis is how one would throw an internationalizable message:
String msg = msgcat.get("EOpenFile", dir, file, ex);The localized message is typically in a .properties file, e.g.
throw new IOException(msg, ex);
EOpenFile=F1231: Could not open file {1} in directory {0}: {2}Each language has its own .properties file. The msgcat class is a utility class that loads the .properties file. Logging messages to a log file typically uses the same constructs.
Looks cool, right? So what's my gripe?
- when coding this, you would have to update .properties file in addition to the .java file you're working on
- It's easy to make a typo in the message identifier, EOpenFile in the example above; there is no compile time checking for these "constants".
- It's difficult to check that the right parameters are used in the right order ({0}, {1}) etc.
- When reviewing the .java file, it's difficult to check that the error message is used in the right context and that the error message is meaningful in the context.
- When reviewing the .properties files, it's difficult to determine where these error messages are used (if at all!) -- you can only find out through a full text search
Posted at
10:26PM Jul 10, 2006
by Frank Kieviet in Sun |
Permalink:
|
http://blogs.sun.com/fkieviet/
|
crawl-002
|
refinedweb
| 6,949
| 56.76
|
Introduction
A lot of social media platforms have been using AI these days to classify vulgar and offensive posts and automatically take them down. I thought why not try doing something similar; and so, I’ve come up with this end-to-end tutorial that will help you build your own corpus for training a text classification model, and later export and deploy it on an Android app for you to use. All this, absolutely on a custom dataset of your choice.
So, are you excited to build your own text classifier app? If yes, let’s begin the show.
Now, before we begin, let me tell you that we’ll be doing all the model’s hyperparameter configuration and training on Google Colab. To build the Android app, we’ll need to have Android Studio. If you haven’t installed it yet, find it here.
Step 1: Build a corpus
I’m building a text classifier that will classify an input text as offensive or non-offensive. Hence, for simplicity purposes, I have limited my text classification model to two classes. Feel free to create a custom dataset of your choice with any number of classes. The overall process will exactly be the same.
Coming to the data collection part, let me be honest here. Although plenty of datasets are available on Kaggle, I didn’t find any of them suitable for my application. So, I have manually built my own dataset by scraping texts and quotes online, that I felt could be best classified as offensive or non-offensive. I have collected about 1000 sentences and labelled them as ‘offensive’ and ‘non-offensive’, depending upon the nature of the language used in each sentence. The ratio of the training and test data is 7:3.
Below is a snapshot of how my dataset looks like.
Dataset
Note: Needless to say, but hope it is understood that no offense is intended for anyone here. 🙂
To create your own dataset, create a CSV file containing two columns – sentence and label respectively as shown in the image above. Add the texts and their respective labels in both these columns. The first column is the index column which is later created by the Pandas library automatically. Simply ignore it while creating your dataset.
Note: If your dataset contains many labels, make sure you collect enough data for each label so that the dataset doesn’t become biased.
Once you’ve collected enough texts for your corpus, split the dataset into two different CSV files – train.csv and test.csv respectively. The ideal ratio would be 7:3. As I keep repeating in my articles, “Garbage in, garbage out”. So, take your own sweet time to build the corpus and do not hurry.
Alright, if you feel you have created a healthy dataset with enough text samples, you’re good to go for the next step.
Step 2: Training the model
Clone this GitHub repository on your local machine. Inside this repository, you’ll find a notebook file named Custom_Text_Classification.ipynb.
Sign in to your Google account and open the notebook on Google Colab and connect to the runtime. Upload the train.csv and test.csv files you created in Step 1; as shown in the figure below.
Connect to runtime and upload a dataset
Now, run the notebook cells one by one by following the instructions.
Install TF Lite Model Maker
Install the TensorFlow Lite Model Maker library. TF Lite Model Maker makes it easy to train models on a custom dataset and reduces time to train by using Transfer Learning on pre-trained models.
!pip install -q tflite-model-maker
Install necessary libraries.
import numpy as np from numpy.random import RandomState import pandas as pd import os from tflite_model_maker import model_spec from tflite_model_maker import text_classifier from tflite_model_maker.config import ExportFormat from tflite_model_maker.config import QuantizationConfig from tflite_model_maker.text_classifier import AverageWordVecSpec from tflite_model_maker.text_classifier import DataLoader import tensorflow as tf assert tf.__version__.startswith('2') tf.get_logger().setLevel('ERROR')
Import dataset
df_train = pd.read_csv('train.csv', error_bad_lines = False, engine = "python") df_test = pd.read_csv('test.csv', error_bad_lines = False, engine = "python")
View dataset
Check your dataset and see if it is properly imported or not.
df_train.head()
Sample Train Data
df_test.head()
Sample Test Data
Choose a model architecture.
Choose any one model architecture of your choice and comment the rest. Each model architecture is different from the other and will yield different results. The MobileBERT model takes more time to train as its architecture is quite complex. However, feel free to play with different architectures until you find the best result.
spec = model_spec.get(‘average_word_vec’)
# spec = model_spec.get(‘mobilebert_classifier’)
# spec = model_spec.get(‘bert_classifier’)
# spec = AverageWordVecSpec(wordvec_dim = 32)
The architecture and working of these models are beyond the scope of this article. However, if you want to learn more about how each of these models works, feel free to visit the following link.
Summary of different Text Classification Models [Reference: Official TensorFlow website].
Customize the MobileBERT model hyperparameters (optional).
MobileBERT Hyperparameter Configuration
Run this cell only if you have selected the ‘mobilebert_classifier’ architecture in the previous cell.
# spec.seq_len = 256
Load training and test data.
Load the training and test data CSV files to prepare the model training process. Make sure the
is_training parameter for
test_data is set to
False.
train_data = DataLoader.from_csv( filename = 'train.csv', text_column = 'sentence', label_column = 'label', model_spec = spec, is_training = True) test_data = DataLoader.from_csv( filename = 'test.csv', text_column = 'sentence', label_column = 'label', model_spec = spec, is_training = False)
Train model.
Start the model training on the training dataset. Feel free to play around with different no. of epochs until you find the ideal epoch value that gives the best results.
model = text_classifier.create(train_data, model_spec = spec, epochs = 100)
Examine your model structure – Layers of the neural network.
model.summary()
Model Summary
Evaluate the model
Evaluate the model accuracy on the test data and see for yourself if the model needs some tweaking such as an increase in the dataset or hyperparameter tuning in order to increase the accuracy.
loss, acc = model.evaluate(test_data)
Export TF Lite model
The final model is exported as a TF Lite model which can be downloaded and directly deployed on your Android app.
model.export(export_dir = ‘average_word_vec’)
When you run the above cell, a folder named ‘average_word_vec’ will be created that contains the TF Lite model named
model.tflite. Download this model on your local machine.
TF Lite Model
This model is now ready to be deployed on our Android app now. But where is the Android app? Find it in the next step.
Step 3: Creating an Android app
I’ve already built an Android app by referencing the official TensorFlow Lite text classification app and customizing it to my own needs where the predictions can be represented visually. You can find this app inside the
Android_App folder in the repository you cloned earlier.
Now, let’s deploy the model on the app.
Copy the
model.tflite file inside the
Custom-Text-Classification-on-Android-using-TF-Lite/Android_App/lib_task_api/src/main/assets directory.
Once you’ve copied the model in the designated directory, open the project in Android Studio and let it build itself for some time. Meanwhile, the project builds, let’s go for a walk and have a cup of beverage together. I’d prefer tea over coffee on any given day. 🙂
Now, when the project is finally built successfully, all you have to do is, open the
TextClassificationClient.java file under
lib_task_api and edit Line 31 by replacing
<your_model.tflite> it with the name of your model file. In this case, replace it with
model.tflite . Build the project once again after making this change.
What’s next? Nothing. Sip your coffee and install the app on your mobile and enjoy using your own text classification app.
Testing the app
So, congratulations on building your own end-to-end custom text classifier app. If you enjoyed working on it, don’t forget to give the repository a star. Feel free to fork it and update the app with more exciting features.
About me: I’m Nitin Tiwari, a B.E undergraduate in Information Technology. I’m currently exploring Machine Learning and Computer Vision. If you liked my article and would want to talk more about it, feel free to connect with me on LinkedIn. Happy to address any feedbacks and queries too. Till then, adieu.
The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion.You can also read this article on our Mobile APP
|
https://www.analyticsvidhya.com/blog/2021/05/custom-text-classification-on-android-using-tensorflow-lite/
|
CC-MAIN-2021-25
|
refinedweb
| 1,432
| 58.69
|
Thin DSL for creating input_algorithms
Project Description
Release History
Download Files
Input Algorithms
A DSL to assist with writing specifications describing valid data and testing that inputted data meets those defined specifications.
Why the name?
I got the inspiration from the movie Transcendence when a character says something to the effect of “We could do this if we had better input algorithms”.
Installation
Use pip!:
pip install input_algorithms
Or if you’re developing it:
pip install -e . pip install -e ".[tests]"
USAGE
Here is an example to help you use the library.
from input_algorithms.validators import Validator from input_algorithms.dictobj import dictobj from input_algorithms import spec_base as sb from input_algorithms.meta import Meta import re meta = Meta({},[]) # 1. Create a class defining your fields. class PersonDictObj(dictobj): fields = ["name", "age"] # 2. Create custom validate methods as required. class ValidName(Validator): def validate(self, meta, val): matcher = re.compile("^[A-Za-z\ ]+$") if not matcher.match(val): raise Exception("{0} doesn't look like a name.".format(val)) return val class ValidAge(Validator): def validate(self, meta, val): if val > 120: raise Exception("I don't believe you are that old") return val # 3. Tie together the pieces. person_spec = sb.create_spec( PersonDictObj, name = sb.required(sb.valid_string_spec(ValidName())), age = sb.and_spec(sb.integer_spec(), ValidAge()), ) # 4. Have some data data = {"name": "Ralph", "age": 23} # 5. Normalise the data into your object normalised = person_spec.normalise(meta, data) # 6. Use the object! print("Name is {0}".format(normalised.name)) print("Age is {0}".format(normalised.age))
Tests
To run the tests in this project, just use the helpful script:
./test.sh
Or run tox:
tox
Release History
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/input_algorithms/
|
CC-MAIN-2017-43
|
refinedweb
| 294
| 54.49
|
Hey everyone: I'd like to make a short announcement that with the permission of its maintainer, I've uploaded HList v0.1 to Hackage. You can find the Hackage page here: <>. 'cabal install HList' should also work. HList for those who don't know is a sort of OO Haskell package which permits heterogeneous lists; you can find out more at <>. (The Darcs repository is at <>.) What changes have been made to the darcs repo? Well, they are mostly updates and cleanups - I've updated build-depends for GHC 6.8.x; largely moved from -fglasgow-exts to LANGUAGE pragmas; put the modules in a proper module namespace; fixed up Haddock generation; removed some unused files, and other things of that nature. -- gwern Covert data bank Armani Larson Missiles Dick CTP SO13 AUTODIN -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 189 bytes Desc: not available Url :
|
http://www.haskell.org/pipermail/haskell-cafe/2008-February/039062.html
|
CC-MAIN-2014-35
|
refinedweb
| 156
| 75.1
|
A Quick and Practical Example of Kafka Testing
A Quick and Practical Example of Kafka Testing
In this tutorial, we learn some of the fundamental aspects of Kafka testing in a declarative way and how to test microservices involving both Kafka and REST.
Join the DZone community and get the full member experience.Join For Free
Record growth in microservices is disrupting the operational landscape. Read the Global Microservices Trends report to learn more.
1. Introduction
In this tutorial, we will quickly explore some basic to high-level approaches for testing microservices applications built using Kafka. Also, we will learn about the advantages of the declarative way of testing Kafka applications over the traditional/existing way of testing.
For everything explained here, we can find running code examples in the "Conclusion" section of this post.
To keep the tutorial concise, we will demonstrate only the below aspects.
- Producer Testing
- Consumer Testing
- Hooking Both Producer and Consumer Tests
- Producing RAW records and JSON records
- Consuming RAW records and JSON records
- Traditional Testing Challenges.
- Advantages of Declarative Style Testing
- Combining REST API Testing with Kafka Testing
- Spinning Up Kafka in Docker - Single Node and Multi-Node
I strongly recommend reading through the Minimum Things We Need To Know For Kafka Testing post before proceeding with this tutorial.
For more details about Kafka streams and how to develop a streaming application, please visit Developing Streaming Applications Tutorial by Confluent.
2. Kafka Testing Challenges
The difficult part is some part of the application logic or a DB procedure keeps producing records to a topic and another part of the application keeps consuming the records and continuously processes them based on business rules.
The records, partitions, offsets, exception scenarios, etc. keep on changing, making it difficult to think in terms of what to test, when to test, and how to test.
Photo credit:@dnevozhai:unsplash
3. Testing Solution Approach
We can go for an end-to-end testing approach which will validate both producing, consuming, and DLQ records as well as the application processing logic. This will give us good confidence in releasing our application to higher environments.
We can do this by bringing up Kafka in dockerized containers or by pointing our tests to any integrated test environment somewhere in our Kubernetes-Kafka cluster or any other microservices infrastructure.
Here we pick a functionality, produce the desired record and validate, consume the intended record and validate, alongside the HTTP REST or SOAP API validation which helps in keeping our tests much cleaner and less noisy.
Photo credit:@jannerboy62:unsplash
4. Producer Testing
When we produce a record to a topic we can verify the acknowledgment from a Kafka broker. This verification is in the format of
recordMetadata.
For example, visualizing the "recordMetaData" as JSON would look like:
Response from the broker after a successful "produce". { "recordMetadata": { "offset": 0, "timestamp": 1547760760264, "serializedKeySize": 13, "serializedValueSize": 34, "topicPartition": { "hash": 749715182, "partition": 0, //<--- To which partition the record landed "topic": "demo-topic" } } }
5. Consumer Testing
When we read or consume from a topic we can verify the record(s) fetched from the topics. Here we can validate/assert some of the metadata too, but most of the time you might need to deal with the records only (not the metadata).
There may be times, for instance, that we validate only the number of records, i.e. the size only, not the actual records
For example, visualizing the fetched "records" as JSON would look like:
Records fetched after a successful "consume". { "records": [ { "topic": "demo-topic", "key": "1547792460796", "value": "Hello World 1" }, { // ... } ] }
The full record(s) with the meta-data information looks like what we've got below, which we can also validate/assert if we have a test requirement to do so.
The fetched records with the metadata from the broker. { "records": [ { "topic": "demo-topic", "partition": 0, "offset": 3, "key": "1547792460796", //<---- Record key "value": "Hello World", //<---- Record value } ] }
6. Producer and Consumer Testing
In the same end-to-end test, we can perform two steps like below for the same record(s):
- Step 1:
- Produce to the topic "demo-topic" and validate the received
recordMetadatafrom the broker.
- For example, produce a record with
"key":"1234", "value":"Hello World"
- Step 2:
- Consume from the same topic "demo-topic" and validate records.
- Assert that the same record was present in the response, i.e.
"key": "1234", "value": "Hello World".
- We might have consumed more than one record if they were produced to the same topic before we started consuming.
7. Challenges With the Traditional Style of Testing
Point 1
In the first place, there is nothing wrong in with the traditional style. But it has a steep learning curve to deal with when it comes to Kafka brokers.
For instance, when we deal with the brokers, we need to thoroughly get acquainted with the Kafka Client APIs, e.g. Key-SerDe, Value-SerDe, Time-Outs while record Poolings, commitSyncs, recordTypes, etc., and many more things at the API level.
For functional testing, we don't really need to know these concepts at the API level.
Point 2
Our test code gets tightly coupled with the client API code. This means we introduce many challenges in maintaining the test suites along with test framework's code.
8. Advantages of the Declarative Style of Testing
To draw a simile, the interesting way 'docker-compose' works is called the "Declarative Way." We tell the Docker Compose framework (in a YAML file) to spin up certain things at certain ports, link certain service to another service etc and things are done for us by the framework. We can drive our tests also in similar declarative fashion, which we are going to see in next sections.
How neat is that? Just think how much of a hassle it would be if we had to write code/shell scripts for the same repetitive tasks.
Point 1
In the declarative style, we can completely skip the API level that deals with brokers and only focus on test scenarios. But still, we have the flexibility to use the Kafka Client APIs and to add our own flavors to it.
Point 2
This contributes to finding more defects because we don't spend time in writing code, but spend more time in writing tests and covering more business scenarios/user journeys.
How?
Here, we tell the test to use the Kafka-Topic which is our "end point" or "url"
i.e.
"url": "kafka-topic: demo-topic"
Next, we tell the test to use operation "produce"
i.e.
"operation":"produce"
Next, we need to send the records to the request payload:
"request": { "records": [ { "key": "KEY-1234", "value": "Hello World" } ] }
Then, we tell the test that we are expecting the response "status" to be returned as "Ok" and some record metadata from the broker i.e. a not-null value. This is the "assertions" part of our test.
"assertions": { "status" : "Ok", "recordMetadata" : "$NOT.NULL" }
Note: We can even assert all the '
recordMetadataat once, which we will see in the later sections. For now, let's keep it simple and proceed.
Once we are done, our full test will look like the code below:
{ "name": "produce_a_record", "url": "kafka-topic:demo-topic", "operation": "produce", "request": { "recordType" : "RAW", "records": [ { "key": 101, "value": "Hello World" } ] }, "assertions": { "status": "Ok", "recordMetadata": "$NOT.NULL" } }
And that's it. We are done with the test case and ready to run.
Now, looking at the test above, anyone can easily figure out the what scenario being tested is.
Note that:
We eliminated the coding hassles using the client API to deal with Kafka brokers.
We eliminated the coding hassles of asserting each field key/value by traversing through their object path, parsing request-payloads, parsing response-payloads, etc.
At the same time, we used the JSON comparison feature of the framework to assert the outcome at once, therefore, making the tests a lot easier and cleaner.
We escaped two major hassles while testing.
And, the order of the fields doesn't matter here. The below code is also correct (field order swapped).
"assertions": { "recordMetadata": "$NOT.NULL" "status": "Ok", }
9. Running a Single Test Using JUnit
It's super easy. We just need to point our JUnit
@Test method to the JSON file. That's it really.
@TargetEnv("kafka_servers/kafka_test_server.properties") @RunWith(ZeroCodeUnitRunner.class) public class KafkaProduceTest { @Test @JsonTestCase("kafka/produce/test_kafka_produce.json") public void testProduce() throws Exception { // No code is needed here. What? // Where are the 'assertions' gone ? } }
In the above code:
'test_kafka_produce.json' is the test case which contains the JSON step(s) we talked about earlier.
'kafka_test_server.properties' contains the "Broker" details and producer/consumer configs.
'@RunWith(ZeroCodeUnitRunner.class)' is a JUnit custom runner to run the test.
Also, we can use the Suite runner or Package runner to run the entire test suite.
Please visit these RAW and JSON examples and explanations.
10. Writing Our First Producer Test
We learned in the above section how to produce a record and assert the broker response/acknowledgment.
But we don't have to stop there. We can go further and ask our test to assert the
"recordMetadata" field-by-field to verify it was written to the correct "partition" of the correct "topic" and much more, as shown below.
"assertions": { "status": "Ok", "recordMetadata": { "offset": 0, //<--- This is the record 'offset' in the partition "topicPartition": { "partition": 0, //<--- This is the partition number "topic": "demo-topic" //<--- This is the topic name } } }
That's it. In the above "assertions" block, we finished comparing the expected vs. actual values.
Note: The comparisons and assertions are instantly done. The "assertion" block is instantly compared against the actual "status" and "recordMetadata" received from the Kafka Broker. The order of the fields doesn't really matter here. The test only fails if the field values or structures don't match.
11. Writing Our First Consumer Test
Similarly, to write a "consumer" test, we need to know:
The topic name 'demo-topic' is our "end point," a.k.a. "url":
"url": "kafka-topic: demo-topic".
The operation, i.e. 'consume':
"operation": "consume".
While consuming message(s) from the topic, we need to send as below:
"request": { }
The above 'request' means to do nothing but consume without doing a 'commit'.
Or we can mention in our test to do certain things while consuming or after consuming the records.
"request": { "consumerLocalConfigs": { "commitSync": true, "maxNoOfRetryPollsOrTimeouts": 3 } }
"commitSync": true: Here, we are telling the test to do a `commitSync` after consuming the message, that means, it won't read the message again when you `poll` next time. It will only read the new messages if any arrive on the topic.
"maxNoOfRetryPollsOrTimeouts": 3: Here, we are telling the test to show the poll a maximum of three times, then stop polling. If we have more records, we can set this to a larger value. The default value is 1.
"pollingTime": 500: Here, we are telling the test to poll for 500 milliseconds each time it polls. The default value is 100 milliseconds if you skip this flag.
Visit this page for All configurable keys - ConsumerLocalConfigs from the source code.
Visit the HelloWorld Kafka examples repo to try it at home.
Note: These config values can be set in the properties file globally to all the tests, which means it will apply to all the tests in our test pack. Also, we can override any of the configs for a particular test or tests inside the suite. Hence it gives us flexibility for covering all kind of test scenarios.
Well, setting up these properties is not big deal and we have to do this to externalize them anyway. Hence, the simpler they are maintained, the better for us! But we must get an idea of what goes inside them.
We will discuss this in the coming sections.
12. Combining REST API Testing With Kafka Testing
Most of the time in a microservices architecture, we build applications using RESTful services, SOAP services (probably legacy), and Kafka.
Therefore, we need to cover all API contract validations in our end-to-end test scenarios, including Kafka.
But it's not a big deal as, after all, nothing changes here, except we just point our "url" to the HTTP endpoint for our REST or SOAP service, then manipulate payload/assertions block accordingly. That's it really.
Please visit Combining Kafka testing with REST API testing for a full step by step approach.
If we have a usecase:
Step 1: Kafka call - We send an "Address" record with id "id-lon-123" to the "address-topic," which eventually gets processed and written to the"Address" database (e.g. Postgres or Hadoop). We then assert the broker acknowledgment.
Step 2: REST call - Query (GET) the "Address" REST API by using "/api/v1/addresses/id-lon-123" and assert the response.
The corresponding test case looks like below.
{ "scenarioName": "Kafka and REST api validation example", "steps": [ { "name": "produce_to_kafka", "url": "kafka-topic:people-address", "operation": "produce", "request": { "recordType" : "JSON", "records": [ { "key": "id-lon-123", "value": { "id": "id-lon-123", "postCode": "UK-BA9" } } ] }, "assertions": { "status": "Ok", "recordMetadata" : "$NOT.NULL" } }, { "name": "verify_updated_address", "url": "/api/v1/addresses/${$.produce_to_kafka.request.records[0].value.id}", "operation": "GET", "request": { "headers": { "X-GOVT-API-KEY": "top-key-only-known-to-secu-cleared" } }, "assertions": { "status": 200, "value": { "id": "${$.produce_to_kafka.request.records[0].value.id}", "postCode": "${$.produce_to_kafka.request.records[0].value.postcode}" } } } ] }
Easy to read! Easy to write!
Field reused values via JSON path instead of hardcoding. It's a great time saver!
13. Producing RAW Records vs. JSON Records
1. In the case of RAW, we just say it quietly:
"recordType" : "RAW",
Then, our test case looks like below:
{ "name": "produce_a_record", "url": "kafka-topic:demo-topic", "operation": "produce", "request": { "recordType" : "RAW", "records": [ { "key": 101, "value": "Hello World" } ] }, "assertions": { "status": "Ok", "recordMetadata": "$NOT.NULL" } }
2. And for the JSON record, we mention it in the same way:
"recordType" : "JSON"
And, our test case looks like below:
{ "name": "produce_a_record", "url": "kafka-topic:demo-topic", "operation": "produce", "request": { "recordType" : "JSON", "records": [ { "key": 101, "value": { "name" : "Jey" } } ] }, "assertions": { "status": "Ok", "recordMetadata": "$NOT.NULL" } }
Note: The "value" section has a JSON record this time.
14. Kafka in a Docker
Ideally, this section should have been at the beginning. But, what's the point of just running a docker-compose file without even knowing the outcome of it? We can find it here to make everyone's life easy!
We can find the docker-compose files and the step-by-step instructions below.
15. Conclusion
In this tutorial, we learned some of the fundamental aspects of Kafka testing in a declarative way. Also, we learned how easily we can test microservices involving both Kafka and REST.
Using this approach, we have tested and validated clustered Kafka Data Pipelines to Hadoop as well as Http REST/SOAP APIs deployed in Kubernetes orchestrated pods. We found this approach very very straight forward and reduced complexity to maintain and promote the artifacts to the higher environments.
With this approach, we were able to cover a lot of test scenarios with full clarity and find more defects in the early stages of the development cycle, even without writing any test code. This helped us to build up and maintain our regression pack in an easy and clean manner.
The complete source code of these examples of the repo GitHub(Try at Home) are given below.
To run any test(s), we can directly navigate to their corresponding JUnit
@Test, under 'src/test/java'. We need to bring up Docker with kafka prior to clicking any Junit tests.
Use "kafka-schema-registry.yml (See Wiki)" to be able to run all the tests.
- Produce Tests (RAW and JSON)
- Consume Tests (RAW and JSON)
- Produce Records Directly From File
- Consume Records and Dump to File
If you found this page helpful for testing Kafka and HTTP APIs, please leave a "star" on GitHub!
Happy testing!
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }}
|
https://dzone.com/articles/a-quick-and-practical-example-of-kafka-testing?utm_medium=feed
|
CC-MAIN-2019-13
|
refinedweb
| 2,663
| 63.49
|
Here's a smaller 10 by 10 matrix (the above are 500 by 500) which probably needs to come with a health warning:
The code to do this using Sage is pretty easy (it makes use of the
plotmethod on matrices):
import os size = 500 nbrofmatrices = 100 for i in range(nbrofmatrices): print "Ploting matrix: %i of %s" % (i + 1, nbrofmatrices) A = random_matrix(RR,size) p = A.plot(cmap='hsv') p.save('./plots/%.3d.png' % i) print "Converting plots to gif" os.system("convert -loop 0 ./plots/*png %sanimatedmatricesofsize%s.gif" % (nbrofmatrices, size))
Each of the three above gifs were made using different colour maps: (ie changing the cmap option).
This creates 100 random 500 by 500 matrices and uses imagemagik (that's a link to a blog post I wrote about creating these) to create an animated gif.
|
http://drvinceknight.blogspot.co.uk/2013/09/for-no-reason-whatsoever-animated-gifs.html
|
CC-MAIN-2017-43
|
refinedweb
| 139
| 55.17
|
Introduction
The iWidget is an IBM specification that provides a standard definition for a widget, allowing for seamless interoperability across various platforms and products. An iWidget is a browser-based component model that encapsulates web content and can participate in content presentation frameworks. It acts as a wrapper for any web content that you create.
In this article, learn several best practices for developing iWidgets. It's common to use JavaScript libraries in iWidgets. Dojo is used in this article. Most of the best practices still apply if other JavaScript libraries are used, however. IBM Mashup Center is used as the target runtime to display iWidgets.
You can download and deploy a sample iWidget to IBM Mashup Center to see how it works (see the Download table below).
This article assumes you have a basic understanding of developing iWidgets. See Resources for more information.
Setting up the environment
Before you can develop iWidgets you need to set up the appropriate development environment. A good development environment can increase productivity. The development environment consists of:
- A build-time environment to write the source code of iWidgets
The build-time environment depends on the server-side implementation technique used for the iWidget. You can choose your favorite IDE according to the server-side programming language. If Java EE™ is used, the recommended IDE is Eclipse with WTP (Web Tools Platform) plug-ins. You can use Apache Tomcat as the web container.
- An iWidget runtime to initialize iWidgets and see how they work for end users
The best iWidget runtime is IBM Mashup Center, where it is very simple to add and view iWidgets. There are two ways to add iWidgets to IBM Mashup Center:
- Add an iWidget package in WAR or zip format.
When a package is used, the iWidget is actually hosted on IBM Mashup Center.
- Add the URL of an iWidget's definition XML file.
Using the URL iWidget's definition XML is a better choice for development. Once changes have been made to the iWidget, you don't have to package and deploy the iWidget again as long as the URL is not changed.
See Resources for links to get the tools mentioned above.
Creating an iWidget
Once the development environment is ready, you can start to create new iWidgets. Use the following steps:
- Create a Dynamic Web Project in Eclipse for an iWidget.
- Create the iWidget's definition XML file that contains minimum content only.
- Deploy the project to Apache Tomcat using Eclipse WTP, and start the server.
- Get the URL of the iWidget's definition XML and add it to IBM Mashup Center.
- View the iWidget in IBM Mashup Center.
- Continue to edit the iWidget and view the result.
After you complete the steps above, you can add more content to the project.
An XML file that conforms to the iWidget specification is the only requirement of an iWidget. The XML file can contain inline HTML, CSS, and JavaScript code. It's possible to contain all the HTML, CSS, and JavaScript code in the XML file, but it makes the code messy and hard to maintain. Using inline HTML, CSS, and JavaScript code is only recommended for small iWidgets or as the output of a build process. (Read more about a build process later in this article.)
For iWidgets that have complicated logic, HTML, CSS, and JavaScript code should be separated into different files.
Figure 1 shows the basic directory layout of a typical iWidget. Files of client-side code are placed under the WebContent folder. JavaScript and CSS files are placed under the js folder and css folder, respectively.
Figure 1. Basic directory layout of an iWidget
Avoiding namespace pollution
An iWidget may expose some global variables. When multiple iWidgets have been added to the same page, they should not conflict with each other. An iWidget should make sure the global namespace is not polluted.
The iWidget's scope object needs to be visible in the global object. Choose
a good name for it. For example, a name such as
com.example.widget.myWidget.MyWidget is better
than
MyWidget since short names are more likely
to cause collision. All other JavaScript objects should be kept in the
same namespace.
It is recommended that you add a special CSS class name to the root node of
each mode, for example:
com_example_widget_myWidget.
This class name should be prepended to all the selectors used in the
iWidget's CSS file. Listing 1 shows some sample
CSS declarations.
Listing 1. Sample CSS declarations of an iWidget
.com_example_widget_myWidget { } .com_example_widget_myWidget .header { } .com_example_widget_myWidget .body { }
Another kind of global name that is easily ignored is the topic name used by
dojo.publish() and
dojo.subscribe(). There may be multiple
instances of the same iWidget existing on the same page. If all these
instances subscribe to the same topic, it can cause serious problems. For
example, imagine an iWidget that manages items of a logged-in user. One
instance publishes a topic to delete an item for a user. Other instances
can receive this topic and can delete the items of other users. To solve
the potential problem, the unique ID of an iWidget instance must be part of the topic name.
The iWidget instance's ID can be retrieved using
this.iContext.widgetId. A good example of a topic
name is
com/example/widget/myWidget/deleteItem/{widgetId}.
Using dijit
An iWidget can have different modes. Each mode has its own structure,
style,
and behavior. You can write HTML fragment code for each mode in
the definition XML file directly. Listing 2 below shows
a code snippet of an iWidget's view mode. The special variable
IWID will be replaced with the iWidget's unique
ID after the iWidget is loaded.
Listing 2. Write HTML code of a mode in the definition XML file
<iw:content <![CDATA[ <div> <input id="_IWID_hobby" type="text"> <button id="_IWID_addButton">Add</button> </div> ]]> </iw:content>
This approach is only suitable when the mode's content is simple; otherwise, it's difficult to implement and maintain.
The recommended approach is to create a dijit for each mode. For example, if the iWidget supports both view and edit mode, a dijit is created for the view mode and another dijit is created for the edit mode. The benefit of this approach is that it's much simpler for certain tasks when dijits are used.
When developing iWidgets you might want to:
- Find certain DOM nodes and manipulate them. If a mode's HTML fragment is declared directly in the iWidget's definition XML file, an ID should be assigned to the DOM node, and
dojo.byId()should be used to find the node. While in a dijit, you can use
dojoAttachPointto declare DOM nodes visible to the dijit's JavaScript object.
- Bind event listeners to certain DOM nodes. If dijits are not used, the DOM nodes should be found first, and then
dojo.connect()is used to bind event listeners.
dojo.disconnect()is also needed to remove the listeners when the iWidget is unloaded. In a dijit, you can use
dojoAttachEventto bind event listeners declaratively.
- Add globalization support by using Dojo's
dojo.i18nmodule (when dijits are used). See the Globalization section of this article for more details.
The dijits used in an iWidget can be created declaratively or
programmatically. If dijits are declared in the iWidget's definition XML
file, you must invoke
dojo.parser.parse() to initialize those dijits
after the iWidget is loaded. It should be done only once for each
mode. The better choice is to create dijits programmatically.
Listing 3 and Listing 4 provide the basic HTML and JavaScript code skeletons for using dijits in iWidgets.
Listing 3. Basic HTML code skeleton for using dijits
<iw:iwidget <iw:content <![CDATA[ <div id="_IWID_viewRoot" class="com_example_sampleIWidget"> </div> ]]> </iw:content> <iw:content <![CDATA[ <div id="_IWID_editRoot" class="com_example_sampleIWidget"> </div> ]]> </iw:content> </iw:iwidget>
Listing 4. Basic JavaScript code skeleton for using dijits
onview : function() { if (!this._viewMode) { var viewRoot = this.byId("viewRoot"); var node = dojo.create("div", {}, viewRoot, "only"); this._viewMode = new sampleIWidget.widget.ViewMode({}, node); } }, onedit : function() { if (!this._editMode) { var editRoot = this.byId("editRoot"); var node = dojo.create("div", {}, editRoot, "only"); this._editMode = new sampleIWidget.widget.EditMode({}, node); } }, onUnload : function() { if (this._viewMode) { this._viewMode.destroyRecursive(); this._viewMode = null; } if (this._editMode) { this._editMode.destroyRecursive(); this._editMode = null; } }
As shown in the two listings above, the HTML fragment of view mode and edit
mode is very simple.
It contains only one DOM node as the containers of the mode's content. In
the
onview and
onedit functions of iWidget's scope object,
dijits are created programmatically. A new node is created first as the
only child of the container node. The new node makes destroying the
dijit easier since the mode's original DOM structure is kept after
destroying the dijit. Be sure to destroy the dijits when the iWidget is
unloaded from the page. Use a dijit's
destroyRecursive() in the iWidget's
onUnload() function to destroy it.
Handling mode switches
An iWidget at a minimum has the view mode. Most iWidgets also have the edit
mode to allow end users to customize the iWidget's behavior. The user can
switch between different modes. When the iWidget has been switched to view
mode or edit mode, the corresponding function,
onview() or
onedit(), will be invoked. Keep in mind that
onview() and
onedit() may be invoked multiple times.
If the
default mode is view mode, after the iWidget is loaded
onview() will be invoked. When the user
switches to edit mode,
onedit() is invoked.
Once the user has finished the edit and goes back to the view mode,
onview() is invoked again.
If the user made changes in edit mode, the changes should be reflected in view mode. One approach is to recreate the view mode again from scratch, which means the dijit is destroyed and initialized again. This approach is possible because the changes have been stored into the iWidget's item set. (Read more about item set later in this article.) It is simple but slow, especially when the user interface and logic are complicated.
Another approach is to partially update, and not recreate, the dijits. This approach is complicated to implement but has better performance. In an extreme example, if the user does nothing in the edit mode and the former approach is used, then the whole user interface is recreated unnecessarily.
iWidget developers must choose from the two approaches above. Listing 5 shows an example of using partial update to handle mode switching.
Listing 5. Partially update a mode's content
//In edit mode var changeSummary = {...}; dojo.publish("com/example/sampleIWidget/editFinished/{widgetId}", [changeSummary]); //In view mode dojo.subscribe("com/example/sampleIWidget/editFinished/{widgetId}", dojo.hitch(this, function(changeSummary) { //Use changeSummary to update the user interface this._toViewMode(); }));
Basically, the user's changes are collected in edit mode and a JSON object is used to represent these changes. If the user decides to save the changes, this JSON object is passed to the view mode and the view mode is updated according to the content in this JSON object.
Using item set
Item set is persistence storage that an iWidget can use to store user preferences and internal data. If data needs to be persistent and should be available when the iWidget is loaded next time, it should be stored in the item set. For example, a weather forecast iWidget needs to store the city name the user has selected. Standard APIs can be used to set and get data from the item set.
An item set is a collection of items. Each item is a name-value pair. Item set itself is very simple to use.
Use a single JSON object
Some iWidgets might have a lot of configuration values that end users can customize. These values should be stored in the item set. One choice is to store each configuration value into its own item in the item set. The drawback of this approach is that multiple items in the item set need to be read or written for a single operation. The code is cumbersome and hard to maintain.
A better choice is to put the configuration values into a single JSON object and store the serialized string of this JSON object. The benefit is that a JSON object is much easier to use than the item set.
Add data type to items
When using APIs to get and set the value of an item, only a string can be
used as
the data type. To store a boolean value or an integer to the item set, the
value needs to be converted to a string. The string value retrieved from
the item set also needs to be transformed into the correct data type. For
example, a boolean value should be string value
true or
false before
being saved to the item set.
Performing the data type conversion is a common task, so this piece of code can be reused. Listing 6 shows an example implementation.
Listing 6. Add data types to items in the item set
_setupItemSetEditor : function() { this._itemSetEditors = { "boolean" : { fromItemSet: function(rawValue){ return rawValue === "true" ? true : false; }, toItemSet: function(formattedValue){ return formattedValue ? "true" : "false"; } }, "integer" : { fromItemSet: function(rawValue){ return parseInt(rawValue, 10); }, toItemSet: function(formattedValue){ return formattedValue.toString(); } }, "json" : { fromItemSet: function(rawValue){ rawValue = dojo.trim(rawValue) != "" ? rawValue : "{}"; return dojo.fromJson(rawValue); }, toItemSet: function(formattedValue){ return dojo.toJson(formattedValue); } }, "string" : { fromItemSet: function(rawValue){ return rawValue; }, toItemSet: function(formattedValue){ return formattedValue.toString(); } } }; }, _loadItemSet : function() { var attrs = this.iContext.getiWidgetAttributes(); var itemNames = attrs.getAllNames(); var resultObj = {}; var itemDescs = this._itemSetDescription; var editors = this._itemSetEditors; for (var i = 0, n = itemNames.length; i < n; i++) { var itemName = itemNames[i], itemValue = attrs.getItemValue(itemName), itemDesc = itemDescs[itemName], dataType = itemDesc.type, editor = editors[dataType]; resultObj[itemName] = editor.fromItemSet(itemValue); } return resultObj; }, _saveItemSet : function(itemSetObj) { var attrs = this.iContext.getiWidgetAttributes(); var itemDescs = this._itemSetDescription; var editors = this._itemSetEditors; for (var name in itemSetObj) { if (itemSetObj.hasOwnProperty(name)) { var value = itemSetObj[name], itemDesc = itemDescs[name], dataType = itemDesc.type, editor = editors[dataType]; attrs.setItemValue(name, editor.toItemSet(value)); } } attrs.save(); }, _describeItemSet : function() { this._itemSetDescription = { "name" : {type : "string"}, "age" : {type : "integer"}, "maritalStatus" : {type : "boolean"}, "preferences" : {type : "json"} }; }
As shown above, the
_setupItemSetEditor function is used to create several
editors for different data types, including editors for
boolean,
integer,
json, and
string.
Each editor has two functions,
fromItemSet and
toItemSet, to convert from and to values in the
item set.
The
_loadItemSet function
loads values from the item set and applies the editors, and then returns a
JSON object that contains the items with correct data types. The
_saveItemSet function accepts a JSON object and stores
its value into the item set.
The editors are also used to get the strings
stored. To make the editors work, the iWidget should declare the
data types of the items in the item set. Use the
_describeItemSet function for the declaration.
Globalization
Using dijits for an iWidget's mode content makes globalization much
simpler. The dojo.i18n module provides good
support for globalization. A message bundle can be loaded in the iWidget's
onLoad() function using
dojo.requireLocalization(). Before that,
though,
the
dojo.registerModulePath() function should be
invoked to register the module name of the current iWidget. Then Dojo
can find the correct path to load the message bundle files. Once the
bundle file is loaded,
dojo.i18n.getLocalization() is used to get a
JSON object that can be used directly in source code to get localized
messages. Typically, the JSON object is mixed into dijits and referenced
in the templates. Listing 7 shows basic usage
of Dojo's globalization support.
Listing 7. Globalization support
dojo.registerModulePath("sampleIWidget", this.rewriteURI("js")); dojo.requireLocalization("sampleIWidget", "messages"); this.nls = dojo.i18n.getLocalization("sampleIWidget", "messages");
In the example above,
this.rewriteURI() is a utility function to
convert a relative path into a full path using
this.iContext.io.rewriteURI().
Handling resizing
Some iWidget runtimes allow end users to resize the iWidgets after the
iWidgets have been added to the page. An iWidget should react to this user
action and re-layout its content accordingly. If the
onSizeChanged function is defined in the iWidget's scope
object, it will be invoked when the runtime detects that the size of the
iWidget has been changed. The iWidget's new size is passed in as a
parameter.
The size change can happen when the iWidget is in different modes. When handling the resizing, the iWidget's current mode needs to be checked first. Listing 8 shows the code snippet to handle resizing.
Listing 8. Handle resizing
_setupSizeChangedHandlers : function() { this._sizeChangedHandlers = { "view" : { node : this.byId("viewRoot"), callback : dojo.hitch(this, this._viewModeChanged) }, "edit" : { node : this.byId("editRoot"), callback : dojo.hitch(this, this._editModeChanged) } }; }, _viewModeChanged : function() { }, _editModeChanged : function() { }, onSizeChanged : function(iEvent) { var p = iEvent.payload; var width = p.newWidth, height = p.newHeight; var currentMode = this.iContext.getiDescriptor().getItemValue("mode"); var handler = this._sizeChangedHandlers[currentMode]; if (handler && handler.node) { var node = handler.node; dojo.marginBox(node, { w : width, h : height }); var callback = handler.callback, thisObject = handler.thisObject; if (dojo.isFunction(callback)) { callback.call(thisObject || dojo.global); } } }
In the
_setupSizeChangedHandlers function a DOM
node to be resized and an optional callback function are registered for
each mode. Once the
onSizeChanged
function is invoked, the DOM node registered for current mode is resized and the
callback function is invoked.
Build process
After an iWidget is developed and tested it can be released and deployed to a production environment. Before that, though, a build process should be applied to the iWidget to meet certain non-functional requirements, including compatibility and performance.
Compatibility
A single iWidget is a deliverable to end users, and it may evolve from version to version. Different versions of the same iWidget should coexist on the same page without conflicts. For example, the user might want to use the old version to work with other iWidgets and use the new version to try new features at the same time.
An iWidget should be built with a version
number that increases from version to version. To make sure
different versions of the same iWidget coexist on the same page, each
version should not pollute the global namespace. For example, the sample
iWidget declares a global object
SampleIWidget.
If different versions use the same object name, when they are added to the
same page they will share the same object and cause serious problems.
The solution is to add version numbers to an iWidget's global names,
including JavaScript object names and CSS class names. For example, the
scope object name of the sample iWidget should become
SampleIWidget_100 and
SampleIWidget_200 for version 1.00 and 2.00
respectively. During the build process, a small script can do full text
search and append the version number to those global names.
Package resource files
An iWidget can have many resource files, including JavaScript, CSS, and
image files. Resource files are included using the
<resource> tag in the iWidget's
definition XML file. Each resource file is downloaded by the runtime when
loading the iWidget. There is a performance penalty if there are too many HTTP
requests to download resources. A good practice is to package multiple
files of the same type into a single file. Ideally, there should be only
one JavaScript file and one CSS file.
There are many tools you can use to combine and minify JavaScript and CSS files (see Resources). Choose a tool and integrate it into the iWidget's build process. You can also embed all the JavaScript and CSS files in the iWidget's definition XML file. By doing this, only one HTTP request is required to load an iWidget.
Summary
iWidgets are used in many IBM products. With the help of IBM Mashup Center, end users can use different iWidgets to create powerful mashups. The iWidget is a simple component model. It's easy to get started if you want to develop iWidgets. By applying the best practices outlined in this article, you can avoid common mistakes and create high-quality iWidgets.
Download
Note
- Deploy the sample iWidget to IBM Mashup Center to see how it works.
Resources
Learn
- Read iWidget Specification 2.0 to understand iWidget's component model.
- Follow the IBM Mashup Center wiki for community-driven, authoritative, and current content.
- Read the Dijit Reference Guide to understand dijit.
- The Dojo Internationalization Reference Guide has information on internationalization (the process of making an application flexible to work in different languages and respect different conventions and customs).
- Stay current with developerWorks technical events and webcasts focused on a variety of IBM products and IT industry topics.
- Attend a free developerWorks Live! briefing to get up to date quickly on IBM products and tools as well as IT industry trends.
- Follow developerWorks on Twitter.
- Watch developerWorks on-demand demos ranging from product installation and setup demos for beginners, to advanced functionality for experienced developers.
Get products and technologies
- Try IBM Mashup Center.
- Download Eclipse and Web Tools Platform.
- Download Apache Tomcat.
- Use Dojo ShrinkSafe and YUI Compressor to combine and minify JavaScript files.
Discuss
- Create your My developerWorks profile today and set up a watchlist on widgets or Dojo..
|
http://www.ibm.com/developerworks/web/library/wa-iwidgets/
|
CC-MAIN-2016-18
|
refinedweb
| 3,533
| 58.99
|
In Silverlight you can interact directly with the HTML DOM (Document Object Model). This can be done through the HtmlPage.Document object:
HtmlDocument doc = HtmlPage.Document;
HtmlDocument doc = HtmlPage.Document;
Make certain to first add a reference to the following namespace:
using System.Windows.Browser;
using System.Windows.Browser;
To illustrate this point I will walk you through a demo that will change the background color of your HTML Page when you click a button. To create this demo, follow these steps:
Step 1. Create a new Silverlight Application using Visual Studio 2008.
Step 2. Open up the your Test page (such as SilverlightApplication1TestPage.aspx) and modify the DIV tag surrounding your Silverlight object to have an ID and background color. In addition, set the width and height to be 20% and your Silverlight control to be 50% wide so that the Silverlight control does not overlap the entire background of the HTML page:
<div id="myDIV" style="background:blue;width:20%;height:20%"> <asp:Silverlight </div>
Step 3. In Page.xaml add a button with a click event:
<UserControl x:Class="SilverlightApplication1.Page"
xmlns=""
xmlns:
<Canvas>
<Button Click="Button_Click" Content="Change Colors"></Button>
</Canvas>
</UserControl>
Step 4. In Page.xaml.cs and the following code which will change the background color of your HTML Page. You will notice we are:
private void Button_Click(object sender, RoutedEventArgs e)
{
HtmlDocument doc = HtmlPage.Document;
HtmlElement div = doc.GetElementById("myDIV");
div.SetStyleAttribute("background", "green");
}
Step 5. Run the application. The background of the Silverlight control is white where as the background of the HTML page is blue.
Screen shot before click:
Screen shot after click:
In Silverlight you can interact directly with the HTML DOM (Document Object Model). This can be done
In This Issue: Dhiraj Gupta, Peter Brombert, Bill Reiss, Jesse Liberty, Mike Snow, Terence Tsang, Lee
Pingback from 2008 October 07 - Links for today « My (almost) Daily Links
Pingback from Silverlight news for October 7, 2008
Pingback from Dew Drop - October 7, 2008 | Alvin Ashcraft's Morning Dew
Post: Approved at: Oct-8-2008 Tip:How to Popup a Browser Window "Let’s say a user clicks on a button
Pingback from Zugriff auf HTML DOM ??ber Silverlight at Blog von J??rgen Ebner
I knew that the interaction was possible, but I've been avoiding it, thinking that it's complications may cause me to blow a the mental fuse. Your example makes it look approachable.
Thank you.
Silverlight Tip of the Day #57 Title: How to Dynamically Load a Silverlight Control within another Silverlight » Blog Archive » ??????????????? ??? ??????
|
http://silverlight.net/blogs/msnow/archive/2008/10/06/silverlight-tip-of-the-day-56-accessing-the-html-dom-from-silverlight.aspx
|
crawl-002
|
refinedweb
| 427
| 56.35
|
The OpenDocument Format (ODF) is an XML-based file format for representing electronic documents such as spreadsheets, charts, presentations and word processing documents. The standard was developed by the OASIS (Organization for the Advancement of Structured Information Standards), and it is a free and open format.
The OpenDocument format is used in free software and in proprietary software. Originally, the format was implemented by the OpenOffice.org office suite and, with Office 2007 SP2, Microsoft also supports ODF subset.
This article will explain the basics of ODF format, and specifically its implementation in spreadsheet applications (OpenOffice.org Calc and Microsoft Office Excel 2007 SP2). Presented is a demo application which writes/reads tabular data to/from .ods files. The application is written in C# using Visual Studio 2010. Created .ods files can be opened using Excel 2007 SP2 or greater and OpenOffice.org Calc.
OpenDocument format supports document representation:
Office applications use the second approach, so we will explain the following benefits:
There are four subdocuments in the package that contain file's data:
Besides them, in the package, there can be many other subdocuments like document thumbnail, images, etc.
In order to read the data from an ODF file, you need to:
On the other side, if you want to create a new ODF file, you need to:
Spreadsheet document files are the subset of ODF files. Spreadsheet files have .ods file extensions.
The content (sheets) is stored in content.xml subdocument.
As we can see in Picture 1, sheets are stored as XML elements. They contain column and row definitions, rows contain cells and so on... In the picture is data from one specific document, but from this we can see the basic structure of content.xml file (you can also download the full ODF specification).
Our demo is Windows Presentation Foundation application (picture 2) written in C# using Visual Studio 2010.
The application can:
Internally, spreadsheet document is stored as DataSet. Each sheet is represented with DataTable, sheet's row with DataRow, and sheet's column with DataColumn. So, to create a new document, we have to create a new DataSet, with DataTables. Each DataTable has a number of rows and columns that conforms to our needs.
DataSet
DataTable
DataRow
DataColumn
DataTables
To show data from our DataSet (and to allow editing that data) the application dynamically creates tabs with DataGridViews (that are connected to our DataTables).
DataGridViews
Through the interface, a user can read, write, edit data and add new rows to the Spreadsheet document.
As application, basically, transforms Spreadsheet document to / from DataSet, it can also be used as a reference for Excel to DataSet export / import scenarios.
Although classes from System.IO.Packaging namespace (.NET 3.0) provide a way to read and write ZIP files, they require a different format of ZIP file. Because of that, our demo uses the open source component called DotNetZip.
System.IO.Packaging
Using ZIP component we can extract files, get subdocument, replace (or add) subdocuments that we want and save that file as .ods file (which is a ZIP file).
.ods
For processing documents, we have used XmlDocument because it offers an easy way to reach parts that we want. Note that, if performance is crucial for you, you should use XmlTextReader and XmlTextWriter. That solution needs more work (and code), but provides better performance.
XmlDocument
XmlTextReader
XmlTextWriter
To read a document, we follow these steps:
XmlDocument
DataSet
table:table
DataTables
Although ODF specification provides a way to specify default row, column and cell style, implementations have nasty practice (that specially apply are equal to the number of columns), although you only have to write data to the first few rows/columns.
ODF specification provides a way that you specify some element (like column/row/cell) and then you specify the number of times it repeats. So the above behavior doesn't affect the size of the file, but that complicates our implementation.
Because of that, we can't just read the number of columns and add an.
DataColumns
DataTable
To write a document, we follow these steps:
In this application, as template, we have to use an empty document. But the application can be easily modified to use some other template (so that you have preserved styles, etc.).
You can download the latest version of the demo application (together with the C# source code) from here..
OpenDocument
As another option, you could use some third party Excel C# / VB.NET component which has support for ODF format. This will probably cost you some money but has an advantage that usually more than one format (for example: GemBox.Spreadsheet reads/writes XLS, XLSX, CSV, HTML and ODS) is supported within the same API, so your application will be able to target different file formats using the same code.
GemBox.Spreadsheet.
|
http://www.codeproject.com/Articles/38425/How-to-Read-and-Write-ODF-ODS-Files-OpenDocument-S?fid=1544287&df=90&mpp=10&noise=1&prof=True&sort=Position&view=Expanded&spc=None&fr=11
|
CC-MAIN-2015-22
|
refinedweb
| 803
| 54.32
|
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: "By default,
csc will output an executable file."
A block of code is set as follows:
using System; namespace program { class MainClass { static void Main (string[] args) { Console.WriteLine("Hello, World"); } } }
Any command-line input or output is written as follows:
PS ~> $env:Path += ";C:\Windows\Microsoft.NET\Framework\v4.0.30319"
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Create a new project by clicking ...
Get C# 5 First Look now with O’Reilly online learning.
O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.
|
https://www.oreilly.com/library/view/c-5-first/9781849686761/pr06s04.html
|
CC-MAIN-2020-16
|
refinedweb
| 155
| 63.9
|
I have IDEA building an exploded war file and deploying it to jetty.
I don't want to include the config file in the war so I am currently configuring Spring like this:
@PropertySource(value="file:${springConfig:etc/testApp/app.properties}")
public class MyConfig {
However, this requires me to copy my app.properties to the jetty folder (jetty/etc/testApp) each time I make a change, which doesn't seem right.
I tried adding the directories and the properties file to the artifact in IDEA (in the root and the web-inf/classes) but Spring can't seem to find it.
What is the best way to do this?
|
https://intellij-support.jetbrains.com/hc/en-us/community/posts/206895385-How-Do-I-Configure-Spring-Properties-With-Jetty-
|
CC-MAIN-2020-34
|
refinedweb
| 109
| 64
|
Welcome to Apache Struts 2 standards and proven design patterns.
Work in progress!
Apache.
Apache Struts 2 in a Nutshell
The framework provides its own web Controller component and integrates with other technologies to provide the Model and the View..
To make it easier to access dynamic data obtained by an Action, the framework includes a library of custom tags. The tags interact with the framework's validation and internationalization features, to ensure that input is correct and output is localized. The tag library can be used with JSP, FreeMarker, or Velocity.
Struts Configuration in a Nutshell
A web application uses a deployment descriptor to initialize resources like servlets and taglibs. The deployment descriptor is formatted as a XML document and named
web.xml. Likewise, the framework uses a configuration file, named
struts.xml, to initialize its own resources. These resources include action mappings, to direct input to server-side Action classes, and result types, to select output pages.
Here's a simple configuration (
struts.xml) for a login workflow:
<struts> <include file="struts-default.xml"/> <package name="default" namespace="/">.
Getting Started
The documentation is grouped into three areas.
An overview of all three areas is available.
|
https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=14419
|
CC-MAIN-2018-34
|
refinedweb
| 197
| 51.14
|
Analyzing a NHL Playoff Game With Twitter
Since its inception eight years ago Jack Dorsey's Twitter has grown into one of the most popular websites on the internet. With over a billion registered users and an average of five hundred million tweets sent per day Twitter is creating incredible amounts of data. Many novel ideas have come out of the question of what to do with all of this data, from predicting stocks to more recently predicting crime.
When I was first learning python one of the first libraries I came across was Tweepy, an open source, easy to use python library for accessing the Twitter API. There are three different ways to get access to Twitters enormous amounts of data. First is Twitters search API which allows you to gather tweets which were made in the past. You can collect tweets based on user, keywords, locations, its basically the same as when you are searching for tweets on Twitters website except you are limited to how much you can collect. Twitters streaming API allows you to compile tweets as they are happening in real time. You can use the same type parameters as you can with the search API looking for tweets based on keywords or even geographic locations. The disadvantage of the streaming API is that you are not collecting all of the Tweets that are being sent in real time only a sample of ~1% of the current traffic. The only way to get the full stream of all tweets being sent that match your criteria is the Twitter Firehose. The only way to get access to the Firehose is to go through a third party such as Datasift or the recently acquired by twitter, GNIP.
Early on when I was experimenting with Tweepy I began thinking of interesting projects that could come out of all this data I had the the potential of collecting. One idea that always stuck was the thought of collecting tweets during sports games and seeing what could be done with the resulting data. Being a Philadelphia Flyers fan I chose to use Twitters streaming API to collect tweets sent during their last playoff game against the New York Rangers (SPOILER ALERT: they lost).
The following code takes all tweets with the keyword 'flyers' and sends the time it was created, text of the tweet, location (if available), and the source of the tweet to a local MongoDB database. I have removed my consumer and secret keys, you can obtain your own by creating an app on twitters dev site.
import tweepy import sys import pymongo consumer_key="" consumer_secret="" access_token="" access_token_secret="" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) class CustomStreamListener(tweepy.StreamListener): def __init__(self, api): self.api = api super(tweepy.StreamListener, self).__init__() self.db = pymongo.MongoClient().Flyers def on_status(self, status): print status.text , "\n" data ={} data['text'] = status.text data['created_at'] = status.created_at data['geo'] = status.geo data['source'] = status.source self.db.Tweets.insert(data)(api)) sapi.filter(track=['flyers'])
Once you run the script you will see the tweets appear on the terminal window and the MongoDB begin to fill. I use the Robomongo GUI to keep track of this. I ran the script fifteen minutes prior to the beginning of the game and ended it fifteen minutes after for the sake of consistency. By the end I had collected 35,443 tweets. For a little bit of context I was collecting around 7,000 tweets for regular season Flyers games and was able to gather 640,000 during the Super Bowl.
Once I had all of the data collected I exported a CSV of everything and began looking at it in iPython. The code below creates a pandas dataframe from the CSV file, makes the created_at column into the index and then converts it to a pandas time series. I also converted the time to EST 12 hour format for graph readability.
import pandas as pd from pandas.tseries.resample import TimeGrouper from pandas.tseries.offsets import DateOffset flyers = pd.read_csv('/Users/danielforsyth/Desktop/PHI_NYR_G3.csv') flyers['created_at'] = pd.to_datetime(pd.Series(flyers['created_at'])) flyers.set_index('created_at', drop=False, inplace=True) flyers.index = flyers.index.tz_localize('GMT').tz_convert('EST') flyers.index = flyers.index - DateOffset(hours = 12) flyers.index
Next I took a quick look at everything using the head and desrcibe methods built into pandas.
flyers.head()
flyers.describe()
Now it was time to get the data ready to graph. One quick line and the created_at timeseries is in a per minute minute format.
flyers1m = flyers['created_at'].resample('1t', how='count') flyers1m.head()
You can also quickly find the average amount of tweets per minute. Which in this case was 187.
avg = flyers1m.mean()
Now that I had all of the data formatted properly I imported Vincent and created a graph.
import vincent vincent.core.initialize_notebook() area = vincent.Area(flyers1m) area.colors(brew='Spectral') area.display()
As you can see because the search term used here was 'flyers' the results are very biased towards them. The two highest peaks in tweet volume are during the first Flyers goal (700 tweets per minute) and the final Rangers goal by ex-Flyer Dan Carcillo (938 tweets per minute), who doesn't have an exceptionally great reputation. There are also two large peaks at the beginning and end of the game.
After I had graphed all of the data I turned to looking at the actual tweets themself. For this process I used NLTK which is a natural language processing library for python. The first steps were to import NLTK, create a list of all the text from the tweets and then create a new list after filtering out all of the stop words (high frequency words that are irrelevant i.e. to, the, also).
import nltk from nltk.corpus import stopwords from nltk import FreqDist stop = stopwords.words('english') text = flyers['text'] tokens = [] for txt in text.values: tokens.extend([t.lower().strip(":,.") for t in txt.split()]) filtered_tokens = [w for w in tokens if not w in stop]
After we have a list of filtered words we are able to look at the frequency ditribution of the words. Below are the 50 most used words and a frequency plot of the 25 most used words.
freq_dist = nltk.FreqDist(filtered_tokens) freq_dist
freq_dist.keys()[:50]
freq_dist.plot(25)
Next I took a look at the source data that was collected with each tweet. Below are the top fifteen sources, as you can see iPhone users dominate the sample with four times as many tweets as both android and web users.
flyers.source.value_counts()
The last piece of data I had to look at was the location. Since having location data attatched with your tweets is optional not every tweet includes this information. Out of the 35,443 tweets I had collected only 1,609 had location data. Below is a map of all the tweets I created using Folium
You can see almost all of the tweets are concentrated in the Philadelphia area but there are also some areas in both Florida and California with some pretty heavy tweeting.
In the future I would like to try putting scripts on EC2 instances and pushing all of the tweets to something like Heroku to automate the process and keep from having everything local. I would also like to try searching for the opposing team simultaneously to see how the results differ from one another. Implementing some D3 visualizations is also somthing I would like to try as well as building a real time web application to watch the data come in as the game is being played.
This was a very interesting project with some pretty cool results especially considering I was only using around one percent of all the tweets being sent during the game. If you have any questions, feedback, advice, or corrections please get in touch with me on Twitter or email me at danforsyth1@gmail.com.
|
https://www.danielforsyth.me/analyzing-a-nhl-playoff-game-with-twitter/
|
CC-MAIN-2022-05
|
refinedweb
| 1,336
| 63.59
|
#include <vil_image_view.h>
Inheritance diagram for vil_image_view< T >:
Views nplanes() planes of data each of size ni() x nj(). The (i,j) element of the p'th plane is given by im.top_left_ptr()[i*im.istep() + j*im.jstep() + p*im.planestep] The actual image data is either allocated by the class (using set_size), in which case it is deleted only when it has no views observing it, or is allocated outside (and is not deleted on destruction). This allows external images to be accessed without a deep copy.
Note that copying one vil_image_view<T> to another takes a shallow copy by default - it copies the view, not the raw image data. Use the explicit deep_copy() call to take a deep copy.
Definition at line 40 of file vil_image_view.h.
|
http://public.kitware.com/vxl/doc/release/core/vil/html/classvil__image__view.html
|
crawl-002
|
refinedweb
| 130
| 62.98
|
Visualizing the Equation for the Eiffel Tower [Code Snippet]
Visualizing the Equation for the Eiffel Tower [Code Snippet]
Look at a visualization of and some code for the equation that helped build the legendary Eiffel Tower.
Join the DZone community and get the full member experience.Join For Free
How to Simplify Apache Kafka. Get eBook.
Robert Banks's book Towing Icebergs, Falling Dominoes, and Other Adventures in Applied Mathematics describes the Eiffel Tower's shape as approximately the logarithmic curve:
...where y* and x0 are chosen to match the tower's dimensions.
Here's a plot of the curve:
And here's the code that produced the plot:
from numpy import log, exp, linspace, vectorize import matplotlib.pyplot as plt # Taken from "Towing Icebergs, Falling Dominoes, # and Other Adventures in Applied Mathematics" # by Robert B. Banks # Constants given in Banks in feet. Convert to meters. feet_to_meter = 0.0254*12 ystar = 201*feet_to_meter x0 = 207*feet_to_meter height = 984*feet_to_meter # Solve for where to cut off curve to match height of the tower. # - ystar log xmin/x0 = height xmin = x0 * exp(-height/ystar) def f(x): if -xmin < x < xmin: return height else: return -ystar*log(abs(x/x0)) curve = vectorize(f) x = linspace(-x0, x0, 400) plt.plot(x, curve(x)) plt.xlim(-2*x0, 2*x0) plt.xlabel("Meters") plt.ylabel("Meters") plt.title("Eiffel Tower") plt.axes().set_aspect(1) plt.savefig("eiffel_tower.svg")
And that's it! }}
|
https://dzone.com/articles/equation-for-the-eiffel-tower
|
CC-MAIN-2018-51
|
refinedweb
| 239
| 58.18
|
start_timeout not found on sysupgrade
Hi, I have just upgraded from 7.0-beta Sep 5 snapshot to Sep 7. During the process, I noticed the following error message: Welcome to the OpenBSD/amd64 7.0 installation program. /autoinstall[2697]: start_timeout: not found Performing non-interactive upgrade. The upgrade process went ok
Run a command on "last day of month"
Hello, I would like to run a command on "the last day of each month". From what I understood reading the crontab(5) manpage, the simplest way would be setting day-of-month to "28-31". But this would mean running the command 4 times for months that have 31 days. Is there a simpler/better way
Re: Using relayd as a reverse proxy for multiple local servers
Hi, In my testings, using « listen on * port https tls » doesn’t work either. What I did is replace the « * » with the IP address where I want relayd to listen to. And as my gateway has several interfaces, I created a relay section for each single interface I wanted relayd to bind to. Regards,
Bugs running 6.9-CURRENT on MacBook Pro Touchbar 2017
Hi, I went back on testing OpenBSD on my MacBookPro14,3. I just installed 6.9-CURRENT and here's a list of non-working stuff. - keyboard and touchpad don't work. I have to use a USB keyboard/mouse. internal keyboard does work in the boot loader. but stops working after the kernel is loaded.
Re: periodic network access failure when accessing nextcloud via relayd
On Thu, Apr 01, 2021 at 01:47:11PM -0600, Ashlen wrote: > On 21/03/31 23:50, Joel Carnat wrote: > > Hello, > > > > I have Nextcloud 21 running with php-7.4, httpd(8) and relayd(8). > > On my laptop, a script regularly runs nextcloudcmd to synchonize the files >
periodic network access failure when accessing nextcloud via relayd
Hello, I have Nextcloud 21 running with php-7.4, httpd(8) and relayd(8). On my laptop, a script regularly runs nextcloudcmd to synchonize the files with the nextcloud instance. And quite often, nextcloudcmd returns such error: 03-31 23:28:56:089 [ info nextcloud.sync.networkjob.lscol ]:
Huawei E3372 loops detaching
Hi, I got a Huawei E3372 LTE USB Stick and plugged it on my T460s running OpenBSD 6.8-stable/amd64. I tried all 3 USB ports and they all act the same way : the stick loops attaching/detaching forever. I also tried current (OpenBSD 6.8-current (GENERIC.MP) #308: Wed Feb 3 20:49:28 MST 2021)
Re: Issues with Teclast F7 Plus
On Fri, 2020-12-25 at 00:34 -0500, James Hastings wrote: > On 13 Dec 2020, 13:27:48 +0000, Joel Carnat wrote: > > Hello, > > > > I just got a Teclast F7 Plus laptop and installed OpenBSD 6.8- > > current on > > it. Most things works except apm and touchpad &g
Issues with Teclast F7 Plus
Hello, I just got a Teclast F7 Plus laptop and installed OpenBSD 6.8-current on it. Most things works except apm and touchpad. Using zzz or ZZZ, it seems suspend/hibernation start but are never achieved. The backlight keyboard and power led are still on. On Linux, keyboard goes black and
dhcpd and pf table with fixed-address
Hello, I have linked dhcpd(8) and pf(4) using -A, -C and -L dhcpd flags. It seems dhcpd only adds IP for dynamic leases and not for leases configured using fixed-address. Is this expected or is there something I misconfigured? Thanks, Jo PS: configuration extracts rc.conf.local:
Re: Issues with TP-Link UE300
Mbits/sec sender [ 5] 0.00-10.13 sec 618 MBytes 512 Mbits/sec receiver Thank you very much. On Mon, Sep 28, 2020 at 10:30:16AM +0800, Kevin Lo wrote: > On Sun, Sep 27, 2020 at 11:43:13PM +0200, Joel Carnat wrote: > > > > Hi, > > > > I have p
Re: Issues with TP-Link UE300
-Original Message- > From: owner-m...@openbsd.org On Behalf Of Joel Carnat > Sent: 27 September 2020 22:43 > To: misc@openbsd.org > Subject: Issues with TP-Link UE300 > > Hi, > > I have plugged a TP-Link UE300 on my ThinkPad X260 running OpenBSD -snapshot >
Issues with TP-Link UE300
Hi, I have plugged a TP-Link UE300 on my ThinkPad X260 running OpenBSD -snapshot and it seems I can't get more than 100Mbps. The dongle attaches and get an IP address. But the speed seems limited. Same behaviour when attached to the USB3 port of my APU4D4 (running 6.7). When plugged in a MacBook
Re: match two conditions in relayd(8)
On Mon, Jan 27, 2020 at 09:22:40PM +0100, Sebastian Benoit wrote: > Joel Carnat(j...@carnat.net) on 2020.01.27 18:21:43 +0100: > > Hi, > > > > I'm setting up an HTTP(S) Reverse Proxy with relayd(8). > > > > I have one listener with multiple FQDN allowed.
match two conditions in relayd(8)
Hi, I'm setting up an HTTP(S) Reverse Proxy with relayd(8). I have one listener with multiple FQDN allowed. But I also have a common path that must be treated separately. As for now, I have: http protocol "https" { match request header "Host" value "one.domain.local" forward to match
snmpd(8) custom OID names
Hello, I have set custom OIDs in my snmpd.conf(5). When I walk or get those values, using snmp(1) or snmpget(1), the "name" parameters is not listed. I only get values described as OPENBSD-BASE-MIB::localTest.* Is there a straight way to get the configured names from snmp clients? Or do I have
How to specify "device" option in vm.conf to always boot PXE
Hi, I need a VM to always boot from the network. I could do it using vmctl(8): # doas vmctl start test -c -B net -b /bsd -n vswitch0 (...) PXE boot MAC address fe:e1:bb:d1:c5:d8, interface vio0 nfs_boot: using interface vio0, with revarp & bootparams But I can't find the syntax to be used in
Re: relayd shows ssh sessions as idle
On Mon, Jun 17, 2019 at 11:56:08PM +0200, Sebastian Benoit wrote: > Joel Carnat(j...@carnat.net) on 2019.06.12 16:10:25 +0200: > > Hi, > > > > I have configured relayd(8) on my vmd(8) host so that I can connect to > > the running VMs using SSH. > > > >
relayd shows ssh sessions as idle
Hi, I have configured relayd(8) on my vmd(8) host so that I can connect to the running VMs using SSH. Using relayctl(8), I can see that those sessions have the same value for age and idle ; even when something happens in the SSH sessions. Is this expected or an error in my relayd.conf ?
Re: productivity/khard (or python) seem slow
On Sat 18/05 19:15, Strahil wrote: > I run vanilla openBSD 6.5 on oVirt (KVM) with gluster as storage and it seems > OK for my needs but I never used khard. > What kind of slowness do you experience? > Maybe I can run some tests and see if the situation is the same on KVM. > Well, it takes
Re: productivity/khard (or python) seem slow
On Sat 18/05 11:39, David Mimms wrote: > On 2019.05.17 11:41, Paco Esteban wrote: > > On Thu, 16 May 2019, Joel Carnat wrote: > > > > > On Thu 16/05 08:55, Paco Esteban wrote: > > > > Can't say about your VM. On my desktop: > > > > > >
Re: productivity/khard (or python) seem slow
On Thu 16/05 08:55, Paco Esteban wrote: > Hi Joel, > > On Wed, 15 May 2019, Joel Carnat wrote: > > > Hello, > > > > I've just setup vdirsync and khard to sync my addressbook from > > nextcloud. It works but querying the local vcf is damm slow. I also >
productivity/khard (or python) seem slow
Hello, I've just setup vdirsync and khard to sync my addressbook from nextcloud. It works but querying the local vcf is damm slow. I also noticed that ranger felt a bit slow to start but thought it was the software ; so I switched to nnn. # time (khard list | wc -l) 112 0m07.10s real
Re: Running php cli when php-fpm uses chroot
On Fri 12/04 15:37, Éric Jacquot wrote: > Hi, > > Le Friday 12 April 2019 à 11:53 +0200, Joel Carnat a écrit : > > Hi, > > > > Is there a better way to handle chroot environnement when running php > > scripts from the cli? > > > > According to
Running php cli when php-fpm uses chroot
Hi, When php-fpm is configured to use chroot, it seems the php(1) cli still tries to work unchrooted. So when running maintenance php scripts (like occ from Nextcloud), errors raises for not finding resources (like mysql socket etc). I couldn't find a option for the php(1) command to "run as
Re: influxdb goes "panic:runtime error: index out of range"
On Mon 08/04 09:00, Daniel Jakots wrote: > On Mon, 8 Apr 2019 13:58:27 +0200, Joel Carnat wrote: > > > On a fresh influxdb instance in an OpenBSD VM: same issue. On a > > fresh influxdb instance in a Linux Ubuntu VM: the error disappears and > > the query gets the corre
influxdb goes "panic:runtime error: index out of range"
Hi, On InfluxDB, I'm getting "panic:runtime error: index out of range" every time I run the "SHOW TAG VALUES FROM unbound WITH KEY = clientip WHERE sysName =~ /$hostname/" query from Grafana. And I also get it using the influx shell. I've tried various things, like giving more resources (via
Re: Touchpad - how to enable two-finger scrolling
Hi, On Sun 31/03 03:56, Brogan wrote: > Hello, > > I recently installed OpenBSD 6.4 on a Dell Latitude 6430u and am trying to > get touchpad two-finger scrolling working in X11. As far as I can tell the > touchpad is being loaded via wsmouse but I'm not sure how or where to > properly
Broadcom BCM4356, bwfm0: could not read io type
Hi, I took my working 6.5-BETA disk out of a ThinkPad X230i and pluggued it in a ThinkPad X260. The system boots ok and I can get an X session. But the wireless card doesn't seem to work. # dmesg bwfm0 at pci2 dev 0 function 0 "Broadcom BCM4356" rev 0x02: msi bwfm_pci_intr: handle MB data
Re: FDE with keydrive imponderabilities
Hi, I wonder if you’re not using fdisk for an MBR setup and disklabel for GPT. Why won’t you use 64 as the starting offset of the RAID partition ? -- Envoyé de mon iPhone > Le 22 mars 2019 à 23:26, Normen Wohner a écrit : > > I thought you might be able to help me with a setup concerning >
Re: How to monitor class usage/limits?
On Fri 15/03 15:47, Stuart Henderson wrote: > On 2019-03-14, Joel Carnat wrote: > > Hi, > > > > The Internet is full of "OpenBSD desktop works better when rising > > datasize/maxproc/openfiles/stacksize in login.conf". One thing I can't > > manage
How to monitor class usage/limits?
Hi, The Internet is full of "OpenBSD desktop works better when rising datasize/maxproc/openfiles/stacksize in login.conf". One thing I can't manage to find is how you can monitor those values? I'm Ok to set arbitrary recommended values depending on system configuration and general usecases (like
Are there real mountpoints for gvfs/gio shares ?
Hi, I was looking at mounting CIFS shares. OpenBSD is the "client" machine. CIFS a published by a remote NAS. Using XFCE and Thunar, everything works well. But when I try to access the mountpoints from the console, I just can't find them. Things like "gio mount smb://", "gio mount -l" and
Re: ldap search fails with Let's Encrypt certificate
Le 05/11/2018 17:07, Stuart Henderson a écrit : On 2018/11/05 17:02, Joel Carnat wrote: Le 05/11/2018 16:38, Stuart Henderson a écrit : > On 2018-11-05, Joel Carnat wrote: > > Le 05/11/2018 13:48, Stuart Henderson a écrit : > > > On 2018-11-05, Joel Carnat
Re: ldap search fails with Let's Encrypt certificate
Le 05/11/2018 16:38, Stuart Henderson a écrit : On 2018-11-05, Joel Carnat wrote:
Re: ldap search fails with Let's Encrypt certificate failed: handshake failed: error:14004410:SSL routines:CONNECT_CR_SRVR_HELLO:sslv3
ldap search fails with Let's Encrypt certificate
Hi, I'm using ldap(1) to query a remote Synology Directory Server (OpenLDAP 2.4.x). Unfortunately, it fails saying: TLS failed: handshake failed: error:14004410:SSL routines:CONNECT_CR_SRVR_HELLO:sslv3 alert handshake failure ldap: LDAP connection failed When I use the OpenLDAP
Inconsistent stats between snmpd(8) and pfctl(8) ?
Hi, On OpenBSD 6.3/amd64, I'm using snmpd(8) to gather pf(4) statistics. It seems that some stats are not coherent. For example, on egress and vio0 interfaces. Asking snmpd(8), I get : OPENBSD-PF-MIB::pfIfDescr.3 = STRING: "egress" OPENBSD-PF-MIB::pfIfDescr.12 = STRING: "vio0"
Re: net-snmpd extend and doas : a tty is scri
net-snmpd extend and doas : a tty is
Re: OpenBSD as an IKEv2 IPsec client with L/P authent
Hi, Le 22/02/2018 09:35, Stuart Henderson a écrit : On 2018-02-22, Igor V. Gubenko
wrote: I am far from an expert; having issues myself at the moment, but maybe if we get all of the iked experimenters together, we can figure it out :) This definitely isn't going to work,
OpenBSD as an IKEv2 IPsec client with L/P authent
Hi, My FTTH home-box provides IKEv2 server support. I connected my iPhone, via 3G, to it. I can now access my internal home-LAN. So I know it works. I want to do the same with an OpenBSD server hosted in "the Cloud" ; in transport mode as far as I understood the docs. I've struggled with
Re: iPhone tethering ?
The iPhone can be configured as a wireless AP. Then OpenBSD can connect to it and gain access to the Wild Wild World. -- Envoyé de mon iPhone > Le 23 oct. 2017 à 07:58, SFM
a écrit : > > Hi everyone ! > > Does iPhone tethering work with OpenBSD? In other words, is
Re: rsa 4096 or ed25519 for ssh keys ?
Le 16/10/2017 19:46, Mike Coddington a écrit : On Mon, Oct 16, 2017 at 05:29:34PM +0200, Joel Carnat wrote: Hi, If both server and client are ed25519 compatible. When generating (user) SSH keys, is it recommended to use ed25519 rather than rsa 4096bits? AFAIK, either would be fine. I
rsa 4096 or ed25519 for ssh keys ?
Hi, If both server and client are ed25519 compatible. When generating (user) SSH keys, is it recommended to use ed25519 rather than rsa 4096bits? Thank you.
Re: softraid crypto seem really slower than plain ffs
Hello, I was really annoyed by the numbers I got. So I did the testings again. Using a brand new VM. Being really careful on what I was doing and writing it down after each command run. I did the testings using 6.1 and 6.2-current, in case there were some changes. There weren't. First of
softraid crypto seem really slower than plain ffs
Hi, Initially comparing I/O speed between FreeBSD/ZFS/GELI and OpenBSD/FFS/CRYPTO, I noticed that there were a huge difference between plain and encrypted filesystem using OpenBSD. I ran the test on a 1 vCore/1GB RAM Vultr VPS, running OpenBSD 6.2-beta. I had / configured in plain FFS and
i386 or amd64 from small Cloud instance ?
Hi, My Cloud instances are always small (1 ou 2 vCPU, far less than 4GB of RAM). From what I saw, all the ports I need are available in i386 and amd64. Every Cloud provider I checked are using KVM hypervisor. Regarding OS and ports performance, does it make sense to use i386 rather than
OpenBSD on XPS M1330, sound and HTML video issues
Hi, I have installed OpenBSD 5.7/amd64 on my "old" Dell XPS M1330. Everything seem right except sound, only working with headphones and not internal speakers, and HTML5 videos, being very choppy (things like YouTube videos). I've read about those issues but couldn't solve them from what I
Re: Windows Server on Qemu
Le 13 août 2015 à 08:41, Mike Larkin mlar...@azathoth.net a écrit : On Wed, Aug 12, 2015 at 06:40:33PM -0700, Mike Larkin wrote: On Wed, Aug 12, 2015 at 10:00:49PM +0200, Joel Carnat wrote: Hi, Anyone here succeeded in having Windows Server 2008/2008R2/2012/2012R2 run in qemu-2.2.0
Windows Server on Qemu
Hi, Anyone here succeeded in having Windows Server 2008/2008R2/2012/2012R2 run in qemu-2.2.0 (OpenBSD 5.7/amd64) ? Mine keeps going BSOD on installation. Most of documentation I found was Linux-centric so I may miss some OpenBSD trick. TIA, Jo
Which tools to monitor traffic and alert ?
Hi, I run several standard services (Web, Mail, DNS, …) and have configured Munin to graph traffic and see what happened. I was wondering what was the usual OpenBSD way for proactive/real-time traffic monitoring and alerting. That is, which software to use that would, for example, read HTTPD
Re: sogo, httpd(8) and the rewrite need
Le 15 juin 2015 à 01:16, Reyk Floeter r...@openbsd.org a écrit : On 14.06.2015, at 18:08, Joel Carnat j...@carnat.net wrote: Hi, I was going to install SOGo on OpenBSD 5.7 using the native httpd(8). In the readme, there are configuration examples for nginx and apache-httpd-openbsd
sogo, httpd(8) and the rewrite need
Hi, I was going to install SOGo on OpenBSD 5.7 using the native httpd(8). In the readme, there are configuration examples for nginx and apache-httpd-openbsd. Nothing for the new httpd. There are rewrite/redirect features that I can’t figure out how to setup with httpd(8). nginx example:
index.php not loading on obsd 5.6
Hi, I just installed 5.6 amd64 on a virtual machine. I installed php-fpm-5.5.14 and launched the daemon. I configured httpd as such : # egrep -v '^$|^#' /etc/httpd.conf ext_addr=egress server default { listen on $ext_addr port 80
Native ldapd and ldappasswd
Hi, I am configuring native ldapd (OBSD 5.4) for users authentication. But it seems I can't use ldappasswd to modify a userPassword. Here's how the object is configured: # ldapsearch -H ldap://localhost -D cn=admin,dc=local -w vierge -b dc=local cn=email (...) # email, users, local dn:
Generate hashed rootpw for native ldapd
Hi, I want to generate a hashed rootpw for native ldapd (on OBSD 5.4). I've tried various things like `echo secret | sha256` but I can't authenticate. If possible, I'd like not to install openldap-server just to get slappasswd. What is the (native) way to generate the SSHA hashed format for
Re: Generate hashed rootpw for native ldapd
-base64 | awk '{print {SHA}$0}' {SHA}ZLvhLmLU88dUQwzfUgsq6IV8ZRE= # slappasswd -h {SHA} -s passphrase {SHA}YhAnRDQFLyD8uD4dD0kiBPyxGIQ= Using the string generated with slappasswd works. Other two don't :( Le 21 févr. 2014 à 13:18, Marcus MERIGHI mcmer-open...@tor.at a écrit : j...@carnat.net (Joel
Re: Generate hashed rootpw for native ldapd
21, 2014 at 6:31 AM, Joel Carnat j...@carnat.net wrote: Hum, I tried it but it doesn't work. I have a slappasswd else where to test. And here's what I get : # print passphrase | openssl dgst -sha1 -binary | openssl enc -base64 | awk '{print {SHA}$0}' {SHA}ZLvhLmLU88dUQwzfUgsq6IV8ZRE= # echo
snmpd, oid and scripts
Hi, I wanted to get rid of net-snmp and use the shipped snmpd(8). I have OpenBSD boxes running various services (DNS, Web, Mail...) and have scripts providing service stats using the extend/exec net-snmp feature. I read about the oid feature of snmpd(8) but it seems it can only publish fixed
Re: ldapd and The Diffie Hellman prime sent by the server is not acceptable
: ... = Hope that sheds some light on this problem.. P.S. I CC'ed ldapd developers in order to have some hope this might be fixed one day.. --- thanks, VA On 2011-01-21 19:21, Joel Carnat wrote: Hello, On a Ubuntu Linux 8.04 machine, I can't query my OpenBSD 4.9
Re: ldapd and The Diffie Hellman prime sent by the server is not acceptable
Built on source tree from 5.2: it works! Gotta switch back to SSL :)) Thank you. Jo Le 28 janv. 2013 à 12:31, Gilles Chehade gil...@poolp.org a écrit : On Mon, Jan 28, 2013 at 12:28:58PM +0100, Joel Carnat wrote: Hi, I wasn't aware of any diffs. With time, the OpenBSD (ldapd
Replication option for ldapd(8)
Hello, I want to achieve a Master / Slave replication with OpenBSD's shipped ldapd(8). Are there any native features to synchronize both instances (like openldap's syncrepl) or do I have to script a bunch of (ldapsearch/ldapadd)|scp ? TIA, Jo
Re: The ultimate OpenBSD email server
Le 19 août 2012 à 14:15, Stuart Henderson a écrit : On 2012-08-16, Joel Carnat j...@carnat.net wrote: - roundcube and suhosin don't play well together ; there is no general problem with roundcube and suhosin playing together, you just have to follow the documentation about disabling session
Re: The ultimate OpenBSD email server
Le 15 août 2012 à 16:16, L. V. Lammert a écrit : On Wed, 15 Aug 2012, Mikkel Bang wrote: But with so many people recommending so many different tools, it gets hard to come to a conclusion. Looks like I'm finally arriving at this though: postfix (postfix-anti-UCE.txt) + dspam - what do you
About `ldapctl stats` metrics
Hi, I've setup some RRDtool magic to graph ldapd(8) metrics (OpenBSD 5.1/i386). Using `ldapctl stats`, I was expecting: requests = search requests + bind requests + modify requests But after a few ldapsearch/ldapadd/ldapdelete testings, it seems requests grows faster than the sum of * requests.
Re: Q: username policy in install and in adduser
AFAIK, there is every likelihood that a third-party software (like Web or Mail server) will not be case-sensitive and will mix data for Foo and foO users. Le 13 août 2012 à 15:20, Eike Lantzsch a écrit : The choice of usernames during OBSD install is more restrictive than adduser. For example
Re: kvm and Openbsd 5.1
Hi, Le 20 juil. 2012 à 19:29, Alessandro Baggi a écrit : Hi list, today I've installed OpenBSD 5.1 amd64 on a kvm (linux slackware) kvm version is 1.0.1. Starting machine with 4 core, and bsd.mp it crash. Disabling mpbios see only one core and not smp. Then, I've updated kvm to 1.1.1 but
smtpd, virtual users/domains and maildir creation
Hi, I am playing with OpenSMTPD and am configuring a virtual domains and users configuration. In smtpd.conf.local, I have set: map vdomains { source db /etc/mail/vdomains.db } accept for virtual vdomains deliver to maildir /home/vmail/%d/%a/ In /etc/mail/vdomains, I have set: tumfatig.net:
Re: smtpd, virtual users/domains and maildir creation
Le 15 juin 2012 à 17:03, Gilles Chehade a écrit : On Fri, Jun 15, 2012 at 03:28:42PM +0200, Joel Carnat wrote: Hi, Hi, I am playing with OpenSMTPD and am configuring a virtual domains and users configuration. In smtpd.conf.local, I have set: map vdomains { source db /etc/mail
Re: smtpd, virtual users/domains and maildir creation
Le 15 juin 2012 à 17:37, Gilles Chehade a écrit : snip What's the proper way to host virtual aliases for virtual domains ? The proper way is the one you're using ;-) Also, one thing you could do is create a fallback address: @carnat.net r...@carnat.net if you want to also catch every
filtering recipients for a secondary mx using smtpd
Hi, Using OpenBSD 5.1, I have configured OpenSMTPD to act as a secondary MX. I have configured this, in smtpd.conf: # secondary mx map v2mx { source db /etc/mail/v2mx.db } accept from all for virtual v2mx relay And this, in /etc/mail/v2mx: hotmail.com accept The smtpd can now relay
PHP issue with native Apache and ProxyPass
Hello, I have an OpenBSD 5.0 server, running the native Apache and providing a local WordPress instance which works great. The Apache also proxyfies simple websites (only HTML/CSS/JS, like xymon, munin, sogo) using the ProxyPass/ProxyPassReverse directives. I wanted to proxyfy another WordPress
Acceleration for Qemu ?
Hi, I was planning on using qemu to run several instances on various OSes on my OpenBSD 5.0/amd64 server. As a first try, I ran an OpenBSD 5.0/i386 instance using qemu-0.14.1p4: # ifconfig tun0 link0 # ifconfig bridge0 add tun0 add bge0 up # qemu -nographic -m 128 -net nic -net tap,ifname=tun0
Re: I don't get where the load comes from
Le 31 mai 2011 ` 00:15, Paul de Weerd a icrit : On Mon, May 30, 2011 at 11:44:29PM +0200, Joel Carnat wrote: | Hi, | | I am running a personal Mail+Web system on a Core2Duo 2GHz using Speedstep. | It is mostly doing nothing but still has a high load average. Wait, what ? ~1 is 'a high load
Re: I don't get where the load comes from
. I don't get how A high load is just that: high. It means you have a lot of processes that sometimes run. can show load variation depending on CPU speed only. El 05/30/11 18:44, Joel Carnat escribis: Hi, I am running a personal Mail+Web system on a Core2Duo 2GHz using Speedstep. It is mostly
Re: I don't get where the load comes from
Le 31 mai 2011 ` 08:10, Tony Abernethy a icrit : Joel Carnat wrote well, compared to my previous box, running NetBSD/xen, the same services and showing about 0.3-0.6 of load ; I thought a load of 1.21 was quite much. Different systems will agree on the spelling of the word load
I don't get where the load comes from
Hi, I am running a personal Mail+Web system on a Core2Duo 2GHz using Speedstep. It is mostly doing nothing but still has a high load average. I've check various stat tools but didn't find the reason for the load. Anyone has ideas? TIA, Jo PS: here are some of the results I checked. #
pid file for ldapd(8)
Hi, Is there a way to tell ldapd(8) to write it's PID in /var/run ? TIA, Jo
ldapd and The Diffie Hellman prime sent by the server is not acceptable
Hello, On a Ubuntu Linux 8.04 machine, I can't query my OpenBSD 4.9 ldapd(8). It works from the local OpenBSD and from a remote NetBSD server. All machines have the CA file installed in the OpenSSL directory and the ldap.conf file configured to use that particular CA file. Here's what I get on
ldapd and namespace access
Greetings, I would like to limit the access to my ldapd content. I've read ldapd.conf(5) but there are bits I don't get. The policy I would like to apply is: (1) allow anyone to authenticate (2) allow read access to all namespace by users that have been authenticated (3) allow write access to
Re: ldapd and self-signed certificate
-Message initial- @: Joel Carnat j...@carnat.net; Cc: Philip Guenther guent...@gmail.com; misc@openbsd.org; De: Martin Hedenfalk mar...@bzero.se Envoyi: lun. 15-11-2010 11:44 Sujet: Re: ldapd and self-signed certificate 15 nov 2010 kl. 00.01 skrev Joel Carnat
Re: ldapd and self-signed certificate
-Message initial- @: Joel Carnat j...@carnat.net; Cc: misc@openbsd.org; De: Philip Guenther guent...@gmail.com Envoyi: dim. 14-11-2010 02:25 Sujet: Re: ldapd and self-signed certificate On Sat, Nov 13, 2010 at 12:02 PM, Joel Carnat j...@carnat.net wrote: I want to use LDAP
ldapd and self-signed certificate
Greetings, I want to use LDAP to store postfix, apache and dovecot users. This sounds a quite simple need so I plan to use the native ldapd. I have installed 4.8 GENERIC.MP#335 amd64 and configured ldapd as follow: # $OpenBSD: ldapd.conf,v 1.2 2010/06/29 02:50:22 martinh Exp $ schema
HTC P3300 not recognised by uipaq
Hello, I read on uipaq(4) that HTC SmartPhone are supported. I plugued my HTC P3300, running Windows Mobile 6, on my Eee PC running 4.4/i386, but it does not attach to uipaq: ugen0 at uhub1 port 2 HTC Generic RNDIS rev 2.00/0.00 addr2 usbdevs says: port 2 addr 2: full speed, power 100mA,
Re: [ landisk ] - install w/o the serial console
, 2008 at 03:43:34PM +0200, Joel CARNAT wrote:
[ landisk ] - install w/o the serial console couldn't find the procedure to manually install
Re: use ifstated to modify pf/rdr
On Wed, May 25 2005 - 12:58, Jason Dixon wrote: On May 25, 2005, at 11:51 AM, Joel CARNAT wrote: I would like to use ifstated (OpenBSD 3.7/i386) in the case (except I'll use SMTP server, not HTTP) to modify the $web_servers macros when one
|
https://www.mail-archive.com/search?l=misc%40openbsd.org&q=from:%22Joel+Carnat%22&o=newest
|
CC-MAIN-2021-39
|
refinedweb
| 4,923
| 72.66
|
If you were following my first three parts of this series, you probably are familiar with basics of threading and how to write simple multithreading applications in .NET using the System.Threading.Thread class and implementing thread synchronization on the .NET platform. In this article, I would discuss few more .NET classes and how and what role do they play a role in building multithreading applications. These classes are:
Using the Thread class to create and manage threads is ideal for situations when the number of threads is small and you want to control the thread details like the thread priority etc. For large number of threads, it is always better to consider thread pooling. It provides an efficient thread management mechanism to handle multiple tasks. The Timer class is a flexible way to run tasks at specified intervals. Async method invocation using delegates are also a preferred threading mechanism
System.Threading.ThreadPool Class
As you start creating your own multi-threaded applications, you would realize that for a large part of your time, your threads are sitting idle waiting for something to happen (like a key press or listening for requests at the socket etc). No doubt, as you would also agree, this is an absolute waste of resources.
If there are a number of tasks, each requiring one thread, then you should consider using the ThreadPool class (in the System.Threading namespace) to manage your resources efficiently and to take benefits of multiple threads. Thread pooling is a form of multithreading where tasks are added to a queue and automatically started as threads are created. Using the ThreadPool class enables the system to optimize thread time-slices on the processor. But remember that at any particular point of time there is only one thread pool per process and there is only one working thread per thread pool object. This class provides your application with a pool of worker threads that are managed by the system thus allowing you to concentrate on the workflow logic rather than thread management.
The thread pool is created the first time when you instantiate the ThreadPool class. It has a default limit of 25 threads per available processor, but that can be changed. Thus, the processor is never made to sit idle. If one of the threads is waiting on an event, the thread pool will initiate another worker thread on the processor. The thread pool continues creating worker threads and allocates tasks which are pending in the queue. The only restriction being that the number of worker threads created will never exceed the maximum number allowed. If you create threads that are in addition to the limit specified, then those threads can start only once the currently running threads stop. The number of operations that can be queued to the thread pool is limited only by the available memory. Each thread runs at the default priority and uses the default stack size and is in the multi-threaded apartment. Once a work item has been queued to the thread pool, you cannot cancel it.
You request the thread pool to handle a task (or work items) by calling the QueueUserWorkItem method of the ThreadPool class. This method adds threads to be executed when the processor is free. This method takes as a parameter a WaitCallback delegate (wrapping the object that you want to add to the queue) that will be called by the thread selected from the thread pool. The runtime automatically creates threads for queued thread pool tasks and then releases them when the task is done.
The following code shows how you can create a thread pool. It is a very simple process. Just create a delegate of type WaitCallback and add it to thread pool.
This mechanism, involving the ThreadPool and an event based programming pattern, facilitates the ThreadPool to monitor all the WaitHandles registered with it and then calling the appropriate WaitOrTimerCallback delegate method when the WaitHandle is released. The modus operandi of this is very simple. There is one thread that constantly observes the status of the wait operations queued to the thread pool. When the wait operation completes, a worker thread from the pool executes the corresponding callback function. Thus, this method adds a new thread with a triggering event.
Let us see how we can add a new thread with an event to the thread pool. Doing this is very simple. We need to create an event, which we will do with the ManualResetEvent class. We next need to create a WaitOrTimerCallback delegate. Then we need an object that will carry the status info to the delegate. We have also to determine timeout interval and the execution style. We will add all of them to the thread pool and set the event on fire.
The unsafe methods ThreadPool.UnsafeRegisterWaitForSingleObject and ThreadPool.UnsafeQueueUserWorkItem can be used instead.
You can also queue work items that are not related to a wait operation to the thread pool. Timer-queue timers and registered wait operations also use the thread pool. Their callback functions are queued to the thread pool.
Thread pooling is a very useful concept and is widely used in the .Net platform to make socket connections, registered wait operations, process timers or in asynchronous I/O completion. For small and short tasks, the thread pooling mechanism is a convenient way to handle multiple threads. This concept is beneficial when you want to start many separate tasks without individually setting the properties of each thread.
But, you should also remember that there are some situations where it is suitable to create and manage your own threads instead of using the ThreadPool class. Cases where you would want to schedule a task (give a particular priority level to a thread) or give a thread a particular identity (like a name to the thread) or if you feel the need to place the threads in a single-threaded apartment (ThreadPool places the threads in a multithreaded apartment) or if you know that a particular task is lengthy (hence chances that it might block other threads is high), you might feel safe in creating your own threads rather than using threads from the thread pool. pass a null reference here. We will then instantiate a Timer object (where we pass the delegate, state object and two more parameters that define the dueTime and period of the Timer). We will use the Change method to change the Timer object settings. Finally, we will kill the Timer object by calling the Dispose method.
Asynchronous Programming
This is a topic in itself and needs detailed explanation. Here, we would just get some familiarity as to what it is because it would not do justice to the multi-threading concepts by ignoring this topic, as asynchronous programming is another way of introducing threads in your application.
We have so far studied what synchronous calls are and how they are invoked. But, these suffer an intrinsic shortcoming, which you might have also noticed. The thread that makes a synchronous call is blocked and has to wait until the function completes. Of course, in some situations this is adequate as in the case where your program's logic is dependent on whatever the thread is doing (say reading the values from the database without which the program cannot proceed).
Asynchronous programming allows more flexibility. A thread that makes an asynchronous call is not blocked on that call. You can use the thread to do almost any task and when the call completes, the thread picks up the results and proceeds. This concept gives a better scalability to an enterprise wide system where the threads might have to manage numerous call requests and hence cannot afford to wait on each request.
The .NET platform provides a consistent support for asynchronous programming and this aspect is used in ASP.NET web forms, I/O operations, Web Services, networking, messaging etc. One of the main design patterns that have made asynchronous programming possible is the .NET delegate classes.
Asynchronous delegates
Asynchronous delegates provide the facility to call a synchronous method in an asynchronous manner. In case of a synchronous call, the compiler calls the invoke method that directly calls the target method on the current thread. In case of asynchronous call, rather than calling the target method directly, the compiler creates the type-safe methods BeginInvoke and EndInvoke. The moment the BeginInvoke is called, CLR will queue the request and return to the caller instantly. The target method would be called on a thread from the thread pool. The original thread that had submitted the request is thus free to carry out any other activities. If you specify a callback on the BeginInvoke method then the target method calls it, when it returns. In the callback, the EndInvoke method is used to obtain the results. If you do not specify a callback on the BeginInvoke, then you have to use the EndInvoke method on the thread that had submitted the request.
We have already studied the ThreadPool and ReaderWriterLock classes. The Common Language Runtime supports asynchronous programming model via these classes. The synchronization constructs like the WaitForMultipleObjects method also support the asynchronous programming feature. As a developer, you will have to evaluate the merits and demerits of the synchronous calls to those of the asynchronous types. Synchronous calls are easy to code and offer complete safety with the help of the different synchronization objects available. Asynchronous calls are a must in a large-scale applications to reduce the number and complexity of threads but are mainly implemented through polling. Polling is not a very proficient way of administering threads as it unnecessary consumes a lot of resources by continually checking the status of an asynchronous call from within a loop.
Conclusion This brings us to an end on the multithreading concepts. It is a vast topic and you need to create your own web of threads to understand it. Just remember that although performance level is boosted by creating multiple threads, yet thread creation is an expensive proposition in terms of the memory required and CPU time consumed to keep them running. Stay away from creating too many useless threads and assigning incorrect priorities to them.
©2015
C# Corner. All contents are copyright of their authors.
|
http://www.c-sharpcorner.com/UploadFile/mmehta/Multithreading411162005051609AM/Multithreading4.aspx
|
CC-MAIN-2015-22
|
refinedweb
| 1,716
| 62.58
|
Matthew, If you are using InstallMgr, then there is a facility for this in the virtual method getCipherCode. The relevant example from our BibleCS code is bool InstallMgrWin::getCipherCode(const char *modName, SWConfig *config) { CipherForm->modName = modName; CipherForm->config = config; return (CipherForm->ShowModal() == mrCancel); } Where CipherForm is a popup dialog which asks the user for a cipher key, let's them test it by grabbing an entry from the module with that key (if it's the correct key, they will see module text, otherwise gibberish), and then let's them accept or cancel. If this does not fit for you, and if you wish to modify the conf file after the module is already installed, there is example code in SWMgr.h (the end of the file) to show how to do this, but it is old and only takes into account the primary module path which was discovered at startup (this path is saved at SWMgr::configPath). It will not work for modules found on AugmentPath entries (including the automatic AugmentPath $HOME/.sword, unless $HOME/.sword is found as the primary module path (i.e., no other module paths were found)). If all of your modules are discovered in the same place, then it will work. We add "AbsoluteDataPath" as a config entry when we load the configuration of modules to help with things similar to this, so you can do: module->getConfigEntry("AbsoluteDataPath"); to tell you where the module data lives. Though this will not officially help you find the config, it should be at {AbsoluteDataPath}/../../../../mods.d/ We should make this easier for you and provide an 'official' way to do this which works with our expanded definition of where modules can be installed to. An alternative to modifying the distributed .conf file is to have your own 'stand off' per module config modifiers. We do this in BibleCS with a file like: userprefs.conf: [KJV] font=somefont [WLC] font=somehebrewfront fontsize=24 Then in code we provide a virtual SWMgr::Load method like: signed char BibleCSMGR::Load () { signed char retval = SWMgr::Load(); userPrefs = new SWConfig("./userprefs.conf"); if ((config) && (userPrefs)) config->augment(*userPrefs); return retval; }; SWMgr::config is the globbed configuration of all modules. The augment method on SWConfig (or the += operator) will add to or update config entries accordingly. This allows you to get your user preference per module entries like any other entry in the distributed .conf file: module->getConfigEntry("About"); module->getConfigEntry("font"); The downside is that the CipherKey entry is needed at module load time (base class version of SWMgr::Load) to know which low level decipher filters to add for that module, so this will not help for your current problem. So, anyway, this is all more information than you probably care to know. Hope it helps some. Troy On 05/22/2010 05:06 PM, Matthew Talbert wrote: > I > > _______________________________________________ > sword-devel mailing list: sword-devel at crosswire.org > > Instructions to unsubscribe/change your settings at above page >
|
http://www.crosswire.org/pipermail/sword-devel/2010-May/034329.html
|
CC-MAIN-2014-52
|
refinedweb
| 499
| 52.09
|
Encoding and decoding SQLite in Swift
This is the third post in a series about powering modern apps with SQLite. The other posts in this series are:
- Powering modern apps with SQLite
- Building a lightweight SQLite wrapper in Swift
- Reacting to changes to data in the SQLite database
One of the best changes to Swift so far was the addition of the
Codable protocol to the Swift standard library. This protocol, which combines the underlying
Encodable and
Decodable protocols, defines a standardized approach to encoding and decoding data. Explaining the ins and outs of Swift’s
Encodable and
Decodable protocols is out of the scope of this post, but Apple’s documentation is quite good, and there are plenty of in-depth guides on the Web.
The ultimate benefit of Swift’s
Codable implementation is that we developers can write a model type made up of simple types, declare its conformance to
Codable, and the compiler will generate all of the code needed to support decoding it to and encoding it from
Data.
struct Task: Codable, Equatable { var title: String var dueDate: Date? var isCompleted: Bool }
Then, all we need to do to encode it to JSON and decode it back to a
Task is to instantiate and use instances of
JSONEncoder and
JSONDecoder.
let jsonEncoder = JSONEncoder() let jsonDecoder = JSONDecoder() let id = UUID().uuidString let tomorrow = Date(timeIntervalSinceNow: 86400) let task = Task(id: id, title: "Buy milk", dueDate: tomorrow, isCompleted: false) // wrap these calls in do-catch blocks in real apps let json = try! jsonEncoder.encode(task) let taskFromJSON = try! jsonDecoder.decode(Task.self, from: json)
The Swift standard library includes support for encoding data to and decoding data from JSON and property lists. As this blog series is all about powering modern apps with SQLite, it would be great if we could replace the
JSONEcoder and
JSONDecoder in the previous example with a SQLite encoder and decoder.
Encoding to and decoding from SQLite
There are many potential ways to encode model types to and decode them from SQLite. Perhaps the easiest approach would be to use a SQLite table with a single BLOB column to store encoded JSON. Taking this approach would sacrifice most of the power of SQLite, however, because, among other reasons, we’d lose the ability to create indexes on specific columns to increase the speed of specific queries. (We could regain some of the advantages of using SQLite if, instead of saving the JSON as ‘Data’, we saved it as text and then used SQLite’s JSON extension to access and modify it.)
Alternately, we could write an encoder/decoder that uses introspection to create tables based on properties of our specific model types (i.e., for the example above, the encoder would create a table called “Task” that includes three columns: title, dueDate, and isCompleted with the correct types). The convenience of this approach, in my opinion, is outweighed by the incredible amount of work it would require, especially if we wanted to support anything besides a straightforward translation from a simple model type to a database table. If this sort of thing sounds appealing, consider using Core Data or Realm.
I prefer to take a middle approach in which the developer is responsible for creating the tables for the model types and for writing the SQL to update and fetch the model types from the database, but the SQLite encoder is responsible for
converting the model types to a form that SQLite understands. The SQLite decoder is then responsible for taking the SQLite data types and converting them into our model types. In practice, this approach requires us to write a bit more code than is required to just add conformance to the
Codable protocol, but the difference is very small.
struct Task: Codable, Equatable { var title: String var dueDate: Date? var isCompleted: Bool } extension Task { static var createTable: SQL { return "CREATE TABLE tasks (title TEXT NOT NULL, dueDate TEXT, isCompleted INTEGER NOT NULL);" } static var upsert: SQL { return "INSERT OR REPLACE INTO tasks VALUES (:title, :dueDate, :isCompleted);" } static var fetchAll: SQL { return "SELECT title, dueDate, isCompleted FROM tasks;" } static var fetchByID: SQL { return "SELECT id, title, dueDate, isCompleted FROM tasks WHERE id=:id;" } }
In the previous example, ‘SQL’ is just a typealias for ‘String’
Then, in the approach I’ve chosen, using
SQLite.Encoder and
SQLite.Decoder with our custom model type is extremely easy.
// wrap these calls in do-catch blocks in real apps let database = try! SQLite.Database(path: ":memory:") try! database.execute(raw: Task.createTable) let sqliteEncoder = SQLite.Encoder(database) let sqliteDecoder = SQLite.Decoder(database) // wrap these calls in do-catch blocks in real apps try! sqliteEncoder.encode(task, using: Task.upsert) let allTasks = try! sqliteDecoder.decode(Array<Task>.self, using: Task.fetchAll) let taskFromSQLite = try! sqliteDecoder.decode(Task.self, using: Task.fetchByID, arguments: ["id": .text(id)])
SQLite.Encoder and
SQLite.Decoder are modeled closely on
JSONEncoder and
JSONDecoder, the implementations for which can be found here. The major differences between the SQLite and JSON versions are 1) the SQLite varieties need to be initialized with an instance of
SQLite.Database and 2) encoding and decoding require a SQL statement and, sometimes, some arguments for the SQL statement.
SQLite.Encoder
The best way to understand how
SQLite.Encoder works is to first review how encoding works in Swift. Our
Task type is very simple, which means the Swift compiler is able to automatically synthesize its implementation of
encode(to:), but, in order to understand how it works, let’s implement it ourselves.
extension Task: Encodable { func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: Task.CodingKeys.self) try container.encode(id, forKey: .id) try container.encode(title, forKey: .title) try container.encode(dueDate, forKey: .dueDate) try container.encode(isCompleted, forKey: .isCompleted) } }
To add support for encoding our
Task, all we need to do is declare conformance to
Encodable and implement
func encode(to encoder: Encoder) throws. Inside of this method, we first ask the encoder for a key-value container to hold our model’s properties. The encoder is something that conforms to the
Encoder protocol. The key-value container is a more complicated type. Swift’s documentation gives its type as
KeyedEncodingContainer<Key> where Key : CodingKey.
KeyedEncodingContainer is an actual struct; it’s not a protocol. Its initializer has the signature
init<Container>(_ container: Container) where K == Container.Key, Container : KeyedEncodingContainerProtocol, which means the
KeyedEncodingContainer is a wrapper around something that is generic on the
Task.CodingKeys
Key type and conforms to the
KeyedEncodingContainerProtocol protocol. After we have gotten the key-value container from the encoder, we tell the container to encode each one of our model’s properties and save it using its key. In the case of our SQLite encoder, the keys each correspond to a column in the
tasks table.
Proceeding from the above, it’s clear that, at the very least, our
SQLite.Encoder will need to implement an encoder that conforms to the
Encoder protocol and a container that conforms to
KeyedEncodingContainerProtocol. Interestingly, the encoder and container are both private types hidden behind the public
SQLite.Encoder interface. Let’s implement the encoder.
private class _SQLiteEncoder: Encoder { var codingPath: Array<CodingKey> = [] var userInfo: [CodingUserInfoKey : Any] = [:] var encodedArguments: SQLiteArguments { return _storage.arguments } private let _storage = _KeyedStorage() func container<Key>(keyedBy type: Key.Type) -> KeyedEncodingContainer<Key> where Key: CodingKey { _storage.reset() return KeyedEncodingContainer(_KeyedContainer<Key>(_storage)) } func unkeyedContainer() -> UnkeyedEncodingContainer { fatalError("_SQLiteEncoder doesn't support unkeyed encoding") } func singleValueContainer() -> SingleValueEncodingContainer { fatalError("_SQLiteEncoder doesn't support single value encoding") } }
Most of this code is boilerplate that we had to add to conform to the
Encoder protocol. One thing to note is that our
_SQLiteEncoder is not as full-featured as the ones that power
JSONEncoder or
PropertyListEncoder because ours only supports keyed encoding and does not support nesting. That being said, our
_SQLiteEncoder is very similar to—and, in fact, modeled after—Swift’s
_JSONEncoder. When asked for a key-value container,
_SQLiteEncoder creates and returns a new
KeyedEncodingContainer that wraps our private
_KeyedContainer, which itself holds a reference to our private
_KeyedStorage. Let’s first take a look at
_KeyedStorage.
private class _KeyedStorage { private var _elements = SQLiteArguments() var arguments: SQLiteArguments { return _elements } func reset() { _elements.removeAll(keepingCapacity: true) } subscript(key: String) -> SQLite.Value? { get { return _elements[key] } set { _elements[key] = newValue } } }
_KeyedStorage is a simple, reference-typed wrapper around
SQLiteArguments, which is just a typealias for
Dictionary<String, SQLite.Value>. The purpose of
_KeyedStorage is to hold the SQLite values we want to encode for a single entity. This corresponds to a single row of values in a SQLite table. For example, if we were to encode
Task(title: "Buy milk", dueDate: nil, isCompleted: false),
_KeyedStorage would end up holding a dictionary like
["title": .text("Buy milk"), "dueDate": .null, "isCompleted": .integer(false)]. It needs to be a reference type because
_SQLiteEncoder needs to be able to return the encoded values via its
arguments calculated variable. As we can see in the code for
_SQLiteEncoder above, every time a new key-value container is returned from
container(keyedBy:), the keyed storage is reset, removing the previously-encoded entity’s properties from
_KeyedStorage._elements.
So, that leaves
_KeyedContainer, which is, by far, the largest type on our SQLite encoder team, but also one of the simplest.
private struct _KeyedContainer<K: CodingKey>: KeyedEncodingContainerProtocol { typealias Key = K let codingPath: Array<CodingKey> = [] private var _storage: _KeyedStorage init(_ storage: _KeyedStorage) { _storage = storage } mutating func encodeNil(forKey key: K) throws { _storage[key.stringValue] = .null } mutating func encode(_ value: Bool, forKey key: K) throws { _storage[key.stringValue] = .integer(value ? 1 : 0) } mutating func encode(_ value: Int, forKey key: K) throws { _storage[key.stringValue] = .integer(Int64(value)) } /** ...a bunch of other variations of Int and Double, such as UInt, Int8, Float, etc.... */ mutating func encode(_ value: Double, forKey key: K) throws { _storage[key.stringValue] = .double(value) } mutating func encode(_ value: String, forKey key: K) throws { _storage[key.stringValue] = .text(value) } mutating func encode(_ value: Data, forKey key: K) throws { _storage[key.stringValue] = .data(value) } mutating func encode(_ value: Date, forKey key: K) throws { let string = SQLite.DateFormatter.string(from: value) _storage[key.stringValue] = .text(string) } mutating func encode(_ value: URL, forKey key: K) throws { _storage[key.stringValue] = .text(value.absoluteString) } mutating func encode(_ value: UUID, forKey key: K) throws { _storage[key.stringValue] = .text(value.uuidString) } mutating func encode<T>(_ value: T, forKey key: K) throws where T : Encodable { if let data = value as? Data { try encode(data, forKey: key) } else if let date = value as? Date { try encode(date, forKey: key) } else if let url = value as? URL { try encode(url, forKey: key) } else if let uuid = value as? UUID { try encode(uuid, forKey: key) } else { let jsonData = try jsonEncoder.encode(value) guard let jsonText = String(data: jsonData, encoding: .utf8) else { throw SQLite.Encoder.Error.invalidJSON(jsonData) } _storage[key.stringValue] = .text(jsonText) } } mutating func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: K) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey { fatalError("_KeyedContainer does not support nested containers.") } mutating func nestedUnkeyedContainer(forKey key: K) -> UnkeyedEncodingContainer { fatalError("_KeyedContainer does not support nested containers.") } mutating func superEncoder() -> Encoder { fatalError("_KeyedContainer does not support nested containers.") } mutating func superEncoder(forKey key: K) -> Encoder { fatalError("_KeyedContainer does not support nested containers.") } }
As we can see, the purpose of
_KeyedContainer is to take the raw, encodable Swift types and convert them into our
SQLite.Value type, which is the type that
SQLite.Database understands. The majority of the Swift types are direct conversions. For example, all of the variations of Swift’s
Int are converted directly into
SQLite.Value.integer. We have to do some smarter conversions for more advanced types like
Date,
URL, or
UUID, but even those conversions are pretty straightforward. The most complicated conversion we have to do is when we encounter a type for which we haven’t created an explicit conversion. This could be something like a
Dictionary<String, String> or a completely custom type (e.g., an array of
Subtask). In this case, we use Swift’s
JSONEncoder to encode the type into
Data, and then we store the UTF-8 textual representation of that JSON. The reason we store JSON text instead of JSON data is that this allows us to use SQLite’s JSON extension to access and modify it, if we wanted.
Now that we’ve looked at all of the private types that power our SQLite encoder, let’s take a look at the public
SQLite.Encoder itself.
public final class Encoder { public enum Error: Swift.Error { case invalidType(Any) case invalidValue(Any) case invalidJSON(Data) case transactionFailed } private let _database: SQLite.Database public init(_ database: SQLite.Database) { _database = database } public func encode<T: Encodable>(_ value: T, using sql: SQL) throws { let encoder = _SQLiteEncoder() if let array = value as? Array<Encodable> { let success = try _database.inTransaction { try array.forEach { (element: Encodable) in try element.encode(to: encoder) try _database.write(sql, arguments: encoder.encodedArguments) } } if success == false { throw SQLite.Encoder.Error.transactionFailed } } else if let dictionary = value as? Dictionary<AnyHashable, Encodable> { throw SQLite.Encoder.Error.invalidType(dictionary) } else { try value.encode(to: encoder) try _database.write(sql, arguments: encoder.encodedArguments) } } }
The public class on our SQLite encoder team is very small and simple. It really doesn’t have much to do. Its main responsibility is creating an instance of
_SQLiteEncoder, passing that instance to the values to be encoded, and then writing the encoded values to the database using the provided SQL statement. In order to be as flexible as possible,
SQLite.Encoder.encode(_:using:) accepts single entities and an array of entities. So, our encoder is also responsible for deciding whether the
value passed into it is a single
Encodable entity or an array of entities. If the value is an array, then the encode method iterates over the array and passes each one to the instance of
_SQLiteEncoder it created. It rethrows any errors that happen during any of the steps of the encoding process.
And, that’s it. Although writing the SQLite encoder required writing a couple hundred lines of code, the majority of the code was very simple. The result is a flexible encoder that can work with nearly any custom type.
SQLite.Decoder
Writing a decoder is very similar to writing an encoder. If anything, it’s easier to implement a decoder than an encoder. As with the encoder, the best way to understand how
SQLite.Decoder works is to first review how decoding works in Swift. Again, the Swift compiler is able to automatically synthesize an implementation of
init(from decoder: Decoder) for our simple
Task, but let’s implement it ourselves.
extension Task: Decodable { init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: Task.CodingKeys.self) self.id = try container.decode(String.self, forKey: .id) self.title = try container.decode(String.self, forKey: .title) self.dueDate = try container.decodeIfPresent(Date.self, forKey: .dueDate) self.isCompleted = try container.decode(Bool.self, forKey: .isCompleted) } }
As is clear from the above, implementing the
Decodable protocol is very similar to implementing the
Encodable protocol. We first need to declare conformance to
Decodable and implement
init(from decoder: Decoder) throws. Inside of this method, we first ask the decoder for a container that holds the encoded values of the properties of our
Task. The decoder is something that conforms to the
Decoder protocol. The key-value container is very similar to the one that powers the encoder. Swift’s documentation gives its type as
KeyedDecodingContainer<Key> where Key : CodingKey. Again, similar to the encoding stuff, the
KeyedDecodingContainer is an actual struct, not a protocol. Its initializer has the signature
init<Container>(_ container: Container) where K == Container.Key, Container : KeyedDecodingContainerProtocol, which means the
KeyedDecodingContainer is a wrapper around something that is generic on the
Task.CodingKeys
Key type and conforms to the
KeyedDecodingContainerProtocol protocol. After we get the key-value container from the decoder, we ask it to decode a value for each one of the properties of our
Task. We specify the type we need the values to be decoded to. We immediately set those decoded values to the properties of our task.
So, again similar to the encoder, it’s clear that our
SQLite.Decoder will need to implement a decoder that conforms to the
Decoder protocol and a container that conforms to
KeyedDecodingContainerProtocol. The decoder and container are both private types hidden behind the public
SQLite.Decoder interface. Let’s start with the decoder.
private class _SQLiteDecoder: Decoder { var codingPath: Array<CodingKey> = [] var userInfo: Dictionary<CodingUserInfoKey, Any> = [:] var row: SQLiteRow? init(_ row: SQLiteRow? = nil) { self.row = row } func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> where Key : CodingKey { guard let row = self.row else { fatalError() } return KeyedDecodingContainer(_KeyedContainer<Key>(row)) } func unkeyedContainer() throws -> UnkeyedDecodingContainer { fatalError("SQLiteDecoder doesn't support unkeyed decoding") } func singleValueContainer() throws -> SingleValueDecodingContainer { fatalError("SQLiteDecoder doesn't support single value decoding") } }
Similar to
_SQLiteEncoder,
_SQLiteDecoder is mostly boilerplate code. It’s modeled after Swift’s
_JSONDecoder, but it’s more limited than the JSON version because it only supports keyed decoding. When asked for a key-value container,
_SQLiteDecoder creates and returns a new
KeyedDecodingContainer that wraps our private
_KeyedContainer, which takes a copy of the row-to-be-decoded.
SQLiteRow is just a typealias for
Dictionary<String, SQLite.Value>. It contains the column names and SQLite values for a single row fetched from the SQLite database. The decoder’s
_KeyedContainer is very similar to the encoder’s
_KeyedContainer.
private class _KeyedContainer<K: CodingKey>: KeyedDecodingContainerProtocol { typealias Key = K let codingPath: Array<CodingKey> = [] var allKeys: Array<K> { return _row.keys.compactMap { K(stringValue: $0) } } private var _row: SQLiteRow init(_ row: SQLiteRow) { _row = row } func contains(_ key: K) -> Bool { return _row[key.stringValue] != nil } func decodeNil(forKey key: K) throws -> Bool { guard let value = _row[key.stringValue] else { throw SQLite.Decoder.Error.missingValueForKey(key.stringValue) } if case .null = value { return true } else { return false } } func decode(_ type: Bool.Type, forKey key: K) throws -> Bool { guard let value = _row[key.stringValue]?.boolValue else { throw SQLite.Decoder.Error.missingValueForKey(key.stringValue) } return value } func decode(_ type: Int.Type, forKey key: K) throws -> Int { guard let value = _row[key.stringValue]?.intValue else { throw SQLite.Decoder.Error.missingValueForKey(key.stringValue) } return value } /** ...a bunch of other variations of Int and Double, such as UInt, Int8, Float, etc.... */ func decode(_ type: Double.Type, forKey key: K) throws -> Double { guard let value = _row[key.stringValue]?.doubleValue else { throw SQLite.Decoder.Error.missingValueForKey(key.stringValue) } return value } func decode(_ type: String.Type, forKey key: K) throws -> String { guard let value = _row[key.stringValue]?.stringValue else { throw SQLite.Decoder.Error.missingValueForKey(key.stringValue) } return value } func decode(_ type: Data.Type, forKey key: K) throws -> Data { guard let value = _row[key.stringValue]?.dataValue else { throw SQLite.Decoder.Error.missingValueForKey(key.stringValue) } return value } func decode(_ type: Date.Type, forKey key: K) throws -> Date { let string = try decode(String.self, forKey: key) if let date = SQLite.DateFormatter.date(from: string) { return date } else { throw SQLite.Decoder.Error.invalidDate(string) } } func decode(_ type: URL.Type, forKey key: K) throws -> URL { let string = try decode(String.self, forKey: key) if let url = URL(string: string) { return url } else { throw SQLite.Decoder.Error.invalidURL(string) } } func decode(_ type: UUID.Type, forKey key: K) throws -> UUID { let string = try decode(String.self, forKey: key) if let uuid = UUID(uuidString: string) { return uuid } else { throw SQLite.Decoder.Error.invalidUUID(string) } } func decode<T>(_ type: T.Type, forKey key: K) throws -> T where T: Decodable { if Data.self == T.self { return try decode(Data.self, forKey: key) as! T } else if Date.self == T.self { return try decode(Date.self, forKey: key) as! T } else if URL.self == T.self { return try decode(URL.self, forKey: key) as! T } else if UUID.self == T.self { return try decode(UUID.self, forKey: key) as! T } else { let jsonText = try decode(String.self, forKey: key) guard let jsonData = jsonText.data(using: .utf8) else { throw SQLite.Decoder.Error.invalidJSON(jsonText) } return try jsonDecoder.decode(T.self, from: jsonData) } } func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type, forKey key: K) throws -> KeyedDecodingContainer<NestedKey> where NestedKey : CodingKey { fatalError("_KeyedContainer does not support nested containers.") } func nestedUnkeyedContainer(forKey key: K) throws -> UnkeyedDecodingContainer { fatalError("_KeyedContainer does not support nested containers.") } func superDecoder() throws -> Decoder { fatalError("_KeyedContainer does not support nested containers.") } func superDecoder(forKey key: K) throws -> Decoder { fatalError("_KeyedContainer does not support nested containers.") } }
The purpose of the decoder’s
_KeyedContainer is to take the raw SQLite types fetched from the database and convert them into native Swift types, which we will then use to initialize our
Task. Just like with the encoder’s keyed container, most of the conversions are direct—for example, from
SQLite.Value.integer to
Int. Again, mirroring the encoder’s keyed container, we have to do some smarter conversions for more advanced types like
Date,
URL, or
UUID, but they are still relatively straightforward. Remembering back to the encoder, completely custom types (e.g.,
Subtask) are encoded using Swift’s JSON encoder before being saved to the database. Therefore, here, we need to decode them using Swift’s JSON decoder. Overall, the decoder’s
_KeyedContainer is a simple, albeit very long, class.
All that’s left is to look at the public
SQLite.Decoder itself.
public final class Decoder { public enum Error: Swift.Error { case incorrectNumberOfResults(Int) case missingValueForKey(String) case invalidDate(String) case invalidURL(String) case invalidUUID(String) case invalidJSON(String) } private let _database: SQLite.Database public init(_ database: SQLite.Database) { _database = database } public func decode<T: Decodable>(_ type: T.Type, using sql: SQL, arguments: SQLiteArguments = [:]) throws -> T? { let results: Array<T> = try self.decode(Array<T>.self, using: sql, arguments: arguments) guard results.count == 0 || results.count == 1 else { throw SQLite.Decoder.Error.incorrectNumberOfResults(results.count) } return results.first } public func decode<T: Decodable>(_ type: Array<T>.Type, using sql: SQL, arguments: SQLiteArguments = [:]) throws -> Array<T> { let results: Array<SQLiteRow> = try _database.read(sql, arguments: arguments) let decoder = _SQLiteDecoder() return try results.map { (row: SQLiteRow) in decoder.row = row return try T.init(from: decoder) } } }
The only public SQLite decoder class is quite straightforward. We expose two methods (in addition to the initializer) publicly. One is for decoding a single instance of one of our types. This is meant to be used when selecting a single item from the database. Our
Task.fetchByID SQL statement does exactly this. The other method is for decoding multiple instances of one of our types. Our
Task.fetchAll SQL statement is a good example of this. Regardless of which method is called, the same code path is followed. First, we fetch from the database using the passed-in SQL statement. Then, we initialize an instance of
_SQLiteDecoder. Finally, for each of the database results, we set the decoder’s
row to the current database result and then call the
Decodable initializer
init(from decoder: Decoder), passing in our decoder. The result is an instance of our custom type, which we then collect in an array and pass back to the caller. The first of the two decode methods checks to make sure that there is either zero or one item in the array and then passes that item (or
nil) back to the caller.
Going forward
Adding
SQLite.Encoder and
SQLite.Decoder to our apps allows us to benefit from the hard work the Swift language team has put into building
Codable. Importantly, this dramatically cuts down the amount of error-prone boilerplate persistence code we need to write. Additionally, this makes our code more flexible because it allows us to easily swap out our SQLite persistence engine for another technology that also supports Swift’s
Codable, if the need arises. Check out the code on Github. I’ve also created a Swift Playgound that includes all of the code in this post. Download it from Github.
|
https://shareup.app/blog/encoding-and-decoding-sqlite-in-swift/
|
CC-MAIN-2022-40
|
refinedweb
| 4,004
| 50.23
|
The .NET Framework class library provides various classes
for working directly with HTTP. Some of these are for client scenarios,
and are useful when you need to fetch resources from a web server such as
bitmaps, or if you need to use an HTTP-based service that WCF cannot
easily work with. You can also provide server-side HTTP support. You would
normally do that by writing an ASP.NET web application, which we’ll look
at in a later chapter. But there is a class that enables other program
types to receive incoming HTTP requests, called
HttpListener. (We won’t be covering that, and we
mention it mainly for completeness—it’s more normal to use ASP.NET, to
which we have devoted a whole chapter.)
The most common starting point for client-side HTTP code
is the
WebClient class in the
System.Net namespace. It offers a few
ways of working with HTTP, starting from very simple but inflexible
methods, through to relatively complex mechanisms that give you complete
control over detailed aspects of HTTP. We’ll start with the simplest
ones.
Although the examples in this section are HTTP-based,
WebClient supports other protocols,
including
https:,
ftp:, and
file: URLs. It is extensible, so in
principle you can adapt it to support any protocol that has a URL
scheme.
Example 13-11
illustrates one of the simplest ways of using the
WebClient class. We construct an instance,
and then use its
DownloadString method
to fetch data at a particular URL. (You can specify ...
No credit card required
|
https://www.safaribooksonline.com/library/view/programming-c-40/9781449392192/ch13s03.html
|
CC-MAIN-2018-30
|
refinedweb
| 260
| 65.22
|
Creating and Invoking a Web service using GlassFish in NetBeans, IntelliJ, and Eclipse - Part 2
By arungupta on Jan 31, 2007
Searching in the help bundled with the IDE on "web service from Java" returned
no results relevant to Web service. I found several (1,2,3)
people asking "How do I develop Web service in IntelliJ 6.x?" but all
the questions are unanswered. The online
documentation does not seem to talk anything about Web service. Searching
on intellij.org gave no results. Finally I found some lead
after searching in the forums but there is no help on "Enable Web Service
Support" as mentioned in the post. Another response
in the forum requires you to add
@javax.jws.WebService manually, pretty primitive. So
I decided to ask the question (1,
2) in
the forum.
After discussion in the forum I found that IntelliJ does not support creation of Web services natively but instead support it through a Web service plugin. The plugin, at the time of this writing is "0.6 build 2" with few skeptical comments but anyway worth a try. This plugin supports JWSDP 2.0 so first I'll investigate how Web services can be deployed on GlassFish and then come back to this plugin.
Here are the steps I followed to successfully build and deploy a Web service:
- Create a Web module (requires 12 clicks for default settings), say with name "hello". On Deployment Descriptors tab, select the default "Web Module Deployment Descriptor" and delete it as shown here. This is not required for deploying a Web service in GlassFish v2. Take all other defaults.
- In the "Project" pane, click on "src", add a new package "hello" as shown here.
- Select the package "hello", add a new class "Hello" as shown here.
- Click on the Project, right-click and select "Module Settings". Select the module and remove "j2ee.jar" as shown here. Add a new module library,
javaee.jar, from GlassFish
libdirectory as shown here.
- Add
@javax.jws.WebServiceannotation to the class and add a method as shown:
@WebService
public class Hello {
public String sayHello(String name) {
return "Hello " + name;
}
}
- Select "Build", "Make Project" (default shortcut Ctrl+F9).
- Configure and Run GlassFish v2 in IntelliJ. I added GlassFish v2 M4 using the following steps.
- Select "Run", "Edit Configurations ..." menu.
- Click on "+" in top-left corner to add a new configuration and then select "GlassFish Server" and "Local" as shown here.
- Specify the location of GlassFish by clicking on "Configure" button.
- Select the domain (default value "domain1"
in "GlassFish Server Settings".
- Add a new server by clicking on "+" in top-left corner and give the location where GlassFish is installed as shown here. Ignore the "There are no modules to deploy" warning as this will be fixed during Run. Now GlassFish is configured.
- To run the GlassFish instance
- Select "Run", "Run" (default shortcut Shift+F10) menu item.
- Run configuration window displays the warning message "There are no modules to deploy". Go to "Deployment" tab and selecting the newly created module to deploy as shown here .
- Check "Deploy Web Module" check box and click "Configure" button and select "Create web module war file". A warning is displayed "Warning: 'Glassfish Web Module Deployment Descriptor' is not defined" as shown here. This message can be ignored as no GlassFish specific deployment descriptors are required.
- Click "Run" button.
- Once the GlassFish server has started, the endpoint is hosted at.
The key point to note here is that no Deployment Descriptors (either standard or application serve specific) are required in the WAR file. The deployed WAR file in GlassFish consists only of the compiled class.The only way IDEA support creation of Web service clients is through Web Services plugin so I'll explore it in another blog. So the recommended way is to use NetBeans 5.5.1 to invoke the Web service.
Enjoy Web services deployed on GlassFish in IntelliJIDEA! And remember, GlassFish v2 uses Web Services Interoperability Technology (WSIT) that gives you interoperable Web services with Microsoft .NET 3.0 framework.
Technorati: NetBeans IntelliJ Eclipse GlassFish Web service WSIT
Posted by Arun Gupta's Blog on February 01, 2007 at 12:51 AM PST #
Posted by Arun Gupta's Blog on February 05, 2007 at 01:18 AM PST #
Posted by AdvTools on February 08, 2007 at 07:49 PM PST #
Posted by Arun Gupta's Blog on February 10, 2007 at 02:36 AM PST #
Posted by Arun Gupta's Blog on May 01, 2007 at 12:19 PM PDT #
Posted by Logic blog on October 14, 2007 at 05:53 AM PDT #
It will be nice if you write an article about intellij idea 7 + jax-ws 2.1 + glassfish (tomcat is much better), or is there something about them online already?
Posted by Thai Dang Vu on December 13, 2007 at 12:41 AM PST #
Posted by advtools on December 25, 2007 at 07:53 AM PST #
Hi Arun, thanks for this good tutorial. I have a question regarding the jax-ws SSL support, I configured my application server with SSL support and basic authentication. When running my client, I got this exception... Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException:. Any ideas? Any tutorial on accessing webservice from a secured server (SSL) with basic authentication? Thanks in advance.
Posted by cjbaldoza on February 05, 2008 at 06:43 PM PST #
Hello Sir,
I followed the screencast of creating and deploying web service using Eclipse on glassfish. It was very informative as i am new to it , thanks for that.
But when i am running my .jsp file on server ,the glassfish server gets started and it is throwing java.lang.NullPointerException . Do u have any idea why is it so.Please help me resolve this problem
thank you
Posted by Priyanka on October 23, 2008 at 03:53 PM PDT #
Hi Priyanka,
We really need more information to help you figure out why you're getting a NullPointerException. I suggest you post to the users@glassfishplugins.dev.java.net mailing list and we can try to help.
Posted by Rochelle Raccah on October 24, 2008 at 06:17 AM PDT #
Dear sir,
I want complete information regarding how to create deploy and run web service in eclipse europa using glassfish
specifically i need information regarding how to create webservice client for accessing web service
thank you
Posted by Kashmira on November 04, 2008 at 12:48 PM PST #
Kashmira, you can find more details at:
Posted by Arun Gupta on November 07, 2008 at 09:09 AM PST #
Enjoy Web services deployed on GlassFish in IntelliJIDEA! And remember, GlassFish v2 uses Web Services Interoperability Technology (WSIT) that gives you interoperable Web services with Microsoft .NET 3.0 framework.
Posted by BATTERY on November 27, 2008 at 08:50 AM PST #
|
https://blogs.oracle.com/arungupta/entry/creating_and_invoking_a_web1
|
CC-MAIN-2015-40
|
refinedweb
| 1,139
| 64.3
|
Before we get into the code involved in creating your own user-defined type in SQL Server 2005, it should be pointed out that CLR UDTs are extremely different from any type of custom data structure you may have created for previous versions of SQL Server. A CLR UDT not only has fields for storing data, but it also has behaviors that are defined by C# methods on the UDT class. The larger and more complex a UDT, the more overhead it consumes. As a result, the most efficient use for UDTs is storing simple data over which you want tight control. For example, you could create a UDT in C# that provides a highly customized type of date/time storage, or you could even create one that stores encrypted data. You can provide behaviors (methods) on that type to gain access to the decrypted values.
The SQL Books Online reference that you can install with SQL Server 2005 illustrates the use of CLR UDTs with a type called Point. What we want to do is to create a table in SQL Server that is storing the positions of all the objects in a fictitious strategy game. This fictitious game uses three-dimensional space, so the UDT that we will create will support three-dimensional points, and will contain a method for determining the distance between two 3D points.
To get started, add a user-defined type called Point3D to your project using the same method used to create a user-defined procedure and a user-defined function.
Next, change the default class definition so that it looks like the one shown in Listing 21.2.
using System; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; using System.Text; [Serializable] [Microsoft.SqlServer.Server.SqlUserDefinedType(Format.Native)] public struct Point3D : INullable { private bool isNull; private int x, y, z; public override string ToString() { if (isNull) return "NULL"; else { StringBuilder sb = new StringBuilder(); sb.AppendFormat("{0},{1},{2}", x, y, z); return sb.ToString(); } } public bool IsNull { get { // Put your code here return isNull; } } public static Point3D Null { get { Point3D h = new Point3D(); h.isNull = true; return h; } } // do not invoke this method when the value is null [SqlMethod(OnNullCall=false)] public static Point3D Parse(SqlString s) { Point3D u = new Point3D(); string rawValue = s.Value; try { string[] vals = rawValue.Split(','); u.x = Int32.Parse(vals[0]); u.y = Int32.Parse(vals[1]); u.z = Int32.Parse(vals[2]); } catch (Exception e) { throw new ArgumentException( "String format is not a valid 3-D point structure", e); } return u; } [SqlMethod(OnNullCall=false)] public Double DistanceFromPoint(Point3D origin) { return Math.Sqrt( (Math.Pow(x - origin.x, 2.0) + Math.Pow(y - origin.y, 2.0) + Math.Pow(z - origin.z, 2.0))); } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } public int Z { get { return z; } set { z = value; } } }
It looks pretty much like any other C# struct, with a few minor differences. The SqlMethod attribute controls the behavior of the method when invoked within a SQL statement.
To use this new data type, first run your project to complete the deployment and registration of your new type. Then, you can use SQL Server 2005's management console or Visual Studio 2005's server browser for creating a new table. Figure 21.2 shows the table editor from within Visual Studio 2005. Note that the Point3D data type appears just like any other type in SQL.
Two of the key methods that make this type work are the Parse method and the ToString method. The Parse method is what allows you to enter textual data in a grid or send textual data in a SQL statement and have SQL properly create an instance of the Point3D type. By default, SQL Server 2005 doesn't invoke the ToString method on your type to display it; it displays the raw serialization data.
Create a new table, GameObjects, with a column for the object's ID, the object name, and the object's location. Then, add in some rows of data, making sure to enter the location points in the format x,y,z.
With the data in place, you can start issuing SQL statements to examine the contents of the data, as shown in the following code:
DECLARE @refPoint Point3D SELECT @refPoint = Location FROM GameObjects WHERE ObjectId=2 select ObjectID, Name, Location.ToString() as CurrentLocation, Location.DistanceFromPoint(@refPoint) FROM GameObjects
This SQL statement will give you a list of all the objects in the game, as well as each object's distance from the object with ID 2. The following are the results from the author's sample data:
1 Battleship Intrepid 0,0,0 21.6101827849743 2 Starship SAMS 1,5,21 0 3 Battlecruiser DotNettica 9,7,3 19.7989898732233
As expected, the distance from object 2 to object 2 is 0. The other objects are displaying the results of the DistanceFromPoint method on the Point3D struct itself.
With this kind of power in hand, you can do a lot of really interesting things. For example, let's say that the Starship SAMS has a radar radius of 20 units. We can easily issue a query that will return all game objects within radar range, as shown in the following lines:
select ObjectID, Name, Location.ToString() as CurrentLocation FROM GameObjects WHERE Location.DistanceFromPoint(@refPoint) < 20 AND ObjectID != 2
You can also access the user-defined type from within your regular .NET code using ADO.NET. All you need to do is add a reference in your client code to the assembly that contains the UDT. Create a console application and then add a reference to SqlProjectDemo.dll by browsing for it. Then you can write the code shown in Listing 21.3.
using System; using System.Data; using System.Data.SqlClient; using System.Collections.Generic; using System.Text; namespace ClientHarness { class Program { static void Main(string[] args) { SqlConnection conn = new SqlConnection( "data source=localhost; user id=sa; password=...; Initial Catalog=SampleDB"); conn.Open(); Point3D origin = new Point3D(); origin.X = 0; origin.Y = 0; origin.Z = 0; SqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT ObjectID, Name, Location FROM GameObjects"; SqlDataReader rdr = cmd.ExecuteReader(); while (rdr.Read()) { Console.WriteLine("{0} ({1}) is at {2}. Distance from Origin {3}", rdr["ObjectID"], rdr["Name"], ((Point3D)rdr["Location"]).ToString(), ((Point3D)rdr["Location"]).DistanceFromPoint(origin)); } rdr.Close(); cmd.Dispose(); conn.Close(); Console.ReadLine(); } } }
When you run this application, you receive the following output:
1 (Battleship Intrepid) is at 0,0,0. Distance from Origin 0 2 (Starship SAMS) is at 1,5,21. Distance from Origin 21.6101827849743 3 (Battlecruiser DotNettica) is at 9,7,3. Distance from Origin 11.7898261225516
Remember that CLR UDTs are designed specifically for small, simple types that might expose a few behaviors. If you attempt to store complex or hierarchical data in a UDT, you might actually be slowing your application down.
|
https://flylib.com/books/en/1.237.1.136/1/
|
CC-MAIN-2022-05
|
refinedweb
| 1,164
| 57.16
|
The HTML and XHTML standards allow a content author to extend the set
of composition elements on a web page by applying special styles to
the <div> and
<span> tags and their content. A styled
<div> block might appear to be a navigation
bar, an advertisement, or some other specialized content that HTML
does not explicitly define. XML Binding Language
(XBL) is an alternate strategy for naming features of web pages. This
hack shows how you might use it.
XBL
is a Mozilla technology that's slowly being adopted
by the W3C. It first appeared at the W3C as a technical note at.
More recently, it has entered the formal standardization track via
the sXBL standard (the s indicates that
XBL's initial standard use is in SVG). That standard
is here:. Mozilla XBL syntax
is not yet the same as the W3C syntax, but the concepts are all the
same. It will match the standard one day.
In Firefox, XBL is used to create a new tag for any XML or HTML
dialect, but most frequently for XUL. Public or strictly conforming
HTML and XHTML documents should not be hacked with XBL. Use it for
custom, private documents only. An XBL binding written in XML is
attached to a tag using a Mozilla-specific CSS
style:
tagname { -moz-binding : url("binding-definition.xml"); }
It's also possible to say the binding is
bound to the tag, but the idea of attachment will get you
into far less trouble.
HTML and XHTML can achieve a lot when combined with
CSS, but they don't contain any direct support for
sidebars. Sidebars are blocks of text,
usually floating on the right side of the screen, that contain
information that's an aside to the main flow of the
text. Let's make a
<sidebar> tag using
XBL.
Here's an HTML equivalent, to begin with:
<div style="float : right; background-color : lightyellow;">
<hr />
<div style="font-weight : bold;">Sidebar Title</div>
<p>This is the content of the sidebar</p>
<p>The content could be long</p>
<div style="text-align : right; font-style : italic;">Anon.</div>
<hr />
</div>
Using XBL, we extract the structural content into a file named
sidebar.xml:
<?xml version="1.0"?>
<bindings xmlns=""
xmlns:xbl=""
xmlns:
<binding id="sidebar">
<resources>
<stylesheet src="sidebar.css"/>
</resources>
<content>
<xht:hr />
<xht:div
<children />
<xht:div
<xht:hr />
</content>
</binding>
</bindings>
The <content> part matches the XHTML
content, with a few namespaces thrown in. Note the use of
XBL's special inherits attribute
and <children> tag mixed into the XHTML. The
<resources> section is optional. In this
case, sidebar.css might contain the following
styles:
.sidebar-title { font-weight : bold; }
.sidebar-author { text-align : right; font-style: italic; }
These styles affect the tags inside the content
part of the binding. These tags can't be styled from
HTML. To attach this binding, HTML pages must include extra styles.
These styles affect the whole binding. The
following file, bind-sidebar.css, is an example
of such a style:
sidebar {
-moz-binding : url("sidebar.xml#sidebar");
background-color : lightyellow;
float : right;
}
The HTML or XHTML page must include this stylesheet with a
<link> tag. Once the binding is created, a
web page can reuse the structural content freely:
<html>
<head>
<link rel="stylesheet" href="bind-sidebar.css" type="text/css">
</head>
<body>
<p>
<sidebar title="First Sidebar" author="Anon.">Foo Content<br>Bar Content</sidebar>
Lorem ipsum dolor sit amet ...
<sidebar title="Second Sidebar" author="- me.">Short Content</sidebar>
Lorem ipsum dolor sit amet ...
</body>
</html>
Figure 1 shows this HTML page after the bound
<sidebar> tags are rendered.
A more typical use of XBL is to increase the set of widgets that
XUL offers. XUL's
default widget set is defined in a file called
xul.css in the chrome. You can increase the set
of widgets by using any stylesheet, or you can hack that file
directly [Hack #75]. Figure 2 shows an example of a simple new widget called
checkbutton.
Each time you click the button, the small checkbox is toggled on or
off. The checkbutton widget is hooked up to the
<checkbutton> tag using CSS, the same as in
the HTML case:
checkbutton { -moz-binding : url("checkbutton.xml#checkbutton"); }
There are no extra styles in this case. XUL relies on the
<?xml-stylesheet?> processing instruction to
load CSS. The widget has the focus (the dotted line), because
it's already been clicked a few times. The tag used
to create this example is simply this:
<checkbutton label="Click me to toggle check state" checked="true"/>
Unlike text, widgets are active and responsive, so the
checkbutton XBL binding has more object-like
features than the sidebar example. Here's the
binding definition:
<?xml version="1.0"?>
<bindings xmlns=""
xmlns:xbl="" <!-- for xbl:inherits -->
xmlns:
<binding id="checkbutton">
<content>
<xul:button>
<xul:checkbox xbl:
</xul:button>
</content>
<implementation implements="nsIDOMXULCheckboxElement">
<property name="checked"
onget="return this.getAttribute('checked') == 'true';"
onset="return this.setAttribute('checked', val);" />
</implementation>
<handlers>
<handler event="click"><![CDATA[
var state = this.getAttribute("checked") == "true" ? 1 : 0;
this.setAttribute("checked", state ? "false" : "true");
]]></handler>
</handlers>
</binding>
</bindings>
The <implementation> section can define
fields, properties, and methods, mostly not illustrated in this
example. The <handlers> section defines
handlers, in this case, a single handler for the
click DOM 2 event. This handler will fire if no
handler is explicitly placed on the
<checkbutton> tag.
Here's a sample XUL document that benefits from this
binding:
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/"?>
<?xml-stylesheet href="bind-check.css"?>
<window
xmlns=""
title="Example Widget">
<description>Test widget for the checkbutton binding</description>
<checkbutton label="Click me to toggle check state" checked="true"/>
</window>
O'Reilly Home | Privacy Policy
© 2007 O'Reilly Media, Inc.
Website:
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
|
http://archive.oreilly.com/pub/h/2958
|
CC-MAIN-2015-22
|
refinedweb
| 984
| 58.18
|
This feature is in BETA stage.
Some benefits of this feature are:
First, define the gift items you want people to be able to purchase as
products. As with regular payments, you'll need to build the user experience where a player can select the different items that can be gifted.
Once a player has selected a gift to send on your UI, they must click a gift button to send. This button launches the in-game gifting dialog where the player can first choose a friend to send this gift to.
To open the in-game gifting dialog, you should use the
FB.ui method of the Facebook's SDK for JavaScript, specifying the
product parameter for the gift the player wants to send. You can create your own gift recipient selector dialog by using the recipient ID in the
to field. If the
to field is provided when the gift dialog is invoked, the friend selector step of the dialog will be skipped and the player is taken to the payment dialog. You can use any user ID in the
to field, including people that aren't friends of the sender.
FB.ui({ method: 'gift', product: 'URL_TO_YOUR_PRODUCT', }, function(response){console.log(response);} );
Send gift to specific recipient, where the
to parameter is the recipient ID:
FB.ui({ method: 'gift', product: 'URL_TO_YOUR_PRODUCT', to: 'USER_ID' }, function(response){console.log(response);} );
Once the dialog is shown, the player can choose a friend to send this gift to. Selecting a friend will launch the payment dialog.
If the payment was successful, your game must fulfill the purchase by awarding the gift at one of two possible times:
Facebook sends a notification to the recipient with the name of the gift included.
Additional to the regular payment information, the callback data will also contain a
receiver parameter and a
gift_requests parameter. The response contains data in the same format you receive when you send an
app_request:
{ "amount":"0.01", "currency":"USD", "gift_request": { "request":"1483068188614502", "to": [1477568509157318] } "payment_id":"624623807654732", "quantity":"1", "receiver":"1477568509157318", "signed_request":"lFd_bGdvcml0aG0iOiJITUFDLVNIQTI1Ni...", "status":"completed" }
If the transaction fails, you will receive an error code and message with more information about the cause.
All payment objects created via the in-game gifts flow will include a
gift_requests field. This is an apprequest object associated with the payment object, and it includes the object id for
gift_requests as well as info about the sender, receiver and game app. You have to explicitly query this gift_requests object via graph API:
GET graph.facebook.com/{payment-id}?fields=items,actions,gift_requests
Here's a sample response for a payment object with
gift_requests:
{ "actions": [ { "type": "charge", "status": "completed", "currency": "USD", "amount": "0.01", "time_created": "2014-11-10T14:42:40+0000", "time_updated": "2014-11-10T14:42:42+0000" } ], "id": "555885171208546", "created_time": "2014-11-10T14:42:40+0000", "gift_requests": { "data": [ { "application": { "name": "Friend Smash! - Dev", "namespace": "friendsmashsampledev", "id": "844042765624257" }, "created_time": "2014-11-10T14:42:42+0000", "from": { "id": "382172578615968", "name": "Guannan Pu" }, "message": "I hope you like my gift!", "to": { "id": "1509388185975350", "name": "Connor Treacy" }, "id": "902190936459036_1509388185975350" } ], "paging": { "cursors": { "before": "OTAyMTkwOTM2NDU5MDM2XzEwMDAwNzEyNTQ4MDk5MQ==", "after": "OTAyMTkwOTM2NDU5MDM2XzEwMDAwNzEyNTQ4MDk5MQ==" } } } }
|
https://developers.facebook.com/docs/games_payments/advanced/ingamegifting
|
CC-MAIN-2018-26
|
refinedweb
| 515
| 54.22
|
These are chat archives for systemjs/systemjs
loadConfigand the config passed to a builder instance?
import * from './moduleA'to
./moduleA/index.ts?
@adamburgess Okay, so, for example,
System.import('app/main.js')? I don't need to map the file-to-be-imported, right?
Also wanted to ask how to work with templates. I did a static bundle that almost worked, but template locations are off now.
var map = { 'app': 'dist', ... }; var packages = { 'dist': { main: 'loghub', defaultExtension: 'js' },
System.import('app/main.js')
dist/main.js, but no dice.
'dist': { main: 'loghub', defaultExtension: 'js' },
this means the
dist (or app) folder's main file is loghub.js
you're calling System.config({map: map, packages: packages}) before the import, right
|
https://gitter.im/systemjs/systemjs/archives/2016/07/20?at=578fca584feb3a7668940f6b
|
CC-MAIN-2019-30
|
refinedweb
| 120
| 62.54
|
I have a GUI on my scene saying "Capsules Collected: 0/10" and a capsule object which has Collider that whenever the player enters the capsule , the capsule will be destroyed and the Capsules Collected will be increased by 1.
The Destroy Works well, the GUI isnt displaying. What is wrong with my code?
Here's my Code, I assigned this C# script on the Player itself:
using UnityEngine;
using System.Collections;
public class CapsuleGET : MonoBehaviour {
int capscore=0;
void Start(){
}
void OnTriggerEnter(Collider other) {
Destroy(other.gameObject);
capscore =capscore+1;
}
void Update(){
GUILayout.Label("Capsules Collected: "+capscore+"/10");
}
}
Like this .. very easy
using Unity.UI; public class CapsuleGET public Text displayScore; // DRAG to connect in Editor void OnTriggerEnter(Collider other) { Destroy(other.gameObject); capscore =capscore+1; displayScore.text = capscore.ToString();
1 - click to add canvas (don't forget to select 'scale with screen size')
2 - click to add Text, position as you want.
3 - in your script, "public Text score"
4 - drag from the "Text" to that variable
explanation with diagrams
|
https://codedump.io/share/VUqMvo9BGRMT/1/display-gui-with-incrementing-variable-each-collision
|
CC-MAIN-2016-50
|
refinedweb
| 172
| 58.48
|
- Pay parking (payment, expiry notification)
- event tickets (purchase, rsvp, ticket image)
- catching pokemon (just catch whatever and message me a snazzy report full of pokemon names every once in a while)
- ordering food
- managing bills (let me know when phone/electrical/heat bill comes in, check usage so far, coordinate payment between all the people in the conversation)
We analyse free-form comments and uses NLP to extract commonly-mentioned problems. Currently users need to log into the app and explore their data in order to discover problems, but it would be much more convenient if we could send the problem descriptions to a slack channel as our AI discovers them. It would be even more convenient if the users could then ask our bot for more details about a problem, such as giving example comments illustrating the problem or listing the customers who are affected. We have the data required to answer those questions, but even though our AI extracts information from free-form text, it's not the kind of AI who can answer free-form questions, so we might need help with that.
For tasks & information which are required for a short duration & thats it and value for which is only for that moment should be implemented as bots.
Parking, ordering are all short, instantaneous tasks which are only of value there & then. Anything that meets this criteria can fit the bill of being a chatbot...
You have 4 months to train for a better job and the best advice is to spend the time studying interview techniques??
I'm not criticizing anyones post here, but the industry in general. That's where we are? Teaching to the test??
I know, I know, "interviewing is broken" and "that's the way the big companies evaluate you" and all.. but geez! Is anyone else bothered by this? Isn't it possible to get a good job at a good company based on your skills & knowledge rather than interview-ability?
I can understand an argument of "well, OP wants to get into Google, and this is the best way", but maybe that means that sights are set too high... maybe it should take longer than 4 months to get a job at Google. Am I taking crazy pills?
Cracking the coding interview is pretty good, but you'll go crazy if you just try to work through it straight without any other content to broaden your perspective.
I'd suggest doing challenges on Topcoder, Hackerrank, etc. to help reinforce the concepts. These questions are very similar in format (if not content) to those you'll see in your interviews, so it's helpful to get thinking in these kinds of modes.
If you're not already comfortable coding on a white board, or talking and coding at the same time, you'll want to work on those as well. Even some simple rubber duck programming will be useful.
Note that the above is probably not going to be anything new to you - you've probably already read this in a bunch of other blogs you found while googling. I repeat it only to reinforce its accuracy.
Understand all of Cracking the Coding Interview. Surround yourself with other developers who know the material well.
Long answer:
The big 4 hire thousands of engineers a year.
They have an interview process that brings in developers who can "get the job done". What I mean by this is that 99% of those thousands of developers won't be building anything groundbreaking.
Before you decide you want to work for these guys ask yourself why you want to work for a big company.
Is it:
- To get away from contracting - do you feel trapped?
- You're not learning any more or getting anything out of contracting?
- You just want to try something different?
- You want to work on a specific team in a specific company because their problem is interesting and unique?
Another thing that's interesting - you say the interview process terrifies you.
You need to ask yourself why it scares you.
A lot of the time when something terrifies you it means that you need to expose yourself to it.
Ask yourself:
- What's the worst that could happen? (you fail the interview and you're in the same place as you were today, just with more experience)
- What do I lose by going into one of these interviews without being prepared (you can't interview again with this company for a year)
- What do I gain by going into one of these interviews without being prepared (you get a feel for how the interview process works)
Don't be afraid of failure - it's the key to success.
1. Unless they contacted you at LinkedIn or you know someone at Google who can refer you, the most difficult part is actually getting an interview.
2. Apply as soon as possible. They don't mind scheduling an interview 3 months in advance and they will send you preparation material and they will be able to answer questions. (This is specific to Google, I would not do that at most other companies).
3. Check out Quora they have a ton of information about the Google interview process. Also some info, but not so much about other companies. That shouldn't matter because the preparation is mostly the same.
4. I don't think it's a bad idea to follow courses as well. At least for me it would motivate me more if I learned something of value in addition to just getting a job. However, unless you are interested in it, don't worry about Math.
5. As others I would recommend to work through the book Cracking the Coding Interview. I also found the website interviewbit.com helpful. It's similar to leetcode, but they organize the questions by topic and gamified it. This helped me to stay motivated.
6. Also prepare for system design questions. Those are equally important as coding, algorithms and data structures for candidates that have industry experience.
7. Do mock interviews. Ask friends, otherwise there is a YC startup called Pramp.com. They allow to do mock interviews with peers for free. There also services that let you do payed mock interviews with people that actually work at big tech companies.
8. Don't be naive about what impact you can have working at big companies like Google. You are going to work on a small subpart.
For example, you want to do some graphics programming, maybe a raytracer, and that leads to thinking about projective geometry and linear algebra and whoah, a few years later all of that stuff is useful when you end up in a machine learning job. (maybe)
But back to the plan, if that's your thing. All the blog posts that complain about the "interview process" seem to be about how they don't understand dynamic programming. So, put that at the top of your list! (And by the way it is loads of fun.)
I have recently found "Elements of Programming Interviews" [1]. For people with 5+ years of experience trying to clear Google style interviews, this is the perfect book for following reasons:
+ The quality of problems is much much better than the other two books popular in this category ([2,3]). I am not saying problem are hard, but they found a right balance between quality and solvability in interview setting.+ The solutions are methodical and of high standard. For experienced people, problems in [2,3] may appear too dumb down. + It has some 260 or more problems covering various areas of CS. By going through this book, you should get CS fundamentals and interview prep in one shot.
I have all three books but strongly recommend EPI
[1] Elements of Programming Interviews[2] Cracking the Coding Interviews[3] Programming Interviews Exposed.
I have no affiliation with authors/publishers of [1]
I mean I do not want to underestimate your skills and intellect but look at what happened to Geohot and I believe he is above your average MIT/Stanford graduate
For learning Algorithms and data structures for interviews
1. Coursera courses on Algorithms by Prof Roughgarden
2. Coursera courses on Algorithms by Prof Sedgewick
3. OCW 6.006 as listed above would be good too.
4. Prof Skiena's algorithms course
5. Berkeley CS 61b by Prof Shewchuk for refreshing basic Data structures like Linked list, tree traversals which are not covered in above mentioned courses.
For practice,
1. geeksforgeeks.org
2. leetcode.com
3. interviewbit.com
4. careercup.com
5. Hiredintech.com
6. topcoder, hackerrank , spoj etc are good sites for practice in general but their problems are embedded with extraneous information not seen in interviews. For example, interviewer is not going to explain you 2 page story, instead he will tell you directly what needs to be done.
In books,
1. Cracking the Coding Interview
2. Programming Interviews Exposed
3. Elements of Programming Interviews
Books on Design Patterns
1. GoF
2. Head first design patterns
3. Software Architecture books by Robert Martin
4. Elements of Enterprise Architecture Patterns by Fowler
5. System Design research papers, gainlo.co has many design questions
Even if your BS in SW had been heavy on math, it wouldn't likely matter much now that several years have passed where you haven't used that education.
As others have said, practicing for the type of interview you'll be subject to at these companies is probably a better plan than taking a bunch of online courses.
My concern is that you seem to equate "solving real problems" with only a handful of companies, and it turns out that those companies are somewhat known to all have this particular interview style which will require you to memorize algorithms and data structures (even if you won't use those skills on a daily basis at that job).
Essentially, you're talking about taking a few months to prepare for the interview that most entry-level candidates with "Big4" aspirations prepare for after graduation.
Another option would be to consider whether there are other companies solving real problems (of course there are), and whether or not these other companies would subject you to the same style of interview (probably not).
Other companies won't interview the same way, and still solve big problems. I'm not sure if this is something you'd considered, but thought I'd throw it out there.
Based on your plan, you would become better versed in several areas of theory, but still limited to being a Java programmer - which in turn will probably lock you into the enterprise space. Unlikely to give you real problem solving opportunities.
@grobaru hit the nail on the head. The established firms you list are either going to hire you for your general programming knowledge or for a specific project. In the latter case domain knowledge and experience is going to be valuable.
I think you need to revisit your goals. What industries do you prefer to work in? What domain knowledge do you bring to the table? Look at what languages, frameworks are used in those areas and then get some experience with them. And have you considered startups? Their mission and problem domain(s) tends to be more focused than the big companies.
Before I worked here, I read Steve Yegge's posts on interviews at Amazon and Google. You cannot get information more straight from the horse's mouth.
I also agree with the general point that you are better off doing interview prep than your general undergrad algorithms courses.
But the catch is that interview prep will lead you back to CS fundamentals anyway. This is a both/and, not an either/or.
The other thing I wanted to address is whether working at Amazon can be practical and cool.
My team is the full stack physical rentals team. When you press a Rent-Now button on Amazon.com, you enter my team's world. Today, we rent physical textbooks to millions of students every semester, and they all get returned at the same time.
We own custom checkout, order management, and return customer experiences. Underlying them is a service ecosystem we built and maintain. To handle the seasonal, spiky nature of our business (back to school, Christmas vacation returns), we use AWS to scale up and down during peaks.
Success breeds success, and we're working on category expansion. Twenty engineers in three teams run the software for this business. That is cool.
There is an incredibly broad spectrum of work going on at Amazon, from mammoth services to front end optimization and everything in between, including unfortunately some very unhappy firefighting operations. Undergirding it is heavy company investment in builder tools and infrastructure, and excellent engineers.
One person's cool is another person's depressing, but I would look at the job listing carefully before writing off a stint at any of the Titans of software.]
If the answer is "well actually I haven't tried yet, but I hear it's really scary" then maybe a better plan is to go interview with google.
They really want to find people who are good at programming computers, which you seem to be. They want that even more than they want to humiliate people with impossible algorithm trivia, believe it or not.
Seems like you might save yourself a few months of no fun, and end up landing your dream job in the process.
These books really pique your interest, and after finishing them you will see the big picture and find sufficient motivation (problem solving wise), and may venture into following proper undergraduate courses with proper textbooks. You might even like to quickly read through Skiena's The Algorithm Design Manual as an intermediary step. This book is a proper 'engineer's book' as in it is basically a catalog of algorithms and data structures with advise and illustration of where to use what.
With this approach, you won't be needing a tutor and can gain a lot by self studying at your own pace.
However, the problems solved at Amazon, Google and Facebook aren't necessarily more "real" than what you're solving now. Google also builds a lot of Java webapps. Sure, there are many advantages to working at these companies, but be aware that you most likely won't end up on the team that builds the algorithms for the self driving car or the machine learning powered object detection for photos.
Depending upon your areas of interest, you might also want to look into related open source projects and attempt to contribute. Chances are that you'll learn a fair bit in the process.
[0]...
I don't work for amazon but yeah i work in one of the so called top 4 companies.I got lucky to get into a good project. But talk with some google employees and you will be surprised to see how many engineers work on some pretty mundane stuff inside of google.
Still i can't process the thought that the OP is not solving real world problems right now as a contractor and would be doing some sort of a dream job after he gets through the google interview process.
What exactly is a real world problem?
Gaining cutting-edge skills sends a strong signal to the market. And can make you more attractive to recruiters.
Don't overlook the professional network piece of making new friends and contacts amongst your fellow students. Those individuals often have inside tracks to hidden opportunities.
Here's a review of Laslo Bock's Work Rules >...
When there is a CS person interviewing me I get depressed because I know they are going to do a sanity check on CS things and I will fail because I don't have Big O memorized.
Why it depresses me is if they say, they want to scale postgres, I can come back to them with a working model, and I may utilize CS like-things, but since I can't remember textbook answers its gates me from jobs.
If you got the savings, I would say go for it and take the time to learn. I don't know how helpful the math for computer science course will be but understanding various algorithms is useful for general knowledge and especially for interviews. Once you know basic algorithms, start on cracking the coding interview, hackerrank etc.
Lastly, I would say the grass is always greener on the other side, so don't disregard all you have accomplished and all that you will continue to do. If you think you will enjoy a job at a top company, go for it, but don't do it because you think what you are doing is inadequate.
This is called vertical integration, by the way. Instead of spending your time learning more and more about the arcane details of programming, you might be much better off learning more and more about how and why people ask for programs to be created -- and what happens to them after they're coded.
Don't be overwhelmed by this though -- API design isn't an exact science. It's also very opinionated.
Personally, I would just start reading actual API documentation (GitHub is a great place to start -- their API is a joy to work with). Find things you like and don't like about it and try to figure out why those decisions were made.
Everyone has different recommendations - dont get discouraged by this.
Make sure also to look into newer standards like JsonAPI if they are suitable - last time i tried to use it the tooling around it was still not strong enough and i decided to go w/ simpler custom api.
Assuming it has to be a restful api (vs graphql) and assuming you want to create an api for multiple kinds of clients (that's the the harder part) - Here my personal TL;DR:
- Autogenerate your docs with your tests
- Do versioning in URL (easier to route/cache/etc)
- Worry about caching (a lot)
- Personalized info only in isolated namespace, rest is fully cacheable
- Never embed personalized information (eg not `{ post: { user_has_commented: true } }`
- Never nest data (not `post: { author: { } }` but reference only `post: {author_id: }`)
- Embed referenced objects only by whitelist
- Never nest routes (not `/posts/343/comments` but `/comments?post_id=232`) filtering tends to become more complex
- Use public feedback tools (eg github issues) for your user questions/complains - so it can become searchable for people with similar problems
hth - happy to answer some of those in detail if useful
As said - highly subjective opinions - i am sure others might disagree w/ some of the points
How to Design a Good API and Why it Matters (Josh Bloch):
[1]
1. Restful API with WCF -
2. Restful API using WebAPI -...
3. API via dll -...
It falls into the category of non-web API. It's a good read and I think it carries over to web APIs quite well.
This is a must watch and encapsulates good design and theory:
Good API design, if you are trying to learn from zero, comes from learning from good examples.
These are some of my favorites APIs by design
+ Stripe
+ Twilio
+ Slack
+ Stormpath (fd: I work here)
There is a lot of work that goes around the API design to make it a great API (examples, documentation, live samples, etc)
If you're talking about REST APIs, then the best book I've come across is RESTful Web APIs by Leonard Richardson and Mike Amundsen:
It actually shows you how to do REST properly, not that shoddy knock-off REST that some people push, where you have to document all your URI structures and hard-code them in your clients. There's solid examples that you build upon throughout each chapter, and jumping off points to standardisation work like JSON-LD etc.
The code examples almost become irrelevant because they make the patterns so clear.
Many of the comments here take API to mean an HTTP exposed API (REST), but API stands for "Application Programming Interface"
It is much more generalized than APIs designed for HTTP consumption.
>The number of APIs produced by Googles various businessunits grew at an astounding rate over the last decade,the result of which was a user experience containing wildinconsistencies and usability problems. There was no singleissue that dominated the usability problems; rather,users suffered a death from a thousand papercuts. A lightweight,scalable, distributed design review process was put intoplace that has improved our APIs and the efficacy of ourmany API designers. Challenges remain, but the API designreviews at scale program has started successfully....
On my last project I found myself revising the API surface twice as a result of doing so.
Restful service design -...
Notes on RESTful APIs - - written by yours truly some years ago
There is also this Medium post:...
and the accompanying slides:......
It documents a number of things we've learned building, using, and supporting APIs at Twilio, major banks, major hotel chains, and others. It's 100% driven by practices in the wild, not academic or theoretical info.
The docs have similar content:
I was impressed with the Rackspace Cloud API and documentation too. Especially their authentication services.
It becomes interesting once you start to use/read "hard" or "shitty" APIs. You may discover that many of them aren't either of their given labels, but that they solve really complex problems, that can't be solved (even) more intuitively.
- Good summary of best practices for documentation:
- Tips for good api doc design:-......
This page was started by a dozen or so researchers back in 2009 and has a list of publications on the subject....
A good starting point in this area is Steve Yegge's famous platform rant:
32GB, Xeon processor, 3840x2160 Touch. You can buy it with Ubuntu preinstalled.
Otherwise, Chromebook Pixel -
You should look into business oriented laptops : HP elite books, dells latitudes, Toshiba tecras. Haven't looked into them for a while now, but HP elitebooks are usually great in term of reliability (but sometimes have sucky screens)
Which thinkpad do you currently own ?
i7/xeon, 64GB RAM, 3 HDD slots, FHD to 4K 15" screen, thunderbolt and dGPU although I think the latest quadros are not currently supported on FreeBSD.
tl;dr: Even if you delete things, they will eventually reappear.
Surprise! Surprise! Facebook was recommending all the people from my deleted account magically to my newly created account which has nothing in common with my old account except for the mobile number.
For all those sharing content in FB, worrying about your privacy is pointless and a total waste of time.
My personal opinion is that, Google somehow values people privacy more than Facebook, that why its social networking attempts are failing. On the other hand, Facebook is just ruthless when it comes to handling people's data and that is why it is having much success as a social networking platform....
That news article also mentioned:......
Go to "see more privacy settings"... then look for 'Limit the audience for posts you've shared with friends of friends or Public?'. It will present a "Limit Old Posts" button.
FB is like a poorly-featured blog.
For example, if someone unliked and removed every post and/or action that had to do with goats. Would they still get suggested content about goats or animals in the same family; would they get more animal-based suggestions than someone who'd never liked goat content? Or would those kinds of suggestions drop off entirely and change to common trends?
I have not used Facebook in a long time, so I'm curious if anyone has insight into the behavior.
But if that is allowed that could be one route, getting all the elements by Xpath that are posts.
Otherwise automation with Selenium or similar could work?
Tl;dr; better footprint reduction method than delete: Replace all text posts with a single letter or word....
*...
*
*
It's also good to know the lower level concepts of directly programming an AVR:
*
*
I find some of the articles on PCB Design magazine to be useful for PCB layout.
Note that a lot of hobbyists use 'Eagle' which is free(ish) as in beer. Profession tools are $$$, though Altium offers (which I can not speak for).
Literally every job I've had has been in a country other than that of my birth - from an unofficial farmhand job when I was a pre-teen to my first QA job in Australia to my subsequent engineering role in Sweden. The positions in Australia and Sweden were both obtained via an online application followed by an in person interview. None of the interviewers or recruiters I've dealt with knew me prior to my application. So far I personally have not experienced the kind of discrimination you describe.
I do hear however that here in Sweden it is often more a matter of people who are Swedish having an easier path into management positions. On the other hand I've been asked if I would like to move toward a management path in the past, so the opportunity was certainly not being denied based on my nationality. How far I'd have gotten I don't know as I opted for a different route.
Historically, racism and slavery by the European nations started as a means of doing more business exploiting people who were precisely considered not to be people back then (notably by the Catholic church).
These intersections between racism and capitalism (and many more oppression schemes) are now well-studied, but they still exist.
In France, where nazism is slowly winning the battle on the political spectrum (with the fascist party gaining votes and the socialist ruling party adopting an incredibly authoritarian and nationalist stance), there's a resurgence of both racist and capitalist feelings :
- veiled women can be insulted on the streets, cops beat up refugees and rroma kids, many youths feel like the Jews are responsible for capitalism
- "working more for earning more", "you get what you deserve", the recent exploitative labour-law reforms
And this is not just about France, look at what's happening in the US, in the UK, in Germany, Spain, Mexico, Turkey, Japan
Everywhere, the bigots and the exploiters are allying to stop any alternative to this fucked up society.
Now is the time to stop doing business, and attack capitalism and racism FRONTALLY.
If anything in Australia, the companies I've experienced have leaned towards 457 visa workers, which I suspect work out pretty cheaply for them (and are invariably Indian).
* Edit: With strong emphasis on the hiring process. I'm not saying racism isn't alive and well in Australia beyond that.
Nepotism has been a factor for centuries; perhaps shining a light on it as the Internet is trying to do, will help people understand what's going on in a larger way.
Some might say it's too late now though.
You seems to be assuming the supply of software developers will keep outgrowing the demand for them. Why? I predict the exact opposite: As the developing world develops, local demand for software will keep outpacing global capability to create developers. I live in the developing world, I should know.
99% of people cannot play an instrument. 99% of people cannot draw. 99% of people cannot do math. 99% cannot develop software. And that's a conservative estimate.
Today's computers "Just Work", no one needs to know anything to use one anymore, and it shows. You find today people working as developers who would have a lot of trouble just using a computer from as late as 20 years ago.
Developers are getting dumber, not smarter. As abstractions have been piled upon abstractions actual programming skills have decreased. No one knows how to do anything anymore without an IDE to hold their hand and a web browser to look up everything. We've replaced the hacker with the hack.
Am I exaggerating? Try interviewing a few people for a developer position and see for yourself. The level of incompetence is astonishing. Degrees, experience or national origin seems to have no correlation whatsoever with their skills.
Well, stop thinking about it. Not only it is depressing but it is also seriously wrong.
I've been hearing that since before I started. Not only did it never happen, but it's getting more unlikely to happen every day.
It's not possible to commoditize something that 99.xxx% of people are unwilling and/or unable to do.
Yes, most people simply don't want to sit at a computer all day and/or don't have what it takes to be a decent programmer. And everyday the barrier to entry is getting a bit harder with more tools and more technologies and more abstractions appearing, each adding a bit more complexity over the precedent.
If anything, look around you and watch the race to the top for the few who can follow. There are entire companies in our industry which exist to attract and bread the best and the brightest.
---
Now, I can understand why some people would be afraid of a commodity market.
Somewhere in the world, there will ALWAYS be a guy who only has $10 to pay for whatever thing he wants done AND there will ALWAYS be a guy that will offer to do the job for that price.
That first guy will always accept the offer because he has no seemingly better alternative and he'll just burn the money hoping to get something in return. (note: ain't gonna happen. You just don't get anything real for $10).
The point being: Just because there are some guys with no money and some guys who are screwing them. That doesn't mean that it's a "commodity market", let's just call that a "scam market".
Anyone serious who wants to get the job done or anyone who can get the job done will simply NOT participate in this scam market. When we're talking real work, there is simply no commodity market whatsoever (in our field).
Rather, think of yourself as a problem-solver, who has many tools at his/her disposal, (a major) one being writing code.
This allows you to fit yourself into many different molds, rather than just a fixed position as a programmer, much like a factory worker at a manufacturer.
I personally enjoy thinking of myself as a consultant, as it allows me to focus on figuring out solutions to problems I encounter, rather than the tools I have at my toolbox. This is not always natural or easy, but a continued, concerted effort at developing this mindset has paid off for me.
In the end, we all are either a labor provider or capital provider. With the ongoing devaluation of all type of labor, instead of moving from one type of labor to another type of labor that may get devalued in the future, you should be thinking and planning about moving from being labor provider to becoming capital provider. You might want to consider exploring labor to capital conversion path.
- Maximize labor to capital conversion rate. Favor "love what you do" over "do what you love."
- Maximize storing of capital. Favor much lower spending than what you make.
- Maximize capital generation through stored capital. Favor experiences over things.
Once your capital is generating enough capital, you no longer need to focus on the devaluation of labor. You can focus on doing what you love irrespective of the value of that labor.
Anytime you feel that the future will be X, while the present is Z, you should focus on being Y.
I did this 16 years ago - I started OpenDomain years so I could give back to Open Source. I buy domains from squatters and let open source groups and non-profits use the domains for Free. I fund this all myself and have given domains worth millions today.
More:
Of course, when sharing 'vaults' with team members you have to remember that each vault is only as strong as the weakest master password of everyone on the team.
When sharing passwords with a team when using passwordSafe, we had to share the same sign-in password - not ideal.
Still use some "pattern" passwords for things I want to remember should my 1P break for some reason.
Also they have a command-line tool that I can use to copy passwords to the clipboard for SSH.
The System/Sales Engineer role is flexible enough that you should be able to move laterally into a field services function (e.g. professional services or product support), or stay in the sales function and graduate to an [technical] account manager role with quota responsibilities.
Breaking into product management/marketing or product development/engineering is generally easier at the same company because most people already know you. You'd have to convince them that you have the skills or to take a chance on you, and revealing your side project may help there (but be careful about the legal department asserting rights).
Whether your new role & function combination will require you to become a specialist or generalist is usually role-dependent. Most small companies only have a single point product for sale, tending to force everybody into specific domain specialization, whereas larger companies usually have a suite of products allowing staff the choice to hop from product to product.
Small companies and startups also need sales engineers - is that an option for you?
It is not your "official" titles but the demonstrable value you bring to your potential employer that counts. There many incompetent people out there with fancy titles - I wouldn't be wanting to hire any of them.
(2) I check my field's arXiv every other day or so.
(3) Google Scholar alerts me of papers that it thinks will interest me, based on my own papers, and it's very useful. Most of what it shows me is in fact interesting for me, and it sometimes catches papers from obscure venues that I wouldn't see otherwise. The problem is that you need to have papers published for this to work, and also, it's only good for stuff close to your own work, not that much for expanding horizons - (1), (2) and Google Scholar search are better for that.
Ok, it doesn't need to be your paper. Just find a paper that was so influential that others working on the same problem probably will cite it, and monitor the new citations.
Finding out how to identify the relevant older work in your field, finding it, reading it, and seeing for yourself how it's aged, been correctly -- or quite often incorrectly -- presented and interpreted, and what stray gems are hidden within it can be highly interesting.
I've been focusing on economics as well as several other related fields. Classic story is that Pareto optimisation lay buried for most of three decades before being rediscovered in the 1920 (I think I've got dates and timespans roughly right). The irony of economics itself having an inefficient and lossy information propogation system, and a notoriously poor grip on its own history, is not minor.
The Internet Archive, Sci-Hub, and various archives across the Web (some quite highly ideological in their foundation, though the content included is often quite good) are among my most utilised tools.
Libraries as well -- ILL can deliver virtually anything to you in a few days, weeks at the outside. It's quite possible to scan 500+ page books in an hour for transfer to a tablet -- either I'm getting stronger or technology's improving, as I can carry 1,500 books with one hand.
So, if you want to see a reddit for research, better news feeds, etc., it is the SHARE dataset that can provide that data. SHARE won't build all those things--we want to facilitate others in doing so. You can contribute at
The tooling is all free open source, and we're just finishing up work on v2. You can see an example search page, currently using v1. Some more info on the problem and our approach....
What is SHARE doing?
SHARE is harvesting, (legally) scraping, and accepting data to aggregate into a free, open dataset. This is metadata about activity across the research lifecycle: publications and citations, funding information, data, materials, etc. We are using both automatic and manual, crowd-sourced curation interfaces to clean and enhance what is usually highly variable and inconsistent data. This dataset will facilitate metascience (science of science) and innovation in technology that currently can't take place because the data does not exist. To help foster the use of this data, SHARE is creating example interfaces (e.g., search, curation, dashboards) to demonstrate how this data can be used.
Why is SHARING doing it?
The metadata that SHARE is interested in is typically locked behind paywalls, licensing fees, restrictive terms of service and licenses, or a lack of APIs. This is the metadata that powers sites like Google Scholar, Web of Science, and Scopus--literature search and discovery tools that are critical to the research process but that are incredibly closed (and often incredibly expensive to access). This means that innovation is exclusive to major publishers or groups like Google but is otherwise stifled for everyone else. We don't see theses, dissertations, or startups proposing novel algorithms or interfaces for search and discovery because the barrier of entry in acquiring the data is too high.
What should I be reading? I'm a computer science student, I want to go into a "Software Engineering" line of work. Are there any places to read up on related topics? I have yet to find something that interests my direct field of choice. Is there one on in academia writing about software?
I also like NLP and other interesting parts. Basically all practical software and their applications are things that interest me.
You're welcome to try it (not sure if the signup workflow still works; let me know). I'll be happy to hear your feedback.
Edit: you can upvote papers, and they'll float to the top just like on HN.
If there's a fundamental new result in basic CS or something like that, I figure I'll hear about it on HN or another news site.
I can imagine it's different for people actively working on new research, though.
- OSDI- SOSP- FAST- EuroSys- APSys- NSDI- SIGCOMM- ATC- ISMM- PLDI- VLDB
These days, accepted papers in specialized conferences are actually on mixed topics these days.. like you'll see security and file systems in SOSP
I hope it catches on.
Others have tried and they don't get enough traffic to get it to take off but since low levels of hosting are free, I could just keep it out there for a long time.
Karpathy's to archive email lists
Semantic Scholar (no notifications) is good for manually finding things
Google Scholar notifies you when your papers get citations... Unfortunately they don't have a way for you to get notified if the paper is not yours.. so I made a few fake accounts that add papers to the library as if they are the author and then I set up a forwarding to my email. (really wish they would just expand the notified of citations feature to your library and not just your papers but whatever)
They index a whole bunch of sites and repos to provide a recommendation engine tailored to you and your field.
[1]
I help build a product called BrowZine [1]. It's focused on researchers at an institution - academic, private, and medical especially - who want to easily track the latest research papers in their favorite journals.
If you have login credentials at one of our institutions, please login and try it out! We think it's a great way to discover what journals your school/hospital/organization subscribes to, and My Bookshelf lets you save favorite journals for later, and keeps track of new articles as they are published.
If you don't have login credentials at a supported school, you can try out the Open Access library with just OA content.
Give it a try - we have a great team trying our best to make it easy to stay up to date with your journal reading! Love to hear your thoughts.
Further more I follow other people interested in this field on twitter/google +/facebook, some of which are researchers in this field.
Moreover when a major conference's program is released I try to look into the proceedings.
You can also use the rss feeds with a service like IFTTT or Zapier to set up an alert system.
I basically just check my twitter account daily (also follow many great researchers who have twitter accounts :))...
That's a link to the various sites, blogs, updates that I subscribe to, Phronix and Ars are both a bit noisey but other than them the rest I take good care to keep up with.
I personally think it's fantastic that RSS has made such a come back (some would say it never actually went away), it' such a simple, useful tool that's easy to integrate with just about anything.
----
Another interesting discussion I enjoy having is finding out how people read / digest / discover feeds:tldr; I use Feedly to manage my rss subscriptions and keep all my devices in sync, but instead of using the Feedly's own client, I use an app called Reeder as the client / reader itself.I can see myself dropping back to a single app / service, which would likely be Feedly but for me Reeder is just a lot cleaner and faster, having said that I could be a bit stuck in my comfort zone with it so I'm open to change if it ever causes me an issue (which it hasn't).
----
I use a combo of two tools:
Feedly - feed subscription management.
Features:
- Keyword alerts
- Browser plugins to subscribe to (current) url
- Notation and highlighting support (a bit like Evernote)
- Search and filtering across large numbers of feeds / content
- IFTTT, Zapier, Buffer and Hootsuite integration
- Built in save / share functionality (that I only use when I'm on the website)
- Backup feeds to Dropbox
- Very fast, regardless of the fact that I'm in Australia - which often impacts the performance of apps / sites that tend to be hosted on AWS in the US as the latency is so high.
- Article de-duplication is currently being developed I believe, so I'm looking forward to that!
- Easy manual import, export and backup (no vendor lock-in is important to me)
- Public sharing of your Feedly feeds (we're getting very meta here!)
2. Reeder -
A (really) beautiful and fast iOS / macOS client.
- The client apps aren't cheap but damn they're good quality, I much prefer them over the standard Feedly apps
- Obviously supports Feedly as a backend but there are many other source services you can use along side each other
- I save articles using Reeder's clip to Evernote functionality... a lot
- Sensible default keyboard shortcuts (or at least for me they felt natural YMMV of course)
- Good customisable 'share with' options
- Looks pleasant to me
- Easy manual import an export just like Feedly
----
- Now can someone come up with a good bookmarking addon / workflow for me? :)
Edit: Formatting - god I wish HN just used markdown
I was in this exact position once. Fun team, fun tech, lots of freedom to experiment and prototype new stuff just in case it became useful. Supportive management and sane working conditions. $37k/year.
Leaving that place was one of the toughest decisions of my young life. I had managed to secure the biggest percentage raise they were willing to give, at the end of a long negotiation explaining the state on the ground as it was in 1998 (when much like today developers were very much in demand and could essentially name their price), but that only got me up to the mid $40s.
So I took the leap. Responded to one of the mails in my inbox and took a job for another shop in town for twice the money. Folks at the old place were stunned and saddened. I wasn't sure it was the right thing to do.
But it was. Absolutely.
15 years later, I was on an even more fun team, with cool tech, respect, and all that stuff from above, but for 10X the takehome pay of that "Dream Job" from the 90s. To put it mildly, that's not where I would have been career-wise had I stayed put.
You have a whole life ahead. Even the best thing to ever happen to you will be something you look back at as a local maxima. It's not worth leaving millions (and I do mean actual real millions) of dollars on the table just to stay someplace fun.
Float your resume today. Future you will thank you for it.
If you work for a reasonable company (and I feel most are), your quality of life is something you make happen or let happen. It is very easy to let the company guilt you into working 12 hours. Set appropriate boundaries and be in control.
You're not challenged and you're flagrantly underpaid in a great tech city. I would guess someone decent with your profile should make 2x what you're making. Think about that. Would you recommend such a job to a friend?
You need to move on. There are lots of companies as good or better as your current one, trust me. Take it one step at a time - start with updating your resume. Hopefully this will get you excited about the next steps.
When you give your notice it will be an amazing feeling. All your self-esteem will come rushing back. Good luck.
As a suggestion based on your skills, perhaps in might be beneficial to learn some machine based programming languages (like java or better yet C). You seem to have a strong background in Web development, maybe a side project working with an Arduino would help to supplement your skills and give you a more rounded Computer Science background.
2) Try to find out which accomplishments grew revenue or cut costs for the business. Try to find out how much. If necessary, take one of the sales managers out to lunch and tell them you're trying to get a broader sense of the work you do from their perspective.
With that information in mind you can get a rough sense for the company's BATNA; When you go to them in a negotiation you now know that for you to leave would mean they lose a resource that generates $450,000/yr in value for the company.
It also means you have some great lines for your resume. "...which earns $4K monthly recurring revenue" is a tantalizing way to end a scentence if it is true.
Google [bingo card creator blog] for more on this topic.
If it is the latter and you are confident that you are making a solid contribution then you could ask for a raise. I'm no expert in this area, but I've seen posts on how to go about that.
To drive home the point of just how much I loved this book, I went on to learn French just so I could read it in the original print.
Make sure it's the full, unabridged edition (1200 or 1400 pages), though!
(Just to throw in a nonfiction title as well, Bill Bryson's A Short History of Nearly Everything is a great gift for scientifically-inclined minds (esp younger ones) looking for a first foray into the world of nonfiction, wittily-written and well-narrated.)
1. Vacuum Diagrams by Stephen Baxter. When I think of epic hard science fiction, the Xeelee Sequence books spring to mind. With a story line that spans millions of years (and a few dozen books), this collection of short stories is a good introduction to one of the best and most underrated sci-fi series out there. Baxter's Manifold trilogy (Manifold: Space, Manifold: Time and Manifold: Origin) are also fantastic.
2. Foundation by Isaac Asimov. The whole Foundation series is wonderful, but this book is a landmark of sci-fi that should be on any fan's bookcase.
3. The Martian by Andy Weir. This book is what I've been giving the last couple years to people who don't think they like sci-fi. Everyone I've given it to has loved it.
4. Rama by Arthur C. Clarke. Another hard sci-fi staple. The rest of the Rama books he "co-wrote" with Gentry Lee are decent but become more space opera than hard sci-fi. I enjoyed them but many sci-fi fans find them polarizing.
5. Silver Tower by Dale Brown. More of a military thriller than sci-fi (Flight of the Old Dog is another favorite of mine by him) and terribly dated by modern standards (it was written when the Soviet Union was still a thing). But it's the first "adult" sci-fi book I ever read as a kid, so it'll always have a special place for me.
EDIT: Another one:
6. Coyote by Allen Steele. I love stories like this one: primitive, longshot interstellar exploration and primitive, first generation colonization. Especially for desperate reasons. The first two Coyote books were good, but I just can't get into any of the subsequent ones.
Oddly, a lot of people hated the various more personal aspects of the book, as you see Cliff's friends, and his life as a whole. While that's valid, calling it a flaw in the book is, I think, inaccurate. The book as much a story a story about Cliff as the shadowy hacker on the other side of the wires, and that's a big part of its charm, IMHO.
Ghost in the Wires, and Exploding the Phone are also good, and true stories.
I also semi-frequently buy (by accident) a second copy of a book that I already own. Usually instead of returning those to the store, I keep them and just give them to somebody as a gift, where the "who" depends on what the book is.
Here are some books I've given as gifts recently:
* The Knowledge: How to Rebuild Civilization in the Aftermath of a Cataclysm, Lewis Dartnell[1]
* The Black Swan, Nassim Taleb[2]
* Siddhartha, Hermann Hesse[3]
* The Happiness Trap, Russ Harris and Steven Hayes[4]
* Code, Charles Petzold[5]
[1]...
[2]...
[3]...
[4]...
[5]...
Several scifi books have also been gifted to friends, mostly Asimov (both the Foundation and Robots series), Herbert's Dune, and Clarke's Rendezvous With Rama.
Also, gifted a copy of Our Band Could Be Your Life by Michael Azerrad, which is my favorite book about my favorite bands (and the American punk scene of the early 80s). The recipient was too young to remember the scene from that era, but was open to understanding why "punk" isn't so much a style of music, but an ethos.
Every book I've gifted is because I really love the book, and really like the person I'm giving it to.
Others:
Lord of the Rings - I gave this to the guard who detained me in Russia. I thought it was the best revenge.
The life changing magic of tidying - to my partner. We're both messy. I've read it, she hasn't... neither of us have changed.
1Q84 by Haruki Murakami to the friend who lent me Wind up Bird Chronicle all those years ago and started me on the path.
[1]:-...
Edit: add Amazon link.
It is really shocking to me, that bright young people (with a bachelors degree) choose to go for a crappy paid hamsterwheel job, barely make ends meet, feel miserable at work, begin drinking/TV to cope with these frustrations and complain all day.
A few years ago I discovered that it isnt a choice for them at all. Many can't even imagine that life can could be any different than this suffering. Once you're trapped in the hamsterwheel a few years, your life is basically wasted and you're a slave to the paycheck forever. But being exposed to very basic lessons like kiosaki's early on can spark just enough curiosity to break out. Just invest a little time in yourself aside of work goes a long way to improve life situations over time. Luck is when preparation meets opportunity, not a lottery ticket.
Going entrepreneur isn't even required, but just getting paid adequately for something you actually like doing, and the confidence by being quite good at it, does work wonders to improve your daily quality of life. You just have to "get" some basic ideas and invest a little effort in yourself.
* Good Omens, by Terry Pratchet and Neil Gaiman [1]
I wish Pratchett and Gaiman had written more books together.
[1]...
It's a book I wish everyone would read, particularly everyone in a public office and the media. It's a shame that comparing politicians and their actions to Hitler has became a cliche everyone now is quick to ignore. Meanwhile there's plenty of stuff happening in the world straight from the Nazi playbook of the 30s.
Every once in awhile, I'll have a conversation with friends about finances, and they'll complain about how much work it is to manage money, and I'll go home and order them this book. It's an easy $10 gift, and they've all told me it changed the way they approach finances. Good stuff. Cannot recommend it enough.
here's a incomprehensive list in alphabetical order:
a people's history of the united states; howard zinn
a rebours; joris-karl huysmans
alcestis; euripides
apology; plato
belaya staya; anna akhmatova
die verwandlung; franz kafka
elements; euclid
epic of gilgamesh; unknown
ficciones; jorge luis borges
fractals: form, chance and dimension; benoit mandelbrot
fragments; sappho
gospels of mary and judas; unknown
i ching; unknown
la vida es sueno; pedro calderon de la barca
leaves of grass; walt whitman
letters of vincent van gogh
meghaduta; kalidasa
my life; isadora duncan
nightwood; djuna barnes
oku no hosomichi; basho
one piece; eiichiro oda
poems; emily dickinson
relativity: the special and general theory; albert einstein
saga; fiona staples and brian k vaughan
the brothers karamazov; fyodor dostoyevsky, translated by constance garnett
the first third; neal cassady
the power of pi; stickman lagrou graves
the secret life of salvador dali; dali
the way of a pilgrim; unknown
twelth night; william shakespeare
thing explainer; randall munroe
ulysses; james joyce
women, race, and class; angela davis
if you want a quick description of any i enjoy talking about them, and i appreciate suggestions
It's my grandmas favorite non-fiction and she's read over 1000 books. She gave it to me and it sat on my shelf for months because the title wasn't appealing and I'm not a big book reader. Since I read it, I've now bought a second version of this book and give it to friends to read.
It's a technical write-up about Love in the general sense. Fromm pitches the idea that love is an art rather than a feeling.
I highly recommend the read. This book discusses the topic in a serious and insightful way.
It is a great little book, which deals with how we handle change in our lives (work and other) and how we sometimes fail to see, when it is time to move on.
My favorite one-sentence takeaway from the book is the question: "What would you do, if you were not afraid?" - which has helped me make hard decisions many times over the years....
Many of my friends are straight out of university, and it's a period where most people seem to start asking existential questions. The two books which have affected me greatly (and which I regularly give as gifts) are:
* Meditations by Marcus Aurelius* Man's Search for Meaning by Viktor Frankl
Stopped smoking six years ago and haven't had the desire to start again since. it feels great.
I actually played the nintendo DS adaptation of the book, which was also available on ios for a while.
it turned all the points the book was trying to make into a series of minigames that really illustrated the principles beautifully.
It's still my favorite book on business, a short easy read filled with anecdotes from his time running CD Baby. The situations are ones I keep encountering myself running a small business, and the way the stories are written makes them highly memorable & applicable. If I can't decide between opportunities, I remember "Hell Yeah! or No." If I'm working on fraud screening, I remember "Don't Punish Everyone For One Person's Mistake". When working on an MVP and feel it isn't big enough, I'm reminded of "Start Now. No Funding Needed." And it has my favorite twist ending in business.
It's the first book I've specifically bought multiple copies of to give away, including to clients.
It opened the doors to the remote lifestyle for me and led me to switch to careers to tech (due to the abundance of remote opportunities) and to embrace a new kind of lifestyle....
* Perennial Vegetables by Eric Toensmeier--eye opening list of vegetables that come back year after year
* The Hard Thing About Hard Things, by Ben Horowitz. Somewhat presumptuously, I bought multiple copies and sent them to some of my friends/acquaintances that were CEOs.
* Climate Wars, by Gwynne Dyer. This mix of fiction and non fiction really brought the climate change crisis to my attention.
[0] -...
The four I remember gifting were Asimov's entire Foundation series, Joseph Conrad's Heart of Darkness, The Phantom Major by Virginia Cowles and See you in November by Peter Stiff.
Set in a mediaeval China that never existed (but should have), it's the story of how village peasant Number Ten Ox and the ancient sage Master Li (who has a slight flaw in his character) go on a quest to save the children of his village from a plague which can count... and the other quest which they find themselves part of.
On the way you'll learn how to make a fortune with a goat, how not to cook porcupine, the best way to move rocks using only a corpse, why you should always be polite to ginseng, and the true meaning of courage. You'll meet ghosts, monsters, and gods --- and they're typically less bizarre than the human cast, which contains such jewels as the Ancestress, Miser Shen, the Old Man of the Mountain, Lotus Cloud and of course, the inimitable Ma the Grub and Pawnbroker Fang...
It's by parts hilarious, touching, gripping, and there are parts that will make you cry from sheer beauty. Read this book.
Admittedly, it may be a bit below the reading level for the average user here but I can't recommend this book enough. Especially for those of us that sit in front of a computer all day. Take a look at the reviews at Amazon which are numerous and nearly unanimous. Do yourself a favour and give it read.
It's a relatively short book and it's focus is on college fraternities (which is what I was in when I first read it). I bought about 20 copies and handed them out after reading it. While it has nothing to do with software development I have found it's core message to be applicable to working on a team. The core message is you can normally divide your organization up into 3 categories, these will not necessarily be equal in size. These categories are the highly motivated "top" go-getters who will do everything they can to help further the org, the "middle" who with the right motivation can work just as hard and be just as driven as the first group, and the "bottom" who rarely make more than minimum effort if that and are extremely unlikely to go out of their way for the greater good of the org. The book suggests to more or less ignore the bottom and spend your energy on "motivating the middle" to use them to their greatest potential. It says that spending your time on the bottom is a fruitless endeavor and will only result in alienating the middle people who are somewhat on the fence.
Now this applies much more to a community-run (in this case student-run) organization where letting someone go is often off the table (in greek life removing a brother/sister can be a much bigger challenge than one might assume). I do not bring any of this up to debate the pros and cons of greek like of which there are many (you can talk to me privately if you wish to do that), but just to bring some clarity to what I'm trying to say.
Often as an employee not in a managerial role you are in a similar situation and while I'd be a lier if I said I always applied this logic but I do try to always remember that being annoyed/angry with under-performers is, in all honesty, a zero-sum game. It's best to focus on what I can do to make the place I work better and work to bring the "middle" to want the same.
It's probably not the best book to bring up here but it's really the only book I'd ever bought for more than 1 person (and the only one that I didn't by for purely entertainment/enjoyment reasons, I've gifted fiction books on a number of occasions).
[0]-...
It's ground hog day, but on a lifetime scale. The search for happiness and what it means to be happy.
Peopleware: Productive Projects and Teams (3rd Edition)...
Biz - the Personal MBA - Josh Kaufman -
Org - the Fifth Discipline - Peter Senge -
SciFi - Perdido Street Station - China Mieville -
Parenting - The Continuum Concept - Jean Liedloff -
The Black Swan by Taleb
Thinking Fast & Slow by Kahneman
Guns, Germs, and Steel by Diamond
The World According To Monsanto by Robin
The Organized Mind by Levitin
The Vital Question by Lane
Life Ascending by Lane
Chasing the Scream by Hari
Anything By Gladwell.
[1]...
(Edit: I just looked at the Amazon page and realized the book seems to cost about $200 used -- can that be true...?! I think I paid $30 for it. Maybe I should have kept it.)
The Dominant Man: The Pecking Order of Human Society...
__ Completely changed my perspective on social interaction. I've been trying to get people to read this but the title sounds very non-pc. Got it for 1AUD on a second hand book table somewhere, it's very dry though and mostly just presents evidence without drawing conclusions.
Cat's Craddle - Kurt Vonnegut__ I love the word Karass. Lots of travelers like this book.
When Nietzsche wept__ Amazing book, the amount of strategy in their conversations is amazing and the book is just high quality. Best to know some stuff about Nietzsche and that era before you read it though.
Teach us to sit still - Tim Parks__ Not something you'd give to anyone but if the person is a little intrigued by meditation then this book will probably get them to start doing it.
Why the West Rules for Now: The patterns of history and what they reveal about the future__ I had learned the history of certain periods in certain locations but this book brought it all together into a cohesive narrative. Highly recommended if you want to start inquiring into history but don't know where to start.
Carlos Castaneda's series on learning shamanism__ I dunno what to think of this. I can believe that the guy actually experienced what he's writing, it's just too much to make up imo. Anyway I'd recommend it to anyone interested in philosophy, religion or meditation because it's just such a radically different perspective on how to live life and the meaning of enlightenment.
--
I also have a long list of books that I've seen recommended here or recommendations from people I've met all over the world that I use for inspiration when I need to give gifts for Christmas or something but I haven't read them yet so I won't mention them here.
One of the most welcome gifts I've ever bought. One friend told me he had rediscovered the pleasure of reading; another read the full Masters of Rome series shortly after. Really good feedback.
Terry Pratchett's Night Watch is also one of my favorites to give. Although when asked if it is the first of a series people tend to be somewhat surprised by the answer: I send them a graph spanning all the Discworld books[1]. Night Watch is in no way the first but I've found it to be a good starter and the order is not that important in Pratchett's books.
Hermann Hesse's Siddhartha. Already mentioned by someone. Some translations have an incredibly lyrical prose, but you've got to be careful with the one you buy.
[1]...
I've given probably 10 copies to family and friends with kids and it's been universally liked....
Humor: Furiously Happy by Jenny Lawson. I've recommended this to many friends who needed a good laugh. I don't remember another book that made me laugh so hard that I dropped the book.
Non-fiction: this one's a tough one because many good books are mentioned already, but two that I really enjoyed and have recommended in the last year are: Boyd by Robert Coram and How the Other Half Banks by Mehrsa Baradaran. Boyd tells the story about a brilliant but petulant air force pilot who rewrote the guidelines of US military aviation. How the Other Half Banks is an eye opening account of how broken our banking system is and the history of how we got to where we are.
Business: again, a lot of good books are mentioned already, but two I've enjoyed are Smarter Faster Better by Charles Duhigg and Never Split the Difference by Chris Voss. Both are fascinating books that'll leave you thinking about how to improve your own game.
--Edit--
Bonus: When Breath Becomes Air by Paul Kalanithi is a tremendous piece. It's a short read but a must read!
This book contained so many great insights into how to deal with life's stresses and has been a revelation in my transformation of attitude.
[0]
Just kidding. I did give a friend The Go Programming Language by Donovan & Kernighan, though
It's focus is to get people thinking about 2nd and 3rd order effects. It's very simple and well written.
Shameless plug -I posted a summary here:...
* Persepolis, first version
* Dark Angel, by David Klass
I've just started reading "Flowers for Algernon", I guess this can also be a good birthday present. I think gifting books is something very difficult, in my experience I never wanted to get books for present.
1. The Tibetan Book of Living and Dying by Sogyal Rinpoche, for those spiritual minds. I am a huge fan of this book, I am traveling this week to Dharamshala to learn about Buddhism after reading this book.
2.Think and Grow Rich by Napoleon Hill, for those aspiring young minds.
3. Into Thin Air by Jon Krakauer, for my adventure loving friends. I had an intense desire to see Mt.Everest after reading this book, I traveled to Everest base camp.
4. Bhagavad-Gt As It Is by A. C. Bhaktivedanta Swami Prabhupada, for everyone, I don't remember how many I have gifted.
5. Imitation of Christ, I have gifted it, but haven't read it myself. It's in my list.
6. Siddhartha by Hermann Hesse
Of the top of my head some books I gave my brother included Salt, Siddhartha, and Shantaram. There were others that didn't start with an S as well.
The Emperors New Mind - Roger Penrose
Godel, Escher, Bach - Douglass Hoffstadter
Brocas Brain - Carl Sagan
The (mis)Behavior of Markets - Benoit Mandelbrot
The Black Swan - Nicholas Nassem Taleb
Fiction
Gates Of Fire - Stephen Pressfield
Neuromancer - William Gibson
Snow Crash - Neal Stephenson
Hardwired - Walter Jon Williams
Altered Carbon - Richard Morgan
Red Mars - Kim Stanley Robinson
Space - Stephen Baxter
Enders Game - Orson Scott Card
Skeleton Crew - Stephen King
I've given away a lot of books. I'm old.
I and my kids have enjoyed all of Graeme Base's books, but The Eleventh Hour is particularly good and have given it to many kids and adults:
I am also thinking about giving Yertle the Turtle By Dr. Seuss out to anyone I meet before the election: have given many Dr. Seuss books away as well.
It's beautiful.
The Thrilling Adventures of Lovelace and Babbage: The (Mostly) True Story of the First Computer
(... )
It's a halfway house between a graphic novel and a proper book, and is written in a very entertaining way. I can thoroughly recommend it for anyone who is interested in Computer History, and normally struggles through dry tomes of non-fiction (which this is most definitely not!)
All students should realize that history is written by the "winners" see US history from the perspective of the oppressed - Native Americans, slaves, women, the poor.?...
Had a run-in with serious burn-out about 12 years ago and had considered leaving software entirely and starting a landscaping business. This book was inspirational in that it helped me figure out what I might LOVE doing, and then made me realize it was right under my nose the whole time. I just needed to get a new job that appreciated and challenged me
* Ulrich Haarburste's Novel Of Roy Orbison In Clingfilm
Also had a strange case of loaning out C# 4.0 in a Nutshell and never getting it back, but I would do it again (with an updated version). Albahari is good at writing a reference without being too boring, and C# has some legitimately interesting sides in how it does some things, like it's dynamically compiled regexen.
The Martian by Andy WeirI very much enjoyed the story and how it was all approached.
Seven Eves by Neil StephensonSimilar to his other books (Snow Crash and Cryptonomicon) I've gifted these a few times. I really enjoy his method of storytelling and his stories appeal to the geek in me as well.
Speak, Memory, Vladimir Nabokov. The pinnacle of the memoirist's art. I find it nearly uncreditable, Nabokov's facility with English, his 5th language.
Lyonesse, Jack Vance. Vance is the greatest stylist in 20th century American letters, and Lyonesse is probably his greatest achievement. Fantasy indebted to Celtic mythology, not Tolkien. Marvelous, poetic, pungent language in service of a wonderful story.
This is the autobiography of a woman who grew up on a farm in British East Africa (Kenya) in the early 1900s. She eventually became a bush pilot and the first person ever to fly an airplane solo across the Atlantic Ocean from east to west. It is a beautifully written and interesting story. Note: if you decide to read it, skip the Forward because it sort of spoils the book. Come back to it at the end, however, because it provides some interesting historical context.
Rework explains the "life beyond work" and "make a dent in the universe" philosophy behind Basecamp and Rails and is a valuable counterpoint to the popular media narrative of the startup IPO mindset. The book also explains how to apply the philosophy with actionable examples and it's fun to read.
[Rework]:
and they tell me it makes a difference to their lifestyle
Obviously this is a selection for someone who likes to read serious nonfiction and is interested in the science of climate change and what we might be able to do about it.
I've mentioned the book on HN before and got an unenthusiastic reception, but I loved it. The author does an excellent job avoiding both knee-jerk skepticism and knee-jerk credulity, and it's so well written I could hardly put it down.
Poor Charlie's Almanack - It's one the books that Warren Buffet always recommends. I gotta say though that I don't get why. But it makes a good gift since it has good "coffee table" value because of the many illustrations.
Intro to programming in Python - I don't remember which one though. I think it was one of the O'Reilly ones.
The title is a bit provocative but if you're looking to move from the US to another country it's a great place to start. I've given it to a couple of footloose people in their twenties who wanted to move abroad but were intimidated by dealing with visas and expense. (Remember, not everyone works in fields where countries are clamoring to give out visas!)
The Elements of Typographic Style by Bringhurst (design) - Most designers I know already own a copy, but interesting for laymen.
The Little Schemer by Friedman & Felleisen (programming) - Fun and educational for anyone interested in programming, at just about any level.
My favorite sci-fi story, I might even admit it is my favorite of all stories. I've given it as a real book but the experience really benefits from the e-reader format because, at least for me, there were many terms to look up and many sections that I wanted to notate for consideration later. It's a challenging book but a very thoughtful and rewarding read. Highly recommended.
Also disappointed that George Saunders didn't make the list. His essays in The Brain-dead Megaphone are great and his short stories, especially Isabelle and others is The Tenth of December, are heart-warming.
"Is God a Mathematician?" by Mario Livio
It is a wonderful exploration and history of math, science and light theology (mostly historic though. the book is written by a mathematician).
I still wonder frequently if math is human made up thing or is it innate. Is the universe inherently mathematical? Can we prove it?
* High Output Management by Andy Grove
* Turn the Ship Around by David Marquet
* The Score Takes Care of Itself by Bill Walsh
For interns I give out these two books:
* The Pragmatic Programmer...
* The Passionate Programmer
Great story and so well written by Werfel.
Truly a phenomenal story IMO
or more recently,
Tamalpais Walking: Poetry, History, and Prints, By Gary Snyder and Tom Killion
and
Quiet Light, by John Sexton
or
Places of Power: The Aesthetics of Technology by John Sexton
Available in PDF now too:
It has all of science fiction classics, but focuses on a guy who can live forever and attempts to experience everything. Of course this leads to some strange events, and is definitely worth a read.
A novel that tells how to manage IT department in a very enchanted manner. The situation entailed in the story is too real. I had some many "I have come across this shit before, wish I handled it better" encounters that I couldn't put the book down until finished.
[1]...
I've given it away seven times & purchased it eight.
Like every book, it's different from the movie. I'm not going to say it's better than the movie, but I'm also not going say the movie is better either. Both are just so amazing in their own right that I adore them both.
Mainly because I think the book has so much great quality photo essays, worth keeping it for a long time, sit down, flip it through from time to time and enjoy the beautiful stories.
[1]......
I don't think it's possible to read Siddhartha without coming just a little bit closer to enlightenment.
I really like Huxleys way of waving thoughts on psychology and philosophy into a story and specially liked it in this novel.
Since this was discussed here recently (in sad circumstances), I'll just say that everyone who might be involved with kids, either as an educator or parent needs to read this book. And it was great to read when I was a kid, too!
Madelaine l'Engle's A Wrinkle in Time. A quite profound children's book with lifelong impacts.
Frank Herbert's Dune introduced true complexity into storytelling for me....
James Burke's books Connections and The Day the Universe Changed, and their accompanying television series, were a profound introduction to the history of technology, science, ideas, and philosophy. Though 30+ years old, they remain highly current and relevant....
Jeremy Campbell's Grammatical Man (1984) introduced the concepts of information theory and their deep, deep, deep interconnections to a tremendous number of interconnected systems, many not explored within his book. Darwin's The Origin of Species, James Gleick's Chaos, and many of the works of Santa Fe Institute members, including John C. Holland, J. Doyne Farmer, Geoffrey West, W. Brian Arthur, David Krakauer, and Sander van der Leeuw, continue these themes.......
William Ophuls' Ecology and the Politics of Scarcity (1977) is perhaps the best, most comprehensive, shortest, and most readable exposition of the fact, reality, dynamics, and interactions of limits on the present phase of fossil-fuel fed economic growth I've found. This is a book I recommend not only for the message, but the author's clarity of thought and exposition, his meticulous research, exquisite bibliographical notes, and, given the nearly 30 years elapsed, testability numerous of his predictions, some failed, yes, others uncannily accurate. Rather more the latter. In a similar vein, William R. Catton's Overshoot looks at the ecological dynamics in more depth, with much wisdom, the writings of Richard Heinberg cover the ground of limits fairly accessibly and more recently. Vaclav Smil in numerous books addresses technical factors of the profound nature of the past 250 years, and implications for the future. Meadows, et al, in Limits to Growth set off much of the post-1970 discussion (though they're hardly the first to raise the question -- it dates to Seneca the Elder),............
Though hardly pessimistic, Daniel Yergin's book The Prize (and TV series) impressed upon me more than any other just how much petroleum specifically changed and transformed the modern world. Though intended largely as laudetory and championing the oil industry by the author, my read of it was exceptionally cautionary. The impacts on business, everyday life, politics, wars, industry, and transport, and the rate at which they occurred, are simply staggering. You can continue this exploration in Vaclav Smil's Energy in World History (1994) (I've recommended Smil independently elsewhere), and a rare but profound two-volume set I'm currently reading, Manfred Weissenbacher's Sources of Power: How energy forges human history (2009). The shear physicality of this book speaks to the message -- it's divided into five parts: 1) Foraging Age (6 pages), 2) Agricultural Age (156 pp), 3) Coal Age (160 pp), 4) Oil Age (296 pp), and 5) Beyond the Oil Age (142 pp). That is, the ~2 million years of pre-agricultural existence are little more than a footnote, the 8,000 years of agriculture roughly equal to the 150 years of coal, and the 100 years of petroleum use roughly twice either. The oil and post-oil ages comprise their own volume. Yergin followed up with The Quest, continuing the search for oil, though I've been less impressed by it.-............
Adam Smith's An Inquiry into the Nature and Causes of the Wealth of Nations is among the most-cited (and most incorrectly cited), least-read books of high influence I'm aware of, outside religious texts (and perhaps it is a religious text to some). The author's message has been exceptionally shaped and manipulated by a powerful set of forces, quite often utterly misrepresenting Smith's original intent. Reading him in his own words, yourself, is strongly recommended. I'd also recommend scholarship particularly by Emma Rothschild and Gavin Kennedy, though also others, on Smith. Contrast with the portrayal by the propaganda disinformation front of the Mont Pelerin Society / Atlas Network / so-called Foundation for Economic Education, and much of the modern American Libertarian movement (von Mises, Hayek, Friedman, Hazlett, Rothbard, and more recently, Norberg). Contrast The Invisible Hand (1964), a compilation of essays published by Libertarian house Regnery Press in 1966, at the beginning of the rise in public use of Smith's metaphor to indictate mechanism rather than an expression of the unknown.
There are numerous editions of Smith, I believe the Glasgow is frequently cited by Smith scholars:-......-.........
I'd like to put in recommendations on technology specifically, but am still searching for a good general text. The material's covered somewhat in the chaos and complexity recommendations above (Campbell et al), though I'd add Joseph Tainter's The Collapse of Complex Societies. Charle's Perrow has several excellent books including Normal Accidents and Organizing America. I'd like to reference something concerning Unix, Linux, and programming, perhaps Kernighan and Pike's The Unix Programming Environment, Linus Torvalds' Just for Fun, Richard Stallman's The GNU Manifesto, and Steve McConnel's Code Complete. The O'Reilly book Unix Power Tools also encapsulates much the strength of the Unix toolset. All these are somewhat dated....-...............-......
to my college best friend as a birthday gift.
I was surprised to find out how old this text was. It hasn't aged a day!
I can't recommend it enough.
Since its such a great idea, but uses mostly off the shelf parts and doesn't require much specialization, its a perfect target for them.
Look at the patterns: They quickly cannibalize and eventually completely commoditize the market for easy-to-copy products by flooding ebay, amazon, aliexpress, etc with comparable but cheaper items, some of which are probably going to be made by your own supplier/factory in China. Eventually the best of these these get on Engadget or Gizmodo and that's it.
Examples: Android tablets, Google Cardboard, Android Phones, Phone Batteries, etc.
Certainly many will have inferior packaging and engrish manuals. But some will be good enough or better than your product... I would be terrified to base a business around this type of item.
I have an Android tablet (Samsung Tab Pro - the 12" beast). An experiment at replacing a laptop on some outings. I bought the A$140 Logitech keyboard / cover, which is good but not great, with some keys being a bit recalcitrant.
Some UI features are frustrating (example: alt-tab brings up the alt-tab switcher - you need to alt-tab twice to move to the most recent process, and toggling between two or three apps on the top of the stack is a common use case for me if I'm trying to do Real Work). An Android problem, I concede.
Given that context - how good is the keyboard, and how are you shipping keyboard + screen at less than a Logitech keyboard - I know, retail, scale, brand mark-up, two years later, etc ... but nonetheless?
Does the app smooth out some of the frustrations (f.e. the alt-tab problem) of working with Android with a keyboard & mouse as though it's a real grown-up DE? Is the app going to offer an increasingly customisable experience, or does it defer to the phone's native Android (and skins) features?
How does it feel - I know you're biased, but have you tried some phones that it just doesn't work on, and/or have some benchmarks or recommendations? I'm on an original Nexus 5 - which still performs adequately, but with low expectations on a phone interface - how well would it drive the Superbook?
PS, would love that it was backlit, that is literally the only complain I have with my Asus UX305CA
Cleaver way of docking the phone! (Especially the option to slide it in under the keyboard.) I wish you could do something similar :)
Can I enter directly to the phone with the keyboard? Does the phone screen show on the large screen without Andromium? Is the large screen a touch screen?
Even more important -- if I have a rooted/virtual machine instance of a standard Linux distro running on my smartphone, can I use that? Do I have to use Andromium if I have a setup like a rooted chromebook? Turning the smartphone into a laptop it seems the biggest limitation would then be the app store. I don't want it to "feel" like a computer. I want it to be a computer -- OS and all.
One final question. What is your privacy policy, open vs closed source and permission requirements for Andromium and why?
This is a great idea, but I am raising a serious eyebrow at the Andromium aspect of it.
Video extension for multiple monitors. For example the ability to plug my phone into a dual monitor setup for coding.
A 13" primary monitor.
Touchscreen on the primary monitor for those annoying times when you forget it's not touchscreen.
USB ports on the device so I can plug in a wireless mouse and keyboard.
Standard Linux OS virtual machine or rooted a la chromebooks.
Then I would carry my phone between home and work and plug it in both places. No more need to carry a laptop. You could pick one of them up and take it with you for travel. That would be beautiful.
I currently tote my 13" laptop around and plug in an extra monitor and wireless usb mouse/keyboard at the endpoints.
Can Superbook do that, with any combination of commodity cable adapters?
I want to turn a large self-assembled home computer into a laptop, not just my phone. That is, something with a powerful processor and dedicated high-resolution video hardware. I think you probably know what I'm getting at, here. I want to put my feet up and play 3D games with WASD+mouse, without juggling all the human interface devices in my lap or building my own custom swing-arm stand for them. Right now, I can handle a regular laptop and wireless mouse, but if the monitor is not affixed to the keyboard, it all falls apart. More specifically, the monitor falls over.
So will Superbook be able to connect with DisplayPort/HDMI in addition to connecting the human interface devices through USB? If not, extra bonus stretch goal?
Not an Ubuntu touch expert, but would it be compatible? Just plugging it in and have what ubuntu want to reach? a complete linux distro on the go?If not, are you able to support it?
On a related note, will you have a well-defined API for other apps to have first-class support for this thing?
I think that's everything... ooh! ooh! No it isn't!
You said that the superbook would be suitable for coding. so will you provide any of:
1: A terminal emulator
2: An X Server
3: Emacs
Thank you for your time.
When doing web development the browser dev tools are indispensable. Is there any possibility to run a full desktop browser on an Android phone to get those tools? Or some other way to inspect elements, live edit CSS properties, debug JavaScript etc.
I'm tempted to back this but I'm in the middle of a move and some personal expenses so I'm trying to be good and conserve money right now, so it'd be nice to know that the Kickstarter won't be the only opportunity in the next year or two to get this.
Its and old article though...
After some sleep, my goal is ready, for example testing a product, and when similar-type things get upvoted.
This depends a lot on niche, I think.
For Ask though, I always visit it when also visiting the homepage, as a lot of interesting questions get posted. Perhaps for Show an optimal time is more critical?
In contrast, this got 390 upvotes and made the front page:
I have gotten articles onto the front page. My experience with that suggests it has little or nothing to do with when you post. It is mostly about posting something good.
1. Couchsurfing. Travelers and hosts are everywhere and many of them love to share their experiences. I messaged different people whether they're up for a coffee/ beer and met their friends. It didn't take long until I was part of their social circle and met amazing people.
2. User groups. I've been a Python developer for a long time and in the bigger cities there is almost always a user group - even if it's just students looking for help with their exam preparation.
3. Sports. I don't have to mention how important it is to stay healthy and fit. So I checked out a local boxing club. Enjoying sports (IMO especially contact sports) with others creates some special kind of friendship.
All of these points (plus the obvious social interactions with coworkers) helped me a lot to get set in this city, but also find travel partners and improve my Spanish. All you have to do is bring yourself to go out and talk to as many people as you can. After all, they're all different and you never know what you get.
Friends as in people you hang out with during your down time? That's beyond me. I'm afraid. I only manage to befriend old people.
2) Sports. Rec league. Just sign-up and play. You get to meet random people if you never pick your team and just get assigned. After a season or two you'll know who you want to play with. Organized play can be better than pick-up games (depending on where you are) because you'll see the same people regularly and have a chance to actually get to know them. Invite them, or accept their invitations, for food or drinks after the game.
3) Church. Unless you're vehemently atheist or have some other fundamental issue with the churches available in your area. Stick around after service, enjoy coffee and donuts, they usually have social and outreach organizations. You don't have to be religious, though you may get pestered about why you don't go to the Bible study, easy to deflect (IME).
4) Bars. Someone else said this. One thing to avoid, if you're feeling particularly lonely/depressed, don't do this. But otherwise, if you can find a nice small bar (not a sports bar, they tend to be too noisy), and sit at the bar. Get to know the bartender, talk to them, there will be other regulars. It's kind of fun too, you may not make as many friends, but I met a guy that was visiting here studying Native American tribes (archeology) from Oxford. Cool random conversations you can have sometimes.
5) Invite people to things. One thing to realize about life, at some point you have to take charge or things won't happen. If you find yourself not being invited to movies, sports, trivia, parties, potlucks, whatever, do the inviting. Get a small group, encourage them to invite their friends. Keep doing this. You can control who you invite so after a while you can focus on the ones that you're actually becoming friends with.
What sort of worked for me the most so far, are various "international" meet-ups/communities, like Couchsurfing (they now have this feature called "Hangouts" where you could hang out with locals and travelers in real life) but those of course are a bit farther from "locals" and more into expat/traveller scenes.
Also, I believe, going to bars works as well. But you need some calm, cozy and compact places (not the crazy/party ones). Craft beer places work good in my experience also some "artsy" venues.
You can also go to meetup.com and find stuff you're interested in.
Bars are fun, I guess, but usually people go with groups so meehhhhh.
2. Participate in recreational activities suited for small groups, such as dance, rafting, backpacking
3. Join a local hackerspace
4. Practice the art of disinhibition
I quit my job the next day.
This was the beginning of the end. Like with all drugs, there is a slippery slope. You start with marijuana, and you move onto heroin. In my case, I graduated to:
"Formal Methods of Software Design":
After that I read:-...
Now in general I am quite depressed:
* I am very judgemental and look down upon most HN posts, especially the ones that praise Alan Kay, natural language programming, or view programming as a "craft" rather than a "science"; my favourite HN feature is the "hide" button
* I am disappointed with my math education, and tired of all the rabbits being pulled out of hats in my textbooks
* I wish I had enough will power and discipline to write a programming language that is nothing more than predicate calculus, but I don't
I foresee that as a result of these readings, I will die alone, sad, and depressed...oh AND penniless.
I wish I was joking.
That's a pretty huge impact.
Followed by sam carpenter's work the system. I think if you're a programmer trying to make it as a business person those two books are the most invaluable.
Edit: about the how part.. Before reading and understanding these books I was always in a kind of firefighting mode. It was like a constant pain in the neck that something was somewhere needed me. Sure i was making money but I was not enjoying it and felt stressed all the time. Plus I wasn't scaling my business because of the constant need of attention from everything. Then I learned the systems thinking and it all started to change.. It was like I felt I had wasted 10 years of my life being stupid before. I'm telling you these two books can forever change your life both professionally and personally if you aren't already doing it.
I am a non CS guy who learnt C++ programming in order to do simulation for my final year project in mechanical engineering. I ended up creating a wonderful GUI (MFC) simulation complete with the diagram of the engine etc. For the next 5 years or so as a freelancer developer assisting professors and the like, I created pretty hot shot applications with nifty graphics, UI etc. I began to see myself as a master programmer and thought how easy it is for CS guys compared to Mech guys. Then I picked up this book. I had never known any of what it talked about. The very first example of union find was a revelation. My ego was completely thrashed. I was thoroughly humbled.
As for non technical, it would be The Count of Monte Cristo. I first read an abridged version of it as part of high school curriculum. As a young teen, I was instantly enamored by revenge and adventure. I still long to own a yacht and sail the oceans, if not get imprisoned, or find a treasure, or kill people. I am reading it again at bedtime and Dantes just got locked up at Chateau d'if.
At the risk of being ridiculed, I'll venture to say this: There's a big part of us that we don't fully know. All of us are trying to different things to find happiness. Above book proposes that Meditation has answers to most of the questions and talks about various Yogi's. This triggered a deep desire for me to know more. I learnt Meditation from a different organization and am very happy at where I am. This book started that journey.
Warning: There will be a bit of mysticism in all this. Take what your gut says and leave the rest.
[1][2]
Convinced me that I absolutely wanted to do backbone ISP network engineering on a grand scale. It's taken a while to get to the level of knowledge where one is trusted and confident working on circuits that can take whole countries off the internet if you fuck up, but very much worth it.
I read it every few months, and I have gifted it to family and friends, and most of them loved it as well.
Its not the writing, nor the story per se that stand out, its not just about how it beautiful highlights and highs and the lows of the Johnss symbiotic relationship and their accomplishments, its not even about how their skills, strengths and weaknesses play into their success and failures (which I am sure is typical of most co-founders stories).
Its about empowering the reader to believe that everythings possible, and how smart, hard-working people can build technologies that affect the lives of many.
This book works wonders for when I am going through burn-outs, or I am not motivated enough to pursue a problem or a project. When I am done reading the book, I am excited and eager to get back into the game. I cant recommend it enough.
My 3rd grade class had a set, and I devoured each one. They turned me into a nerd thanks to a teacher who told me to never stop reading.
I did my first reading in high school and it was absolutely brilliant. I never expected so many twists and turns where characters melt into one another and plots jump from world domination conspiracy theories to self discovery and awakening.
Decades later, I am now looking more into Robert Anton Wilson's other work (in particular Maybe Logic) and am seeing some very interesting applications, especially in software quality and artificial intelligence.
Edit: I also want to mention "Language in Action" by S.I. Hayakawa. I read it too recently to say that it has had the most impact on my life of any book, but it opened my eyes to orders of magnitude more cases of imprecision in our language than I had ever noticed before.
On a professional level The Mobile MBA by Jo Owen, because it explained to me - the programmer - valuable management skills in no bullshit way (I can not stress this enough), thus allowed me to grow in my career.
It showed me that the questions I'd always had were real, and finally let me break free :)
- Discourse on the Method [1], to become a healthy criticist of everything (perfect for your 15's-20's development)
- Beyond Good and Evil [2], a definition of the 20th century craziness by the crazy genius Nietzsche (perfect for your 30's burnout)
- The Praise of Folly [3], to realize that life is just a game (perfect for your 40's post-burnout rehab)
- Propaganda [4], because you want to play the game too (perfect for your 50's meteoric rise to fame & success :).
[1]:
[2]:
[3]:
[4]:
Siddhartha by Herman Hesse [2] for contributing to helping me come out of excessive questioning of everything (philosophy) to science that helps towards actually answering the questions answerable.
Feynman Lectures in Physics [3] and Surely You're Joking Mr. Feynman [4], with no need to explain "how". :-)
The Ghost in the Atom [5] for explaining varied views on the nature of science, especially Quantum Mechanics, and what goes in the minds of the top-notch scientists working on these problems.
Parsing Techniques by Dick Grune [6] for teaching me the fundamentals of computer science and helping me proceed with my deep interest in Artificial Intelligence.
[1]...
[2]...
[3]
[4]...
[5]...
[6]......
I crafted my first computer from cardboard :) and learned to type and code using hand drawn keyboard :)
It helped me realize (along with other things), that no, the world isn't getting worse. Things are much better than they've ever been for most people, and they're only getting better, faster.
Edward DeBono...
This is the book that inspired me to start in the world of business.
because the pace of half the book so closely resembles my life, decisions, alternative histories and the limited time we have in the world. not sure how much more I can say without spoilers.
I've been obsessed with productivity and mindfulness ever since.
I think this is a false sense driven by HN and the like. Startups playing with new things made me feel that my Java centric knowledge was outdated. They would say, "look at the scale we achieved with clusters of Node and Mongo." When I looked at what they were doing, what they actually produced the sheen faded. A generation spent on ads.
Then I turned my attention to a problem that I have and to another faced by my clients. This gave me clarity. Stay aware of new tools and techniques, but realize they are just tools and techniques. Don't lust after them. Rather look how and if they can be applied to your problems. Look if they are a better fit. See if they can help you achieve your goals in a compressed timeline. Then dig in.
As for teams and deadlines, that is not really a matter of tech. Poor teams occur even in the newest tech. I've seen people totally misunderstand, at best, and squander Hadoop and its tooling. I've seen systems that used proper decoupled design rot into a quagmire of failure due to people not reading about software architecture or the tools in the stack. You have to power through this. In such situations, I've seen first hand that people want leadership even if during the process of asserting that they despise you.
Here's what I learned when recovering from burnout (it took a year): the reason you do something dramatically impacts whether you're able to enjoy doing it. This is why being a prostitute is not the best job ever. I recommend to all of my artist friends that they find a job that pays the bills so that they can do art on evenings and weekends. This prevents them from coming to resent their art as necessary to live. Why do we let our need to buy things strip away the joy from things we enjoy most?
I do want to say that it's not your lack of focus which is the problem. It's good to be curious and try new things. There are some people that thrive because they spend their lives being the best at one thing, but many of us are valued because we're really good at a lot of different things.
Make sure that you have hobbies that are not technical. I like photography. You'll find that being an interesting person, you'll attract other interesting people (and opportunities) to you.
Finally, always make sure that anything "work" related that you do, including programming, that you do in the context of having a problem to solve or a project to finish. Even if you're the one with the project or problem. The key is that problem solving is how we learn to use tools and the reason we retain knowledge. You know a language or tool not when you have the API memorized (forgotten next week!) but when you have developed your instincts suitably to know how you'd use it to solve a problem.
People don't pay you to know everything, they pay you to be faster/better at figuring out the solution than the others.
Anything worth doing in life is hard. Good luck and have fun.
I share many of your feelings. I live in Spain. The markets are common. But honestly, I think it's not a matter about Italy being shitty at anything. The IT world has changed. There is no three platforms any longer. There is no one single deployment paradigm any longer. Things are much more complex now and it's truly impossible to try to take on everything as it was 15 years ago. I found that myself frustrating many times. Thinking, heck, 15 years ago I could study this, this and this and be an expert pretty much on everything software related. Now this is not true any longer and it can be very frustrating for all of us that come from that world.
I think the key here is holidays of course, but also to adapt to the new software world. And learn that not all what appears in HN is shiny and great, not all that is done in the cool places like SV is shiny and great, and not all those frameworks and languages that pop up are shiny and great. Rather than a matter of focus is a matter of taking it easy. Do something that you like and that you enjoy learning and learn to let things pass on. You don't have to be a master of react, golang or angular to be a competent software person, there is more choices than ever. Focus on the models, patterns, problems and solutions. That's where the value is today.
And yes, computing is about data and algorithms and nothing else. Don't fall into the trap of new names of same concepts. Always think about problems in terms of data and algorithms and no other bullshit like objects, patterns that so called software engineering piled up in search for a silver bullet.
If you can take a >1 week you can program for fun after 5-7 days and get a sense for what interests you without work interfering. If you can only take a shorter vacation have fun and do something outside of technology and relax.
Consider working on a side project in the weeks following a break and hack on small projects that interest you. If you want to leave the .net space find local companies working on interesting problems.
Ask to get coffee with anyone in your network (or outside) to get information about other parts of the industry/other companies and methodologies.
All in all take a vacation and then spend 2 months hacking on projects and talking to anyone in any part of the industry around your area (or potential prospect cities).
> I am interested in security, c, go ect...
Talking to people actually coding in a language, securing infrastructure, doing X, will be a lot better then learning Go for 2 months and finding out that it didn't help with your core goals.
Take a break. Expand your professional circle and knowledge base. Format a plan based on that info. Execute).
Seldom does using a different language fix anything. Programming is programming.
Excercise can fix your life outlook. Better teammates can change things. Nicer boss. But seldom will language or business do that much do your day to day life.
Don't panic.
Work is going to be a little bit boring for you for a while; learn how to cope with this for a bit. It is going to take longer for you to become an expert at something interesting and important than it took for you to get to where you are now. This may seem counterintuitive as you are quite a bit more aware of what you don't know than you than you were before you typed your first "hello world". That's okay. This is how knowledge works. All those abstractions you've built up in your brain for the the low-level things you didn't need to know at first are massive wells of knowledge that you only see the surface of.
So How do you get good at something? I truly believe you can only get good at something that you can sustain working on for a few years. I find, personally, that I can read one theory book or set of papers between bouts of working on something. That seems to be a good mix for me.
This isn't a race, this takes time. Once you start down the path of becoming an expert at something you'll realize it is the work of an entire lifetime. Enjoy the ride.
I don't know much about tech in Italy but I have heard the same complaints -- culturally, Italy doesn't have high standards for quality in technology. If you struggle with that, then there are two solutions: work for a US or Israeli company, remotely if you can, or start your own business.
If you want to start your own business, I'd recommend starting a solo software consulting practice first, that way you know you can make some money on the side while building your business..
in my country (Italy) there is no importance (or almost) to quality of projects (especially Technically), you have to face with ridiculous deadlines, poor team mate (in order of thech knowledge) and tremendous customers.
Moving into a different field (one which is more specialized than generalized-enterprise-business development-in-yet-another-problem-domain) won't fix any of those things.
Having tangential interests (security, low-level computing, new languages) is also normal, and a symptom of possessing a naturally curious creativity.Having tangential interests (security, low-level computing, new languages) is also normal, and a symptom of possessing a naturally curious creativity.
i constantly feel interested in IT Security, then low level programming (C/C++) than again "new" languages like GOLang, RUST etc.. i can't focus on nothing, i think it's due to my work frustrations
So, the question: Is an inability to deliver on hobbies, and convert them into productive professional skills, driven by miserable distractions? Nah. Whether you make something of them, isn't going to be the cure of the things that you find frustrating, BUT the time you spend tending to frustrating tasks will be time that is poorly spent, under any circumstances. Fluffy bean-counting busy work will eat up the precious moments of your life, no matter the career.
So, now you'd like to migrate your skills over to newer hoobyist interests, that you've explored tangentially? Makes sense, but it won't solve the human factors stemming from social circumstance. Nor will it prevent unfulfilling, soul-crushing toil from creeping into your newfound career path.
It WILL, however, temporarily cure your wanderlust, and relieve that dreaded sensation of stagnation.
I dunno, try this, for starters:
LinkedIn founder Reid Hoffman looked back over his career and cited his biggest career mistake as not leaving Microsoft for Netscape. At the time, Netscape was where all the innovation was happening. It was spouting out entrepreneurs. The right question wasnt how can I learn to be a product manager? It was, how can I get in the building at Netscape?
Italy is so far behind when it comes to the internet adoption, it's not funny. It's also a rather poor country, especially among the young generation, many young people live with their parents till 35-40. So you're much better off making (or working on) a project that faces some of the more developed countries (US, Australia, UK, Germany).
- I'm Italian
- I'm in my 30s
- I have ~8 years of professional experience, mainly in big agencies
- I have fully experienced the pains of your country, consider also I have been independent contractor for some years (you know, clients not paying you?)
I moved to France following my girlfriend, and I'm sitting here waiting for a response to some job positions I applied for. Also I'm running out of money. I am also really thirsty when it comes to technical challenge. So well I'm the last who can give you advice, but here are some things that worked for me:
- Stop looking at Italy for jobs, instead look at Europe. I had an experience working for a company in San Francisco (ok, that's USA) and it was ages beyond the typical Italian experience. I'm pretty sure that Berlin, Amsterdam, Barcelona can offer great positions _and_ professional cultures. I'm actually checking europeremotely.com basically daily, but also StackOverflow jobs is pretty cool for that. I hope not being wrong about this.
- Don't stop feeding your passion. If you love coding, keep doing it. Personally, I took everything which was outside my consolidated professional competence, and put it in a box called "game development". That's my secret corner where I experiment everything I love. Like well "modeling a mafia economic system through agent based simulation". There, I practice stuff I'll probably never use professionally: C#, LUA, C++, Golang, OpenGL.
- When you evaluate new technologies which may become part of your daily work, don't stop at the tool, but look at the context around it. RUST is good for system development. Would you like a job in that area? I'm basically a PHP developer, but man how much I would like to escape from it. I'm currently learning Elixir, as it looks like the Ruby of the next decade. I bet there will be a lot around it in web area.
- I force myself to switch off the mac after 8 pm. Before, I could sit there all the day and a good part of the night. Doing something else, especially if it involves physical activity, often helps me seeing more clearly myself, my real interests, and above all works as an antidepressant.
After all of this, I'll fail and be forced to return to Italy anyway. In that case, I'll give up coding and learn doing pizzas.
The right tool for launching might be the one that requires the fewest trips to StackOverflow via Google, or maybe that idea is not an important optimization to your workflow.
If those technologies excite you, great! Maybe you'd rather do security / be a generalist. Just make sure that's the path you choose rather than just looking for escape from boring enterprise software. If it's that, then see other answers and take a break.
Edit: And try making it more than just a cursory whim. Write up a whole document of what you do and how you plan to do it, as if someone else had to approve it. That really tests your resolve up front.
There might be a division in your company dealing with newer technologies. You can try to switch there, or try to join a startup that is more akin to your technology preferences.
Regardless of what you prefer, I strongly suggest that you join a meetup (see meetup.com) that is related to your interests. You will be learning new things and connecting with people that share your interests. If you lack the time, hang out in IRC channels and join interesting conversations.
Focus: its healthy to try lots of different things, there are lots of interesting areas. Maybe if you can get a better job, they will be using a particular new technology, and then that will motivate you to focus more on that.
Personally I find trying to work on an OSS project the best way to "try-before-you-buy".
Since this is mostly work related, I'd say change your job. You want to find a place where you can work with psychological safety. Psychological safety is the condition where you feel safe to take risks, and be vulnerable to people you interact with. It's proven (...) to be the most important factor in success and employee satisfaction. You cannot achieve this by yourself, it is dependent on the work culture of your workplace, and unless you have enough authority to change the work culture, you'll have to keep switching job until you find a place that has the culture you need to have psychological safety.
Trust me, at first glance, two jobs might appear similar, but work culture is a very subtle arrangement of tiny details that add up to be the most influential factor, and so, it's really hard to know without just trying the work for a few months. But also, each and every workplace will have a vastly different culture. So try other jobs, it's worth it.
Now about your lack of focus, that's normal. Try to work at two levels of attention. Off course, you want to have some fun, learn some new things, be curious. This is your intrinsic motivation, and do not kill it off by trying to tell yourself you need to focus and bore yourself to death to become more "professional". Don't try to have rewards take over it either, value a lesser paid job if it allows you more creativity and freedom for you to learn and try new things. This is the first level of attention, you enjoy the details, the tech for tech's sake. Now also try to think more about the second level of attention, imagine all the code you write is assembly language, and even though such details are interesting, it is mostly the case because it is also easy for you to work at that level. So spend some time learning about the higher level. What happens if I consider all algorithms to exist as tools for me to use, what problems can I become interested in solving at that layer. This is when you realize it takes you closer to business problems. How do you optimize the business needs, with the tools you have. How do you arrange multiple systems together to scale, etc. Unfortunately, most people's CS degree didn't go there, and so going to that level is hard, and most people find hard things less interesting. If you put some more thoughts into hard things though, they start to become easy, and suddenly, interesting again.
Sometimes, companies who don't advertise remote positions are willing to try it. Sometimes, companies who prefer full time salaried employees are willing to bring you on as a contractor. Sometimes they may even be willing to consider a short 3-6 month gig to build out a prototype or project that they'd been meaning to get to but never had a full-time dev to throw at.
The only way to find out is to ask. Good developers are hard to find, and good companies know to grab ahold with both hands when they find one. If that developer just happens to want to do his thing remotely, in short bursts, or even from the beach in Costa Rica, that might not be as much of a stumbling block as you think.
You're going to have to do sales of some kind. Outbound is faster.
Proactively talk to people who need professional services, talk to them, understand their needs, explain their business to them and then tell them that you can do it, for X. X is a lump sum or a number of hours billed at Y, doesn't matter. Sell your business and be on point.
Do not be the guy who does "oh this takes X hours" and then it takes 3x as many hours.
Be professional. And don't mind anyone else. Don't compete on price. Compete on quality.
If you can't do the outbound sales thing, apply to Toptal and Gigster. On toptal, its the same thing. People say you can't earn a decent rate, which is not true. I showed up there, with my very lofty rate, and made it happen in a week. Exactly the contract that I wanted. I'm working part-time on a full-time salary that dwarfs anything I could make anywhere in the world outside of the Valley while living the good life.
Just be quality. It's 2016. If you're good and you can make this your profession, you'll live pretty well.
And pay the naysayers no mind. There is no race to the bottom. Indians who charge $15/hour are just fundamentally bad. The really good indians won't work for that rate either. They know what they're worth. Compete on quality.
It is fundamentally impossible for there to be a race to the bottom, since there is too much demand. If anything, we are experiencing a race to the top and its only begun. Increase your hourly by 50% per semester at least until you hit $250/hour.
It started out small. With only a handful of small jobs, but if you make your clients happy, more work will come.
The more established you become, the more access you will have to higher paying clients.
I'm fairly new to using it myself, and while I've not gotten any work through it so far, I have gotten a couple phone interviews, so it's not nothing.
Focus on growth of both top and bottom lines, and highlight margin improvements over the 4 years and 4 projects. Try to quantify your accomplishments in dollar figures since they stand out more. Statements such as "Grew revenues 50% YoY from $0 to $X million over 36 months" will quickly catch anybody's attention.
Throw in some specific, targeted technical phrases that are keyword friendly and you'll easily be an outstanding candidate.
Be prepared to explain why you'd want to join the target company and not stay at your current company.
TLDR: Hiring managers hone in on results, not only titles. Quantify your business impacts and list your technical accomplishments.
EDIT: Regarding my comment about quantifying your margin impact, for those that don't know, "margin" and "markup" are not equivalent[1]. Thankfully it's really easy for technically inclined folks to grasp this insanely useful financial concept.
[1]...
Shamelessly, don't hesitate to reach out if you might be interested - we're hiring in all areas, and I would especially love to chat if you or your co-founders are looking for engineering, PM, or marketing roles :)
The fact that you've held a job for more than just 6 month stints is enough to push you all the way to the front of the line. Most applicants we see just do 6 months here and there. I refuse to hire anyone that hasn't stayed at a company at least 2 years (excluding new grads). 4 years is pretty much a unicorn nowadays.
For the resume I focused on the journey's small wins, just bulleted. I had no revenue numbers to share, so just highlighted what was achieved in what time.
It was very hard, but what I figured quickly was that the resume mattered way less than the people i pushed it to.
What worked:
1. Sent linkedIn connects to a crazy number of startup founders (50-100 daily), apart from the usual HR connects. side note : i bought linkedIn premium subscription at about $40 a month to cover my search limits.
2. Whoever connected back (10-15%), I shot them a crisp email telling them I'd like to meet for startup advice and/or opportunities with a one liner.
3. Whoever responded with 'No', I politely asked if they could recommend someone they knew who'd like to connect.
4. Whoever responded with maybe/Yes (5-10% of the connects), immediately tried to set up a time within the next 2/3 days. Could be a call/meeting/skype/anything.
Note: the eMail always
a) had a touch of personalisation.
b) was no more than 3 lines
c) included my product snapshot as an attachment
d) ofc, had resume attached and contacts+linked in profile link included in signature.
Met great people along the way, will surely help in future. And met one of the best founders in my country - he made me join his company Nearbuy (Groupon India). The hunt took me 6 months, partly because I had 2 hard filters a) not going to wear a suit to office..so consulting/finance was out b) no politics..so most corporate jobs were out.
Takeaways: Seek help like crazy. Your passion and hardwork at your startup is your resume, nothing else will matter.
- have a clear, simple story to answer "why are you (single person) leaving the startup". You'll be asked at every interview (and if multiple people apply to the same company, you want a coherent answer). Include that you all are leaving if this is the case -- the risk is that you (single person) are seen as one giving up
- list down 4-5 main achievements. Make sure there are 1-2 which are not co-done, but you can state "this was mostly my own achievement". This is the hardest part, but if you're still working together you can easily agree on how to split
- make sure to clearly tell 1 story, which doesn't need to be the one of the startup, but the one for which you're seeking the new job position -- if I'm looking for a position as data scientist I'll focus on my research experience, if I'm looking for devops I'll focus on security, etc.
- in linkedin specifically, if it applies, link some press or some blog post, or anything I could spend time digging in to get to know you more -- if you feel that the list of jobs is not enough, help me finding more info about you
From the other side of the table, when I look for people to source/interview, I look at the total working experience. Wether it's 4y in a single company or 2+2 it doesn't make any difference. I personally (I see others can disagree, but this is me) see as a yellow flag a 1+1+1+1 experience, simply because I fear you'll leave my company after a sole year.
(If you'd like to chat more feel free to ping me via email.)
Awesome Great Company I started: 2014 - Present
CEO/HR - I was responsible for ...
CEO/VP Sales - I successfully sold 4 large projects which resulted in ... sales ...
CTO/Tech Lead - I designed, built, tested ... Also, created a complete automated test suite... using NoSQL, Android...
But like many have said here if you write on your resume what you have actually been building over the last couple years you should be fine. Being able to clearly talk about your experience is more important.
- this job for which I'm applying, what do they REALLY need, and which 3 to 5 bullet points capture my competence and accomplishment in this area
- how is this company like mine, and how can I communicate the similarities to my experience working w/ others, building a certain type of product, applying domain expertise, etc.
- what story will I tell if/when they ask, "So do why do you want a job when you've been your own boss for so long?" Maybe something like "You know, what I really like to do is make an impact doing X, and that's something I get to do in any position with responsibilities A, B, and C."
And my generic resume writing advice is... try writing your resume without adjectives. It forces you to focus on highlighting what you've really done. Let your awesomeness sell itself. Calling yourself awesome doesn't do much for you.
Put all 4 projects on there and try to sell them as technically as possible.
I was at an unknown company (nationally) for 7 years before I left. I had no issues whatsoever getting interviews.
When people talk to me about what I did they think it's impressive and love the technical challenges I tell them about, but most of the times the rejection happens only because of fear that I will create my startup again after a short time of working at company x. I got this confirmed multiple times after asking about the reason.
I'm living in Asia and it might be a thing here but it is very frustrating.
As an aside, not everyone is on LinkedIn, and those of us who aren't apparently can't see the profile you linked.
Also, full disclosure, it sounds like I'm a bit older than you but my background is somewhat similar, so my views here may be biased. But having sat on the hiring side of the table in various roles, I'd take demonstrated ability to get things done and build successful projects over some random progression of short term jobs with increasingly impressive-sounding job titles any day of the week.
If you didn't pick up any coding or tech skills during running your start-ups you may or may not have issues.
For me my start-ups were like going to school to pick up a new/in-demand skill that I could fall back on if my startup dreams fell flat.
Ran a semi-successful web / mobile app development company. We were a small team of four, hitting early to mid thirties. From the outside anyone would have thought our company was successful. Good brand recognition in our geographic region, finding clients was easy. They found us.
We paid ourselves decent salaries, paid the bills on our dev infrastructure, we all worked in the trenches, at our own pace, and we all generally loved what we were doing.
However, after about five years we got that itch. In a way we were too comfortable. Our finances looked the same year after year. We purposely weren't growing. Or maybe we just didn't want to take that risk. I guess we peaked early and got comfortable staying there.
At first no one really talked about it. You could feel it though. As we got older. Being so close to the business administration became a chore. Planning summer vacations with a small team became a chore. Riding out December became a chore. Maintaining apps over a five+ year lifecycle became a chore. Dealing with dev infrastructure maintenance became a chore. Wearing too many hats became a chore.
Life outside of work becomes more important as you get older. Family and that sort of thing.
So we decided to shut it down. Lots of emotion, soul searching, panic, joy.
Anyhow ...
I personally had the same feeling you did. Does co-founder look good on a resume? What the hell did I do for the past five years? Will I fit in with corporate culture? How do I transfer my skills to the corporate world?
What I learned is that you've got nothing to worry about.
Working on a small team, and staying profitable, and paying the bills means that you understand the value of money. You wear multiple hats. You're skilled at sticking to a budget and meeting deadlines. You had to "show up" every day. You worked the trenches and enjoyed getting your hands dirty. You worked twice as hard and twice as fast. You stayed the course for four years. You're loyal. You're reliable. You understand the entire lifecycle of building something from start to finish. And you've done it successfully multiple times over. You understand failure too, and know how to bounce back. You have an amazing combination of business savvy and technical smarts that's difficult to find. You're entrepreneurial. You've got vision. You're an ideas person. You've got real-world experience. And a track record of success. Most startups crash and burn early, you didn't, and you're leaving it on your own terms. Knowing when to exit is an extraordinary skill in itself. You understand how it all works. You haven't lost touch.
Don't scare potential employers with big fake C-level job titles. In a company of four you never really had a specific job title anyways. Use that to your advantage.
Custom tailor your resume for different roles. You've got so much to offer your challenge will be figuring out what to "leave out". You've got volumes of specific examples and accomplishments to draw from, which you can talk about for hours.
You're still young. In fact you're in your prime. You'll be a massive positive addition to any team.
Look for a larger (than yours) company that hasn't lost their entrepreneurial spirit. You'll be right at home. Don't settle and don't be surprised if five or six years from now you get the itch to embark on another startup.
It's all good.
Technical
* Implemented xyz process to reduce pdq by x%
Leadership
* Developed market strategy for team of y teams to improve market share by z% in 3 months
etc
You don't need to show a ton of progression. You just need to know how to market the skills and experience that you have. If you've been profitable and are getting paid well, and have four substantial projects over four years, you're marketable.
Feel free to inquire if you'd like professional help.
If you find a position you like, send an email. Tell them why you're interested, what you could bring to the table. You can mention your history if it's relevant, casually, just like you wrote it up here.
If they don't like it, fck them, their loss, try a different company.
edit: Just to be clear, i'm not suggesting you skip the resume because of your specific history, rather because the whole concept of presenting resumes is utterly inhumane and counter-productive.
- don't worry about inflated job title, especially in the bay area.
- resumes are targeted to its audience.
- know what you want to do (engineering, product management, etc).
- reach out to managers at companies that you'd like to work at. ask them what they need (don't go by job postings, too generic most of the time). fill resume with relevant info if you have them.
- communicating that you're a desirable hire is done in the interview stage. resume is a tool to get you the interview if you have zero connection inside that company (don't blow it off though, since it's usually shown to a hiring board for final decisions).
Your work will speak for you, and discerning employers will find you.
More and more large corporates value what you have, and in cases, are willing to pay a premium for startup skills. They are also sophisticated enough to separate the company's failure from your skill.
Really, don't sweat it.
All the best.
Isn't 5 years at a startup doing [presumably] technical work pretty much the best thing you could possibly put on a resume?
I guess if you were a bizdev-type, then maybe the negative here is: why was still a startup after 5 years?
5 years at a startup, for a technical person, sounds awesome.
otherwise, give yourself a different title for different periods of time, and list your co-founders or customers as references.
If you are looking for a certain job, you don't want a resume with a bunch of empty titles. You need a strong resume addressing the specific requirements of that particular job, in terms of skills and relevant experience.
Large organizations need both people that take care of the "ordinary business" and people that take care of "special projects", that are the doers, that figure things out by themselves: your startup experience automatically qualifies you for all the activities that require this second type of people.
It's not obvious but in my view, Aurora does not have a great scalability story, it's more of a reliability play currently. It can give you greater throughput due to the internal replication of data, but not faster queries than you can get on your own big server (owned or rented) if you spend the big bucks. When you are getting a big server, it is not particularly cheaper over time, although it does reduce/remove the need for capex and let you spend opex. It is however wonderful if you want to reduce the need for a DBA and/or have really easy to setup and manage replication and resiliency to hardware failures for your database. There aren't great MySQL open source or AWS MPP options out there for scaling-out in my view (MySQL Cluster requires you use NDB tables and MySQL Fabric imposes some significant shard key limitations.)
Postgres-based scale-out options include AWS Redshift (for analytics) or open source Greenplum (for analytics) or, for more regular web/oltp-type traffic the recently open sourced citusdb. The latter two you presumably could run on AWS EC2 instances.
To me the scale-out story for Postgres looks better than MySQL. But if easily-managed reliability is more of a concern, I would probably go Aurora.
Other than that, I was going to use an old iPhone or Android phone as a wall-mounted touch panel for my Hue lights or to run media apps to cast to one or more Chromecasts around the house. The original plan was to put the phone in a 3-gang box in the wall with some foam or other material to hold it in place. Then I attempted to use my dremel to rout out an opening in a blank plastic wall plate so the phone was held in place but the screen was accessible.
Unfortunately my dremel skills aren't good enough to the point where I could get one looking good enough that I'd want it on the wall. I guess I should just have one 3d printed but I've slept on it after the initial disappointment.
Additionally, I wouldn't be able to mount the power supply in the wall if I want it to be safe/up to code so I would need to run the wire down behind the wall and have it exit out of a notch in the receptacle wall plate below it near the floor with the wall wart plugged in. Still not very attractive so there are definitely shortcomings with this concept.
In the end, it's just been easier to use our existing phones since they're always close at hand and my ambition comes and goes with projects like this. It's a real shame that there don't seem to be any ready-to-buy, relatively universal wall mounts for charging and using smartphones or tablets this way. I've seen some but they're usually specific to one model of phone or tablet and they tend to be pretty expensive and ugly.
[1]
[2]
You can easily connect a lot of things to your mobile and automate them. The phone already has a lot of sensors so I would think more along the line of "which motors can I connect my phone to?". You could build a robot for example...
(I know, it's probably bad for the environment...)...
It is beautiful app with many integrations(Zendesk, Jira, Trelo, Slack, etc) and many features which helps you to conduct research, prioritize what to build next, communicate plans and progress.
Hubert, the CEO of PB, is also very active on Medium where he writes about product management -
Full disclosure: I helped them get started (supplied some early coding time).
Under 1 year, I have to think that something out of the ordinary happened and I would be inclined to ask about what happened. Did the company go under? Were there some crazy red flags that forced you to leave? And internally, I'd ask myself, is this person really picky? Do they have some red flag that keeps getting them let go? Etc.
I don't have an upper limit, but definitely a lower limit; 2 years. 1 year to get up to speed, 1 year to give the company a chance. I recognize that all companies have problems and I want to see progress being made on solving those problems. If, after 2 years, we're still talking about the same issues we faced when I started, then I'm going to start looking.
Curious why someone would place an upper limit on time served? If the work is good and the company is good, why leave?
Whatever the stack I get up to speed usually after 1 week and provide value to the company pretty much immediately (it's always scary starting a new project because I feel like I need to prove myself within the first few days since I'm working with a new team).
If it's a normal job, I think 1.5 years should be a good amount since that is apparently the median for how long developers stay at a company nowadays.
I think the mentality that a hiring manager won't hire someone because he's afraid someone will leave after 6 months is old school. People are going to leave, but you need to figure out how to get the most value out of your developers while they are there. Also, if it takes you that long to get someone up to speed it's either that developer is too slow or there's someone wrong with your process.
Ultimately I see the pros of job hopping (early on in your career at least) because you will have worked with so many different people. Your gauge in people's personalities and experience will be a useful asset. Plus you will get to know a lot of people in the industry.
So ... if a person leaves at the 1 year mark, it was likely they who chose to leave. Given the stories about bad employers in tech and the fact that there are many good employers too these days, I would say good for the moving employee!
Another red flag I look for is when someone has freelancing on their resume and they will basically have this:
Freelancing, Inc. 2005-Present
Company A July 2014-September 2015
Company B December 2012-August 2013
Company C January 2011 - March 2012
You get the pattern. While those people generally end up spending more than a year with the company, they always quit and go back to "freelancing". I've spoken with some people about it in the past and it seems semi-common for freelancers to work full time for a company, save up as much as possible, then leave and skate through their savings and the odd freelancing job for a year or two, and repeating. That's generally not what we are looking for
So for someone with more than a few years of experience, I generally like to see at least one job in the last 5 years where they lasted 2 years.
If I have context why you're job hopping then I'll take it into consideration. There are legitimate reasons to leave in a few months. However, if you've never been at a place or project for more than a year, I can safely assume you never had to support an application much in production because by the time you were knowledgeable enough to do so, you left.
I had two slighty-more-than-a-year stints in a row and I know some people who it caused concern for. What was the reason? One was a contract with a non-profit that didn't have the budget to continue and the second was a failing startup that was downsizing. Both perfectly logical and understandable. Fortunately my next boss-to-be asked first.
I've also seen people who love small startups, they get in on the ground floor and stay for 18months before they move on. They did an amazing job and I wouldn't hesitate to hire them on even if I knew it was only for 18 months. (oh, then they found an amazing startup and stayed for ~4 years)
At the end of the day there are way too many variables. As a hiring manager myself I've seen and heard it all. So don't make assumptions. Don't guess. Interview them as normal and ask the pertinent questions about their history.
This has become a really big issue as when I look my "stability" is bought to light consistently. My first two roles were 2.5 years, and 1.5 years respectively. Both times I left on good terms. So I can commit, and will if given the oppurtunity too, and room to grow. My contracts have just been largely proof of concepts, that were shelved.
The thing is I'm tired of jumping, worrying how long my contract is going to last. That I need to keep going looking for the next thing, because either the contract will run out or I stagnate. This is also leading to a counter point and negative when I look. I've not been able to ship any projects to production. I feel at this point I'm stuck in a contracting loop, and I'm not sure how to get out.
When you have someone who's been repeatedly changing employers every 12-18 months for a while with no mitigating factors, you begin to wonder about ability to commit.
It may matter less if your are in a field where things are done in sprints, the person is likely to be instantly productive, and there isn't a lot of complexity to absorb.
There are people who have the temperament to be short to mid-term contractors, and who don't like to be and wouldn't be good long-term hires.
But in general, I skip if the pattern seems to be hopping every year in the last 2-3 years.
Another thing that I look at is where geographically the candidate was working. If I see no hopping for a while, then moved to Silicon Valley and started hopping every year, then I pass, or at least I yellow flag that in the pipeline.
I don't have any issue with several years in just a company, actually I think it's rare and very positive.
Speaking of seniority, it's very hard to hire someone into a senior or leadership position if they've never stuck around at a job long enough to actually develop any seniority. It's impossible to develop management skills if you're quitting your job every 12 months. Even at every 24 months you're really limiting your ability to get some truly solid management experience under your belt.
All that said, having long tenures on your resume obviously doesn't guarantee anything. A week or two ago I interviewed someone with 15 years at the same company and the title of Chief Architect who seriously struggled with a simplified version of FizzBuzz.
The bottom line is that I try to keep an open mind about everyone, and if I have concerns over the lengths of previous jobs I'll always give the candidate the opportunity to explain their viewpoint. Usually I can be convinced and won over.
It might be that long before seeing your first "annual" pay increase. It is very common for me to see the crap raise that I got for the year and send out resumes to check on competitive offers, to see if I could do better.
It is also long enough to see a company on its worst behavior, and decide that enough is enough. I personally go two years with a merely bad--but not awful--company, to see if I can jump-start any improvements. After that, I send out resumes, and jump ship as soon as it is feasible.
But I'd also see that as an indicator of the quality of companies these days. I have only worked at two companies (out of 8 jobs) where I would have been happy to stay there indefinitely. They both got bought out, and the new owners laid me off without regard to my individual value.
I have always been "at will", so if you're going to question my durance at previous companies, I'm going to question your commitment to all your employees that have no contracts. That door swings both ways. If you're looking too closely at that, I might think you're trying to weed out candidates that are too sensitive to the corporate bullshit that may be driving your existing turnover rate, in which case, I might get spooked and either withdraw or demand a higher offer from the start.
1. Several <1 year tenures - this person gets fired a lot
2. Exclusively 1-2 year tenures - This person is trying to jump around to maximize salary (and isn't able to convince their current employer to match/exceed an offer)
For #1 job history is usually not the only indication that this will be a problem. Depending on how many open positions you have they might make a screen, with the vast majority washing out there. "It was contract work" is usually a flag, and being at startups that went under is a mitigating factor.
#2 is somewhat more risky as a hiring manager - more expensive to interview because they are less likely to flame out early in the process, but then much more likely to not be able to agree on an acceptable offer. Overall these folks are still going to be net positive contributors over their tenure, but there is opportunity cost in missing out on hiring someone who would kick ass over 5+ years at your company. It's hard to definitively pin someone down as this category outside of 4+ jobs never going more than 2 years. If they are coming through a recruiter that's a flag, and if they have moved cities that's somewhat of a mitigating factor.
Seeing someone who stayed at the same company for 4+ years and got one or more promotions there is a big plus on resumes.
There is not a lot of research into any of this stuff AFAIK, so this is basically all just my opinion. What I have seen basically says that people are pretty bad and inconsistent at evaluating resumes:
That doesn't mean every bullet on your resume needs to be 2 years long, but if you're at least a handful of years into your career, you should have at least one.
And yeah, if you're working for startups and they keep going under, that sucks. But maybe it suggests that you could stand to learn a bit more about the business end of things and improve your ability to evaluate an employer's prospects.
I prefer working in startups and smaller businesses rather than a bank or government entity. In the startup world I found 1-2 year stints don't seem like a bad thing. In the conservative banking world it could be.
Employees are like expensive, specialized tooling. The more specialized and refined your skill set is then the more acceptable job hopping becomes. If you're the kind of person that's brought in as a subject matter expert to help do something your experience may not be relevant and you may be, expensive, under utilized and dissatisfied when there's no more work for you. To continue the tooling analogy, if a company buys specialized equipment for a contract job it's usually sold afterward. This is why highway plowing and bridge building equipment is all ancient and has had half a million owners. A contract is won, (used) equipment is bought, maintenance (or modification for the specific task is performed), the work is done, someone else wins the contract, the equipment is put up for sale and the cycle continues. It takes resources to keep specialized equipment or specialized employees around and functional (pay/maintenance) and it's not efficient to have it sit around mostly unused (making a senior dev chase bugs). However, if you're switching jobs in less time than a typical project takes you're gonna come under the same scrutiny as the crane that's up for sale while the rest of the fleet is building bridges, "what's wrong with this one?" If you're not sticking around for about as long as it takes to complete on project then it's gonna draw scrutiny.
If you're resume looks like you're job hopping and moving up it's likely going to be looked upon neutrally or favorably (i.e. "nobody can keep this guy because everyone else has more important/lucrative stuff for him to do").
Job hopping is definitely within the range of normal for the vast majority of the industries people on HN work in so unless your resume practically says you can't hold a job then it shouldn't be a problem.
I'm not going to put a number on "job hopping" because it's dependent on industry, specialization, region, training time and probably a bunch of other things" What's short for someone developing control software for radar systems in Boston is likely an eternity for a JavaScript dev specializing in UI in SV.
Upgrade regularly, as soon as you find a new job that you like more go take it. Building your skills and Networking are key. Network all the time, get to know people who will be hiring, conferences, events, find people who are working on things you want to work on and people you want to work with.
Lifes too short to wait it out.
Upgrade fast and regularly, pay shoots up, location improves.
Upper limits depends on company and movement within the company. 10 years in a company with good reputation isnt a problem. 10 years in a staid government department with no movement wouldn't likely represent a go-getter.
I don't really believe in hard and fast rules with recruiting. There are usually too many variables for arbitrary limits to be helpful, and I've seen plenty of good hires with unusual resumes. The important questions are:
1. Is the person you're looking at likely to be an overall benefit if you hire them for the position?
2. Is anyone else who is applying likely to bring more overall benefit?
There are three concerns I usually have with a resume full of short-term gigs.
Firstly, someone who has never stuck around long enough to deal with the consequences of their own decisions or who has no real understanding of issues like technical debt is a huge liability above entry-level positions. If someone is applying for a senior developer role and I don't see evidence of knowing how to maintain software long-term from their employment history, there would need to be something else in the resume to make up for that or it's basically an instant no-hire.
Secondly, the equivalent for more junior positions is that someone moving jobs every few months may not be gaining useful basic skills and developing sound professional judgement as effectively as their time served might otherwise suggest. There's an old joke about someone with ten years of experience and someone with the same year of experience ten times. The latter is probably a no-hire.
Finally, there is always some cost and some disruption associated with hiring a new member of staff. Someone whose pattern of previous moves suggests they're just trying to climb a ladder as fast as possible without necessarily contributing much value in each step along the way is a no-hire. Just as important, even someone who looks like they'll probably stick around for a year and generate some real value after a few months ramping up is still going to be a much less attractive candidate than someone who usually sticks around for say two or three years.
Maximum 2 year
1 year for some equity and to judge if I even want it, 2 year solely so hiring managers don't disqualify me (along with random employees that anecdotally heard what red flags).
And I remove all the 3 month stints off my resume
And I also take off contracts done in chronologically parallel time periods because they confuse people that are silently judging how long I had been anywhere, than any other merit
Easier to get an experienced based salary upgrade at a different company, than at the current company.
Another quirk seems to be that everyone in engineering seems to like seeing gaps. So disappearing my 3 month stints has an added effect that would be counterintuitive to all the unemployed bloggers writing resume tips on ask.com
It is an adaptation. Get money.
On the other hand, if someone stayed at one place for 5 years and doesn't have a lot of progress they can point to, I'd be somewhat concerned about their trajectory in their field.
Personally I think I would ask more details of an engineer who stayed with a company 6 months or less but I wouldn't necessarily be suspicious. Anything beyond 12 months, I wouldn't ask at all.
It's because your not paying employees the market rate so they leave.
Nothing to do with skill of the employee.
They just want to get away with paying below rate salaries.
You won't get in the door just applying to jobs and saying you've got 30 years of being a hobbyist and love Assembly. You'll have to demonstrate something you can do, and ideally it will be something interesting to the person receiving your message/application. This becomes a marketing issue, and you can market yourself as a junior programmer and career transition candidate willing to take on junior work at junior prices for the chance to get in the door.
You can usually disguise your age at least a bit by omission in resumes. A resume isn't a full biography, so we don't need to list every single thing (especially since you will likely have lots of irrelevant professional experience). We can also delete things like graduation dates (if you attended college) in order to avoid someone guessing your age.
I'm the same age as you - if you're priced correctly for your skill level, your age might even be considered somewhat of an asset (maturity) in certain companies and jobs, but the key for you is marketing whatever skills you do have and leveraging those to get the skills you want (more programming).
You aren't old. They were 55+.
When I interview people, age does not concern me (45 wouldn't even make me blink). It is only if I think that person will be an asset to my team. And if they are, why should age bother me?
More important questions I ask myself is: Is this person going to be self sufficient or are they going to need a lot of assistance?
Is this person a generally positive person who is willing to communicate with others and me about any struggles they are having so we can fix it?
etc...
There are still tons of projects/products that use very small microcontrollers or microprocessors. You're not going to run Linux and Java on an embedded system that's got 8KB of EEPROM and 256 bytes of RAM.
Good luck!
Next time someone is looking for those skills, hopefully your name will show up in their Googles?
A word of caution... doing RE in a mediocre way is fairly easy. Doing it well requires knowing, well, a lot of shit about a lot of shit. Encryption, compilers, information theory, high level compiled languages, network protocols, etc. are all required knowledge to not get stuck at some point while doing that job. And sooner or later you'll find you'll be writing your own RE tools out of necessity.
This might sound cynical, but the good news for job seekers is that there is often a higher demand in the security industry for a mediocre reverse engineer who is willing to make a lot of guesses, abandon problems that are too difficult, and move on to the next thing quickly. If you're willing to learn in the job it's almost an ideal place to start.
One would be to start working on an OSS project that is well supported locally and to attend relevant meetups. Get known in the community, get credibility, and, after a while, let people know you are looking for work.
Another would be to start in testing - if you have the mindset for it. I know quite a few people with non-technical backgrounds who started in testing and moved onto careers as developers, integrators, and more, all with non-technical backgrounds. Testing is more about mindset, curiosity, organization, and detail, than about specific technical skills - or at least some types of testing are.
FWIW, YMMV.
Both assembly language and reverse engineering are vast, ambiguous fields of knowledge, so it's difficult to provide an on-point answer. A couple things come to mind though:
- Quite a lot of demoscene-related sourcecode has been released over the past few years (covering many individual productions along with supporting tools), and quite a lot of it is in assembly language. Considering that you've been tinkering for 30+ years, DOS/similar-era stuff may be of particular interest to play with or explore. This would best be considered akin to soldering practice, to use an electronics analogy - DOS-specific knowledge (including eg low-level VGA or SoundBlaster/GUS control) is not likely to be helpful commercially. That said. old technology is similar to learning a language like Latin, and provides the advantage of neatly sidestepping the general social/human confusion concentrated within the current focuses of technological development.
- Many people are likely to generally recommend microcontroller development, but I understand chips with eg 256 bytes of RAM or ROM (where hand-assembling code would be useful) are somewhat rare nowadays. This may be interesting to explore though.
- Finally, considering that you really like reverse engineering, you could make yourself available for hire for medium/long-term contract work reversing major applications or systems. Depending on the system in question this may be a lot of fun or incredibly tedious; reverse engineering is generally nontrivial work, as on the one hand there's the occasional tedium of picking IDA up when it doesn't realize it's fallen down, and there's also the general strain of ensuring the technical specifications you produce are complete, bug-free, and provide 100% coverage (or, in the case of self-modifying code, "100.% coverage").
As an aside, I think your age is actually a big asset - I don't think enough emphasis is generally put on the fact that age and maturity means an applicant already has a lot of "life" things taken care of. Obviously domain-relevant skill(s) remain key, but it's possible an employer may be willing to provide additional education to someone who's been around the block a bit. Case-by-case-specific though.
This forum doesn't provide a way to edit posts and comments after an hour, but you can always update it via a top-level reply.
Age is definitely not a factor. The speed with which you are able to learn definitely is. Good luck. I think this is awesome.
Your main barrier is experience, but if you're willing to go for a junior level position, that shouldn't be an issue.
So generally, look for companies with a more mature culture - avoid buzzwords like "rockstar" and "ninja" (secretly, everyone should do this), steer clear of "unicorns", and read the bios on a companies website, and you should be able to find a good fit.
If you really want to get into programming, I'd go for something higher level like PHP, Ruby, JavaScript, Python, etc. Then create some stuff in the language(s) you've chosen. This will give you a shot at getting a junior level job in that language.
When I hire someone to a junior level position, I'm still not going to hire someone with no experience. It's going to be someone with less experience but still some. I don't have the time to teach someone starting from zero. You need to go from zero to a low level of experience on your own.
"First find a problem to solve, then we'll talk."
I know it's glib, but I genuinely believe that learning to program or learning to be an engineer is, in and of itself, pointless. And every time I've tried to teach people the fundamentals of programming, they get bored, move on, and never come back. It could be that I'm a bad teacher - and I am - but I think there's something else at play.
I think it's that the reality of being a programmer is very different to what people think it is. For example, people think you can lean to program to a point were you "know" how to program. As though at any point a programmer can accomplish any task by sitting at a computer and bashing the keys in just the right way to solve any problem as if the solution was pre-ordained, just hanging in the aether waiting for you to pluck it into existence.
In reality, it's a never ending journey of learning. You can never stop learning. There will never be a day when you can stop educating yourself and proclaim to the world that you are now, and will forever be, a programmer. And I think when that dawns on people, they lose interest.
Also, programming is just the tool. The job is something very different. I could teach you how to swing a hammer in no time at all, but you'll be no closer to being a sculptor or a joiner or a stone mason. A web developer can't write a high frequency trading algorithm without first learning a lot about a lot of other subjects.
People often want to learn to program for all the wrong reasons. But if your desire is to solve a problem? Well that's a different story.
If you can find a problem AND you have a desire to solve it then you've taken your first step towards becoming a programmer... or a doctor... or a farmer... or anything else. And if you can also think of a good solution, that's your second step. What follows is a few million more thankless, frustrating steps. If your problem is best solved with the help of a computer, you will become a programmer.
So I would say this to you. You're probably going to have a hard time breaking into assembly as a career at your age for all kinds of reasons. Some valid, some not.
But if you can use what you know to solve a problem, and it's a problem people want someone to solve, or better yet if it's a problem people don't even realise they have! If you can do that, then all the challenges you would otherwise face in your quest to become a professional assembly programmer, they all disappear. You won't need a job. The people who have all the jobs to give, they'll need you.
Lots of them wanted to - but it was just a matter of time ... they have full time jobs, families etc
Since tech companies are the financial beneficiaries of everything open from operating systems to databases and programming languages, shouldn't "they" be reinvesting?
Why would we expect professionals to do this for free? When they do it is extremely generous.
|
http://hackerbra.in/ask/1470945901
|
CC-MAIN-2018-51
|
refinedweb
| 28,207
| 70.13
|
I am getting a couple of errors when I compile this program and all I seem to be doing today is making them worse.
This program is a homework program that I did before and it worked, but my program structure was totally different. I am re-writing it again as a class(we are working about classes , structs, inheiritance etc., and I wanted to try out this new material on a program that I had done before), but have screwed up in my functions and am just confused now. I know this is a case of messing with it for too long and the more I try to correct it the more I am messing it up.
Specifically, I am getting error code C2601 on line string reverse(string word) and bool pal(string word).Specifically, I am getting error code C2601 on line string reverse(string word) and bool pal(string word).Code:#include <string> #include <iostream> using namespace std; class PString : public std::string { public: PString( const std::string &aString ); bool isPalindrome() const; }; PString::PString( const std::string &aString ) : std::string( aString ) { } bool PString::isPalindrome() const { string reverse(string word) { string reverse; int length=word.length(); for(int i=length;i>=0;i--) { reverse=reverse+word[i]; } return reverse; } bool pal(string word) { bool pal=true; if(word!=reverse(word)) { pal=false; } return pal; } return true; } int main() { std::string str; std::cout << "This program is a palindrome-testing program. Enter a string to test:\n"; std::cin >> str; // Create a PString object that will check strings PString s(str); // Check string and print output if (s.isPalindrome()) { std::cout << s << " is a palindrome"; } else { std::cout << s << " is not a palindrome"; } std::cout << std::endl; system("pause"); return 0; }
I get error C2780 two lines below that line and it tells me there is a problem in the void function- but I have no void function.
What do I need to look at to get this to work? (Besides aspirin and a stiff drink!)
|
https://cboard.cprogramming.com/cplusplus-programming/136264-errors-i-cannot-figure-out.html
|
CC-MAIN-2017-26
|
refinedweb
| 338
| 67.08
|
.
All function, type and macro definitions needed to use the Python/C API are included in your code by the following line:
#include "Python.h"
This implies inclusion of the following standard headers: <stdio.h>, <string.h>, <errno.h>, <limits.h>, and <stdlib.h> (if available).
Note
Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included.X.Y/Python.h>; this will break on multi-platform builds since the platform independent headers under prefix include the platform specific headers from exec_prefix.
C++ users should note that though the API is defined entirely using C, the header files do properly declare the entry points to be extern "C", so there is no need to do anything special to use the API from C++.
Most standard type hierarchy). For each of the well-known types there is a macro to check whether an object is of that type; for instance, PyList_Check(a) is true if (and only if) the object pointed to by a is a Python list.
The(Py_ssize_t) >= sizeof(void*))..
The reference count behavior of functions in the Python/C API is best explained in terms of ownership of references. Ownership pertains to references, never to objects (objects are not owned: they are always shared). “Owning a reference” means being responsible for calling Py_DECREF on it when the reference is no longer needed. Ownership can also be transferred, meaning that the code that receives ownership of the reference then becomes responsible for eventually decref’ing it by calling Py_DECREF() or Py_XDECREF() when it’s no longer needed—or passing on this responsibility (usually to its caller). When a function passes ownership of a reference on to its caller, the caller is said to receive a new reference. When no ownership is transferred, the caller is said to borrow the reference. Nothing needs to be done for a borrowed reference.
Conversely,):
PyObject *t; t = PyTuple_New(3); PyTuple_SetItem(t, 0, PyLong_FromLong(1L)); PyTuple_SetItem(t, 1, PyLong_FromLong(2L)); PyTuple_SetItem(t, 2, PyString_FromString("three"));
Here, PyLong_FromLong() returns a new reference which is immediately stolen by PyTuple_SetItem(). When you want to keep using an object although the reference to it will be stolen, use Py_INCREF() to grab another reference before calling the reference-stealing function. *tuple, *list; tuple = Py_BuildValue("(iis)", 1, 2, "three"); list =++) { PyObject *index = PyLong_FromLong(i); if (!index) return -1; if (PyObject_SetItem(target, index, item) < 0) return -1; Py_DECREF(index); } return 0; }
The situation is slightly different for function return values. While passing a reference to most functions does not change your ownership responsibilities for that reference, many functions that return a reference (the caller becomes the owner of the reference).
It is important to realize that whether you own a reference returned by a function depends on which function you call only — the plum(), and (!PyLong_Check(item)) continue; /* Skip non-integers */ total += PyLong (PyLong_Check(item)) total += PyLong_AsLong(item); Py_DECREF(item); /* Discard reference ownership */ } return total; }
There.
The result of sys.exc_info();_info() dict[key] = = PyLong_FromLong(0L); if (item == NULL) goto error; } const_one = PyLong.
Theins, _X.Y relative to the parent directory where the executable named python is found on the shell command search path (the environment variable PATH).
For instance, if the Python executable is found in /usr/local/bin/python, it will assume that the libraries are in /usr/local/lib/pythonX.Y. .
Python can be built with several macros to enable extra checks of the interpreter and extension modules. These checks tend to add a large amount of overhead to the runtime so they are not enabled by default.
A full list of the various types of debugging builds is in the file Misc/SpecialBuilds.txt in the Python source distribution. Builds are available that support tracing of reference counts, debugging the memory allocator, or low-level profiling of the main interpreter loop. Only the most frequently-used builds will be described in the remainder of this section.
Compiling the interpreter with the Py_DEBUG macro defined produces what is generally meant by “a debug build” of Python. Py_DEBUG is enabled in the Unix build by adding --with-pydebug to the configure command. It is also implied by the presence of the not-Python-specific _DEBUG macro. When Py_DEBUG is enabled in the Unix build, compiler optimization is disabled.
In addition to the reference count debugging described below, the following extra checks are performed:
There may be additional checks not mentioned here.
Defining Py_TRACE_REFS enables reference tracing. When defined, a circular doubly linked list of active objects is maintained by adding two extra fields to every PyObject. Total allocations are tracked as well. Upon exit, all existing references are printed. (In interactive mode this happens after every statement run by the interpreter.) Implied by Py_DEBUG.
Please refer to Misc/SpecialBuilds.txt in the Python source distribution for more detailed information.
|
http://docs.python.org/release/3.1.2/c-api/intro.html
|
CC-MAIN-2013-20
|
refinedweb
| 817
| 55.13
|
#include <wx/snglinst.h>
wxSingleInstanceChecker class allows checking that only a single instance of a program is running.
To do it, you should create an object of this class. As long as this object is alive, calls to wxSingleInstanceChecker::IsAnotherRunning from other processes will return true.
As the object should have the life span as big as possible, it makes sense to create it either as a global or in wxApp::OnInit. For example:
Note that by default wxSingleInstanceChecker::CreateDefault() is used to create the checker meaning that it will be initialized differently for different users and thus will allow different users to run the application concurrently which is usually the required behaviour. However if only a single instance of a program should be running system-wide, you need to call Create() with a custom name which does not include wxGetUserId().
This class is implemented for Win32 and Unix platforms (supporting
fcntl() system call, but almost all of modern Unix systems do) only.
Default constructor.
You may call Create() after using it or directly call IsAnotherRunning() in which case CreateDefault() will be implicitly used.
Destructor frees the associated resources.
Note that it is not virtual, this class is not meant to be used polymorphically.
Initialize the object if it had been created using the default constructor.
Note that you can't call Create() more than once, so calling it if the non default ctor had been used is an error.
Calls Create() with default name.
This method simply calls Create() with a string composed of wxApp::GetAppName() and wxGetUserId().
Because this method uses wxApp::GetAppName(), it may only be called after the global application was constructed.
Returns true if another copy of this program is already running and false otherwise.
Notice that if the object was created using the default constructor Create() hadn't been called before this method, it will call CreateDefault() automatically.
|
https://docs.wxwidgets.org/trunk/classwx_single_instance_checker.html
|
CC-MAIN-2021-49
|
refinedweb
| 314
| 53.31
|
Java made easy
RoseIndia has made learning Java easy with its online Java course, Java... tutorials along with Java course that helps
all the beginners in Java to understand the language and has made learning Java
very easy. A beginner just has to go
pal
To find palindrome no in a file - Java Beginners
To find palindrome no in a file hi all i am having a problem...I wanted to write one java program where i have to count the no of palindrome in a file. I tried it with my own but not able to get result.pls help me out
Java Programming video tutorial for beginners
for beginners in Java help them to understand Java step-by-step and in systematic way... application system, real time application, etc. It is easy to learn Java if you... that programmer already know much. But the Java programming video tutorial for beginners Programming Tutorials for beginners
Java Programming tutorials for beginners are made in such a way... simple so that not only Java professionals but Java beginners can also
learn it easily.
For the beginners in Java we bring our best of the best collection
Java for beginners
Java for beginners Java for beginners
Which is the best resource... am looking for the easy to learn Java tutorials. If you can suggest me the best Java video tutorial for beginners.
Thanks
Hi,
Here are the best
Java Course
made easy as you just have to watch a video where an
experienced Java...Java Course provided at RoseIndia spreads into various levels from basic to
professional to advance. These courses are tailor made for both beginners
To check a palindrome number?
To check a palindrome number? program to check a number is palindrome or not using recursion?(wihout converting to string
Java Tutorial Videos
Java Tutorial Videos provided by RoseIndia helps beginners in Java to learn
the language in a very easy and interactive way. All the Java Videos...
program and running it using command prompt.
Tutorial for Beginners in Java... was developed to execute the business logic. You can develop EJB, or Java Beans to process
Online Java Training for Beginners
Online Java Training for Beginners
The online java training for beginners... and benefits of Java.
In this age of advanced technology, Java has made... for the beginners.
The Online Java Programming course for the beginner's
Java Basic Tutorial for Beginners
Java Basic Tutorial for Beginners - Learn how to setup-development
environment and write Java programs
This tutorial will get you started with the Java...)
More tutorials for beginners
Getting
Started with Java
Learn
palindrome array problem
palindrome array problem I'm having trouble figuring this assignment out. Can someone please help me?
Generate (write the code) and save in an array Palidrome[250][5] all the 5 letter words using {a, b, c}
Write the code
Roseindia JSP Tutorial
are made with an objective to help learners grasp the fundamentals of JSP in easy... for beginners as well as experienced programmers as the JSP tutorials... tutorials for you that makes it quite easy for you to create dynamic
Learn Java for beginners
Learning Java for beginners has become an easy task now, with the popularity...
Java Beginners tutorial Home page... in the
field of Java. With online training of Java, RoseIndia brings the course to your
Java tutorials for beginners with examples
Java Video tutorials with examples are being provided to help the beginners
learn the Java programming in an easy way. Java being the most popular and used..., methods, interface, variables, etc.
Java tutorials for beginners with examples
a java program - Java Beginners
for more information.... a java program well sir, i just wanna ask you something regarding... about the second line...
i have made my program but not able to click.
Java projects for beginners
In this tutorial you will be briefed about the Java projects for beginners... and complicated Java, can be become easy with the help of this
tutorials which have been... is more tutorials for Java coding for beginners
What
Add two big numbers - Java Beginners
Add two big numbers - Java Beginners Hi,
I am beginner in Java and leaned basic concepts of Java. Now I am trying to find example code for adding big numbers in Java.
I need basic Java Beginners example. It should easy
prime pal - Java Beginners
prime pal 1) WAP to print all prime-palindrome number range between 1-500
2) WAP to print all prime-Fibonacci number range between 1-500
Hi Friend,
1)Prime and Palindrome:
import java.util.
Converting Anything to String
Java: Converting Anything to String
Summary: Converting any data to strings is easy.
You can do almost everything with concatenation, but can get more... for converting
any object into a string.
printf() was added in Java 5 to use a format
Java - Java Beginners
java. While designing it, i came across a problem. I tried to store the functional dependencies using the hashmap class. e.g. for a dependency A->B, i made... A->B. This i knew after reading the java docs. So is there any workaround features - Java Beginners
program malfunction.
the java designers made hard attemp to alter...java features Why java is called as neutral language hai frnd..
JAVA is not neutral language...but ARCHITECTURE-NEUTRAL..
1 of the main Compilation error. - Java Beginners
on java visit to :
Thanks
static...: Java Compilation error. what is the difference between static
Core Java Tutorial for Beginners
Core Java tutorials for beginners help you to learn the language in an easy way giving you simple examples with explanation. Core Java is the basic of Java language. Java is an Object Oriented Programming language that is made open
|
http://www.roseindia.net/tutorialhelp/comment/95796
|
CC-MAIN-2014-35
|
refinedweb
| 955
| 57.37
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.