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
|
|---|---|---|---|---|---|
uuid_from_string- converts the string representation of a UUID to the binary representation
#include <dce/uuid.h>
void uuid_from_string( unsigned_char_t *string_uuid, uuid_t *uuid, unsigned32 *status);
Input
- string_uuid
- A string UUID. (For information about string UUIDs, see
RPC Data Types.)
Output
- uuid
- Returns the UUID specified by the string_uuid argument.
- status
- Returns the status code from this routine. The status code indicates whether the routine completed successfully, or if not, why not.
Possible status codes and their meanings include:
- uuid_s_ok
- Success.
An application calls the uuid_from_string() routine to convert the string representation of a UUID, string_uuid, to its equivalent binary representation.
None.
uuid_to_string().
Please note that the html version of this specification may contain formatting aberrations. The definitive version is available as an electronic publication on CD-ROM from The Open Group.
|
http://pubs.opengroup.org/onlinepubs/9629399/uuid_from_string.htm
|
CC-MAIN-2015-18
|
refinedweb
| 130
| 50.12
|
Opened 5 years ago
Closed 4 years ago
Last modified 4 years ago
#18478 closed Cleanup/optimization (fixed)
Field.get_default will stringify everything that isn't a callable
Description
I'm using a JSON-encoded field that can take any python data structure as default, this way:
info = fields.ContactInfoField("Contact info", blank=True, default={"a":u"I ♥ Django"})
and found out that I was getting
"{'a': u'I \\u2665 Django'}" as a default value in my model objects.
I tracked it down to Field.get_default, which stringifies all non-callables:
def get_default(self): """ Returns the default value for this field. """ if self.has_default(): if callable(self.default): return self.default() return force_unicode(self.default, strings_only=True) if (not self.empty_strings_allowed or (self.null and not connection.features.interprets_empty_strings_as_nulls)): return None return ""
Indeed this works as expected:
info = fields.ContactInfoField("Contact info", blank=True, default=lambda:{{"a":u"I ♥ Django"})
I cannot understand the reason for the different treatment of values and callables, and comments don't help. Field documentation does not mention this behaviour either. From what little I can understand, this looks like a bug,
Attachments (1)
Change History (7)
comment:1 Changed 5 years ago by
comment:2 Changed 5 years ago by
comment:3 Changed 5 years ago by
Well, it took me a bit of time to find it, and I wasn't aware of this reason :)
Accepting as a documentation issue.
Duplicate of #8633, and the reason is explained there.
|
https://code.djangoproject.com/ticket/18478
|
CC-MAIN-2017-09
|
refinedweb
| 246
| 58.28
|
👋 Goodbye Sprockets. Welcome Webpacker
A simple guide to switch from Sprockets to Webpacker
Updated on the 9th October 2018
This guide will let you through the process of migrating your Rails Application from Sprockets to Webpacker. Even though Webpacker suggests to keep using Sprockets for CSS and images, I don’t really see why we should keep two bundlers at the same time when we can simply use only Webpacker. If you want I have a video available of this tutorial that explains how to migrate JS and CSS (but not images).
The requirements
We’ll start this guide from a Rails 5.1 application which uses Sprockets. In our case we used EcmaScript6 and therefore we have the
sprockets-es6 gem in our Gemfile (we were not using Sprockets 4).
Why didn’t we use Webpacker right from the beginning has a really easy answer: even if Rails ❤️ Javascript, in order to use Webpacker you needed to run an additional process and have a lot of additional configuration files. All of that changed with Webpacker 3 and that’s why, today, we’ll switch to it and never come back.
To follow this guide I suggest you to migrate your application to Rails 5.1 and then proceed, but that’s not mandatory: when developing there are a lot of things that are not necessary but, from time to time, you should take the chance to do them 😉.
Adding the gems
The first thing to do is to add
webpacker-rails gem to our project’s Gemfile:
gem 'webpacker', '~> 3.5'
and install it, following the project’s README:
bundle
bundle exec rails webpacker:install
Now we have Webpacker ready and we can already start using it! 🎉
I’ll not explain to you what does this do and which files it generates: you don’t need to know that now. What you need is to drop Sprockets and that’s our goal today.
Test it
Is it really working? Let’s test it first.
Let’s meet our first generated folder:
app/javascript. That’s the equivalent of our old, dear,
app/assets/javascript folder and, as in the old one, you’ll find an
application.js file you can start from.
That file is the exact equivalent of
app/assets/javascript/application.js: is the starting point where we’ll include all our JS resources.
Let’s add it to our template, as we did for the old one, using
= javascript_pack_tag 'application'
(you may want to add the option
'data-turbolinks-track': 'reload' if you are using Turbolinks.)
and we should see the “Hello World” message in the Chrome Developer Tools, which confirms that everything is working fine:
Migrate Javascript
Now that we have Webpacker installed and everything is working fine we can proceed by moving our old Javascript files. Our
application.js example has a very simple structure:
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= require formvalidation/formValidation
//= require formvalidation/bootstrap4.min
//= require_tree .
it basically requires some libraries and then includes our js and es6 files.
Let’s move the last ones first: the steps for that are easy:
- Remove
//= require_tree .from your old
app/assets/javascript.js
- Move all files and folders from
app/assets/javascriptto
/app/javascript/src/js(rename eventually
.es6files to
.js)
- Import all your files in the new
application.js
import '../src/js/your_js_filename';
Migrate libraries
Now is time to move the libraries we are using. Since we are talking about a very simple Rails app, those are our libraries at the moment:
//= require jquery
//= require rails-ujs
//= require turbolinks
//= require bootstrap-sprockets
We need to download the equivalent Webpack modules and require them.
Setup jquery
If you are using JQuery in your app, you probably don’t want to get rid of it now (also because Bootstrap still requires it…) so we can migrate it. Add the package:
yarn add jquery
Now we have to configure Webpacker to include it in all our environments. To do that we change the
environment.js file.
# app/config/webpack/environment.js
const {environment} = require('@rails/webpacker');
const webpack = require('webpack');
environment.plugins.append('Provide', new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}));
module.exports = environment;
so you can finally use it into your
application.js file.
# app/javascript/packs/application.js
$(function () {
console.log('Hello World from Webpacker');
});
Setup rails-ujs and turbolinks
Install the modules:
yarn add rails-ujs turbolinks
and start them:
# app/javascript/packs/application.js
import Rails from 'rails-ujs';
import Turbolinks from 'turbolinks';
Rails.start();
Turbolinks.start();
Setup Bootstrap
The last piece missing is Bootstrap. JQuery is in place so we can simply install the package and require it.
yarn add bootstrap@4.0.0 popper.js
add Popper to the environment configuration:
# app/config/webpack/environment.js
...
environment.plugins.append('Provide', new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: ['popper.js', 'default']
}));
...
and import the plugins:
# app/javascript/packs/application.js
import 'bootstrap/dist/js/bootstrap';
With Bootstrap, we have successfully moved all our Javascript resources to webpacker. We can remove the old
application.js file and remove the import of it from our template.
As you can see is pretty easy to move javascript from Sprockets to Webpacker. Once you understand how files and modules are organised you’ll see that is easy as it was with Sprockets and you can remove some of the gems that were just including javascript and import the correspondent npm package. In our case, for example, we could already remove
sprockets-es6 ,
jquery-turbolinks and
jquery-rails .
Webpacker is meant to manage javascript files, therefore we can stop here and keep using sprockets for images and CSS, but Webpack can manage also those resources, so I think is worth to take a look on how to migrate them as well.
Migrate CSS
We can manage also stylesheets with Webpacker. Our application contains some custom SCSS files in our assets folder, bootstrap and font-awesome from a gem and a stylesheet in the vendor folder.
@import 'font-awesome';
@import 'shared/variables';
@import 'bootstrap';
@import 'transactions';
@import 'custom_buttons';
@import 'formValidation.min';
We’ll start by renaming the Webpacker folder, because it feels really wrong to place stylesheets into a javascript folder. Rename the
app/javascript into
app/webpacker and move all the javascript files from
app/javascript/src to
app/webpacker/src/javascript.
Create a
app/webpacker/packs/stylesheets.scss file and move your css resources inside
app/webpacker/src/stylesheets folder. That file will look very similar to your original one:
#app/webpacker/packs/stylesheets.scss
@import '../src/stylesheets/transactions';
@import '../src/stylesheets/custom_buttons';
and include the following call in your template:
= stylesheet_pack_tag 'stylesheets'
Bootstrap
To have bootstrap working, and compiled from scss, you can simply include the following in our new
stylesheets.scss
@import '~bootstrap/scss/bootstrap';
Since we customised our bootstrap, we can import the variables as we were doing before via
@import '../src/stylesheets/shared/variables';
before the import of bootstrap.
If you were using scss before, in the end, it doesn’t change that much.
We need, in the end, to import font-awesome from the npm package instead of the gem.
# fontawesome 4
yarn add font-awesome
# fontawesome 5
yarn add @fortawesome/fontawesome-free
and
# fontawesome 4
$fa-font-path: "~font-awesome/fonts";
@import '~font-awesome/scss/font-awesome';
# fontawesome 5
$fa-font-path: '~@fortawesome/fontawesome-free/webfonts';
@import '~@fortawesome/fontawesome-free/scss/fontawesome';
@import '~@fortawesome/fontawesome-free/scss/solid';
and you can remove the old link to the sprockets file
= stylesheet_link_tag 'application'
Images
To migrate your images is relatively easy. What we are going to do is to create a pack containing all the images and import them.
Create a folder
app/webpack/images and move all your images in that folder.
Then create an
index.js file in that folder to reference all of them. The content will look like the following:
# app/webpack/images/index.js
import './btn_google_dark.svg'
import './renuo_logo.png'
import './goody.png'
import './icon.png'
Create a file
app/webpack/packs/images.js and import the content of that folder:
# app/webpack/packs/images.js
import '../images'
Now all your images are available through Webpacker. To use them you need to replace your old images using the
asset_pack_path helper.
- asset_path('icon.png')
+ asset_pack_path('images/icon.png')
Since Sprockets helper are not available anymore you need to replace them in you SCSS files:
.google-icon {
- background-image: image-url('btn_google_dark.svg');
+ background-image: url('../images/btn_google_dark.svg');
}
Conclusion
You have successfully replaced Sprockets with Webpacker and you can start take advantage of all the benefits of it like Hot Module Reloading or Bundle analysis.
Does this mean you won’t use Sprockets anymore? From my point of view yes.
It simply doesn’t make sense to use a slower tool with less features when using Webpacker is so easy. I already started using the following options when creating a new application and I really don’t miss Sprockets.
rails new my_app --skip-sprockets --webpack
Using Webpacker you can add a frontend framework very quickly as soon as you’ll need it and it’s also much faster.
If I missed something or you have questions, leave a comment. If you want to read about some of the cool features you can use now that you have Webpacker installed, read my articles about Hot Module Reloading for CSS and Hot Module Reloading for React.
|
https://medium.com/@coorasse/goodbye-sprockets-welcome-webpacker-3-0-ff877fb8fa79
|
CC-MAIN-2019-04
|
refinedweb
| 1,570
| 55.95
|
El 20 Apr 2006 00:32:43 +0200,Andi Kleen <ak@suse.de> escribió:> Some people claim it will be used in the future in a particular application> that most people I know don't want to have anything to do with,> but right now that application uses an own file system that is also unlikely> to work with selinux or anything so it won't change anything for that.> > I'm not aware of any other proposed application.However such application may exist in the future (which is why the featurewas implemented, i guess). If AppArmor becomes widespread in the future(well suse has it anyway so it's already quite widespread) it won't be easyto create succesful apps which play with namespaces, not to speak that itwon't be possible to "securize" such apps. From my user POV it seemsreally weird that a feature forbids you from using another unrelated feature.-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
|
http://lkml.org/lkml/2006/4/19/339
|
CC-MAIN-2016-30
|
refinedweb
| 182
| 50.67
|
Device Identification is a Native Extension that provides access to device identification data. It is possible to read the IMEI code, IMEI SV code, Device Serial Number, MODEL and IMSI code.
Sample
import com.flashvisions.mobile.android.extensions.system.data.DeviceIdentity; import com.flashvisions.mobile.android.extensions.system.SystemNFO; var systemInfo:SystemNFO = new SystemNFO(); var result:DeviceIdentity = systemInfo.getDeviceIdentity(); trace(result.IMEI); trace(result.IMEISV); trace(result.IMSI); trace(result.MODEL); trace(result.SERIAL); trace(result.PHONENUMBER);
thx for that !
You’re welcome!
5$ and thats work only on android ?
It’s not that bad
I agree that it could be much better if iOS was supported as well.
have you test to build an ANE like this one ?
No, I haven’t. In fact I never tried to build any ANE so far.
Hi, can’t access the files. Links please.
Hi Bayo! Looks like their website is down for now. I am not an affiliate or something, I just listed their ANE here. I am afraid you will have to wait until the website is back online.
Hi, i have build a free version
Hey there! That’s awesome! I will add your version to the site tomorrow. Thanks!
if you have ideas for others extensions, send me an email, i can build it 😉
That’s outstanding! Thank you again for the contribution.
[…] Device Identification Native Extension that provides access to device identification data. It is possible to read the IMEI code, IMEI SV code, Device Serial Number, MODEL and IMSI code. […]
Hi Chris, can you please walk me through now to use the extension? I have it downloaded already. And while at it, is it applicable to iOS too or just Android? Thanks
not work with Flash Professional CS5.5
How to use this for action script 3?
|
http://www.as3gamegears.com/air-native-extension/device-identification/
|
CC-MAIN-2017-43
|
refinedweb
| 301
| 52.66
|
Java is a powerful programming language and it supports various data structures to make the life of programmers easy. In this article we will take a look at one such data structure that is Java Queue. These are the pointers this article focus on,
- Queue In Java
- Implementation Of Java Queue
- Methods In Java Queue
- Program To Demonstrate Queue Methods
- Iterating Through A Java Queue
Queue In Java
A queue is a data structure which follows the principle of FIFO (First-In-First-Out) i.e. the elements are inserted at the end of the list, and are deleted from the beginning of the list. This interface is available in the java.util.package and extends the Collection Interface.
Queue supports multiple methods, including insertion and deletion. The queues available in java.util.package are known as Unbounded Queues , while the queues present in the java.util.concurrent package are known are Bounded Queues.
All queues, except the Deques, support insertion at the end and deletion from the front. Deques support insertion and deletion of elements at both the ends.
Let us move to the next topic of this article on Java Queue,
Implementation Of Java Queue
In order to use the queue interface, we need to instantiate a concrete class. Following are the few implementations that can be used:
- util.LinkedList
- util.PriorityQueue
Since these implementations are not thread safe, PriorityBlockingQueue acts as an alternative for thread safe implementation.
Example:
Queue q1 = new LinkedList();
Queue q2 = new PriorityQueue();
Let us take a lok at some important Java Queue methods,
Methods In Java Queue
- add(): The add() method is used to insert elements at the end, or at the tail of the queue. The method is inherited from the Collection interface.
- offer(): The offer() method is preferable to the add() method, as it inserts the specified element into the queue without violating any capacity restrictions.
- peek(): The peek() method is used to look at the front of the queue without removing it. If the queue is empty, it returns a null value.
- element(): If the queue is empty, the method throws NoSuchElementException.
- remove(): The remove() method removes the front of the queue and returns it. Throws NoSuchElementException if the queue is empty.
- poll(): The poll() method removes the beginning of the queue and returns it. If the queue is empty, it returns a null value.
An overview of the following methods is given as follows:
Let us take a look the demonstration now,
Program To Demonstrate Queue Methods
import java.util.*; public class Main { public static void main(String[] args) { //We cannot create instance of a Queue since it is an interface, thus we Queue<String> q1 = new LinkedList<String>(); //Adding elements to the Queue q1.add("I"); q1.add("Love"); q1.add("Rock"); q1.add("And"); q1.add("Roll"); System.out.println("Elements in Queue:"+q1); /* * We can remove an element from Queue using remove() method, *this removes the first element from the Queue */ System.out.println("Removed element: "+q1.remove()); /* *element() method - this returns the head of the *Queue. */ System.out.println("Head: "+q1.element()); /* *poll() method - this removes and returns the *head of the Queue. Returns null if the Queue is empty */ System.out.println("poll(): "+q1.poll()); /* *peek() method - it works same as element() method, *however, it returns null if the Queue is empty */ System.out.println("peek(): "+q1.peek()); //Displaying the elements of Queue System.out.println("Elements in Queue:"+q1); } }
Output:
Elements in Queue:[I, Love, Rock, And, Roll]
Removed element: I
Head: Love
poll(): Love
peek(): Rock
Elements in Queue:[Rock, And, Roll]. In the above example, Generic Queue has been used.
In this type of queue, we can limit the type of object inserted into the queue. In our example, we can have only string instances inserted into the queue.
Iterating Through A Java Queue
Elements in a java queue can be iterated using the following code:
Queue q1 = new LinkedList();
q1.add(“Rock”);
q1.add(“And”);
q1.add(“Roll”);
//access via Iterator
Iterator iterator = q1.iterator();
while(iterator.hasNext(){
String element = (String) iterator.next();
}
//access via new for-loop
for(Object object : q1) {
String element = (String) object;
}
The sequence in which the elements are iterated depends on the implementation of queue.
While there are multiple methods that a Java Queue can implement, the most important methods have been discussed here.
Thus we have come to an end of this article on ‘Java Queue’..
|
https://www.edureka.co/blog/java-queue/
|
CC-MAIN-2019-35
|
refinedweb
| 742
| 55.84
|
HTTPS support for jupyterhub deployment on k8s
Problem to solveProblem to solve
Jupyterhub deployment does not provide https.
Further detailsFurther details
(Include use cases, benefits, and/or goals)
ProposalProposal
JupyterHub deployment from GitLab managed apps on k8s to support https out of the box.
This can be acomplished using cert manager:
There are a few parts to this:
1. Install
cert-manager on the cluster
Original docs:
I installed it using Helm. Since we use mutual auth for now I had to hack together a rails script to generate a helm client key. Obviously when we implement this feature to deploy
cert-manager via GitLab you won't need to do this. But for the record here is the script to be run from the rails console:
helm = Clusters::Applications::Helm.last; nil File.open('/tmp/ca_cert.pem', 'w') { |f| f.write(helm.ca_cert) }; nil client_cert = helm.issue_client_cert; nil File.open('/tmp/key.pem', 'w') { |f| f.write(client_cert.key_string) }; nil File.open('/tmp/cert.pem', 'w') { |f| f.write(client_cert.cert_string) }; nil
Now once we have our helm certs in place we can install
cert-manager like so:
helm init --client-only --tiller-namespace gitlab-managed-apps helm install stable/cert-manager --name cert-manager --namespace gitlab-managed-apps --tiller-namespace gitlab-managed-apps --tls --tls-ca-cert /tmp/ca_cert.pem --tls-cert /tmp/cert.pem --tls-key /tmp/key.pem
2. Configure the
ClusterIssuer
Original docs:
kubectl create -f - <<EOF apiVersion: certmanager.k8s.io/v1alpha1 kind: ClusterIssuer metadata: name: letsencrypt-prod spec: acme: server: email: my-email@example.com privateKeySecretRef: name: letsencrypt-prod http01: {} EOF
3. Configure the
ingress-shim
Original docs:
helm upgrade cert-manager stable/cert-manager \ --namespace gitlab-managed-apps --tiller-namespace gitlab-managed-apps \ --tls --tls-ca-cert /tmp/ca_cert.pem --tls-cert /tmp/cert.pem --tls-key /tmp/key.pem \ --set ingressShim.defaultIssuerName=letsencrypt-prod --set ingressShim.defaultIssuerKind=ClusterIssuer
NOTE After following all these steps the
cert-manager should create a
Certificate for you and this should automatically be picked up by the running ingress and your Auto DevOps deployed app should be reachable by
http:// URL.
NOTE I did run into an issue where the HTTPS URL was still constantly returning
default backend - 404. In the end I figured out by looking through
kubectl logs deployments/cert-manager cert-manager --namespace gitlab-managed-apps -f that it was caused by the domain name being longer than 64 bytes. So the only way I was able to get a shorter domain name was by using a shorter group and project name as the domain name is generated by the Auto DevOps pipeline (see)
What does success look like, and how can we measure that?What does success look like, and how can we measure that?
When jupyterhub is deployed, https is default.
Links / referencesLinks / references
MR
|
https://gitlab.com/gitlab-org/gitlab-foss/issues/52753
|
CC-MAIN-2019-43
|
refinedweb
| 473
| 50.94
|
I'm attempting to publish a geojson file as a hosted layer to ArcGIS Online but it gives me "There was an error". However, if I add it as a layer to an already created map, it shows just fine.
I have the permissions of a creator and publisher under my organization.
The type is a Feature Collection, crs is set, I'm not really sure what else it could be.
Has anyone had this error before?
I have seen similar issue with other datatypes at some point and if i remember correctly it was due using wrong item type or similar on the publish method.
Some documentation that solved my issue:
arcgis.gis module — arcgis 1.7.0 documentation
Publish Item—ArcGIS REST API: Users, groups, and content | ArcGIS for Developers
If you can share the code, I could have a better look on it.
Apologies for not sharing the code. I wasn't sure if there was a bug out there but it pulls a created .geojson and here is a sample
from arcgis.gis import GIS
import os
import json
username = "username"
password = "password"
gis = GIS("arcgis online organization website", username, password)
data_path = os.path.join(r"C:\Users\taylor\Desktop\rentals.geojson")
item_properties = {'type': 'geojson',
'title':'Rental Properties',
'description':'Rental Properties',
'tags':'rental'}
Rentals = gis.content.add(item_properties, data_path)
published_service = Rentals.publish(file_type='FeatureCollection')
{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties": { "OBJECTID": 1218029, "Parcel Number": "1461", "LICENSENUMBER": "RHL20", "Address": "42 WAY", "LICENSESTATUS": "Issued", "APPLIEDDATE": "2017-09-29T00:00:00", "ISSUEDDATE": "2017-09-29T00:00:00", "EXPIRATIONDATE": "2021-09-29T00:00:00", "LASTRENEWALDATE": null, "SUBCOMMUNITY": "North", "RENTALTYPE": "Standard Rental", "COMPLEXNAME": null, "BUILDINGTYPE": "Single Family Dwelling", "ENERGYCOMPLIANT": "Yes", "BUILDINGIDENTIFICATION": "RHL2015-00466", "DWELLINGUNITSONCASE": 1, "ROOMINGUNITSONCASE": 0.0, "MAXIMUMUNRELATEDOCCUPANTS": 3, "OCCUPANCYBEFOREREZONING": "NO", "PROFESSIONALLICENSEHOLDERNAME": "null", "PROFESSIONALLICENSEHOLDERCMPNY": null, "PROFESSIONALLICENSEYEAR": 2017.0, "SHAPEAREA": 70551.149319832402, "SHAPELEN": 1194.74474079076, "strap_x": "R00368 ", "strap_y": "R00968 ", "eff": "1974", "remodel": 0.0, "status_cd": "A ", "code": "RES" }, "geometry": { "type": "Polygon", "coordinates": [ [ [ -105.282824422242228, 40.050975815768872 ], [ -105.282243756596387, 40.050975449135876 ], [ -105.282248337352939, 40.05217015748709 ], [ -105.282825708018564, 40.052170943882906 ], [ -105.282825425662821, 40.051946591042061 ], [ -105.282825176117441, 40.051711208021224 ], [ -105.28282492234834, 40.051479357327715 ], [ -105.282824676197606, 40.051245852152 ], [ -105.282824422242228, 40.050975815768872 ] ] ] } },
}
There's about 1846 records in my code, this is only one of them
I tried your geojson file (i fixed it to be valid though) with following code and it seems to work for me.
I checked what agol will add to the json metadata when adding things manually to agol and copied the exact formats from there.
rentals_item = gis.content.add(
item_properties = {
'type': 'GeoJson',
'title':'Rental Properties',
'typeKeywords': ['Coordinates Type', 'CRS', 'Feature', 'FeatureCollection', 'GeoJSON', 'Geometry', 'GeometryCollection'], # this seems to be what manual add will add, works without this as well
'description':'Rental Properties',
'tags':'rental'
},
data = r'./example-data/example.geojson')
rentals_item
published_service = rentals_item.publish(file_type='GeoJson') # file_type is not needed since seems to work without it as well
published_service
Thank you Antii! I'll try out this code. What did you fix in the geojson to make it valid? Maybe it's something within my geojson file when it's created using geopandas?
No worries. let us know if that fixes your issue.
I just made sure that it's valid Json since you posted only one item and the format if broken due that.
This is the error code I get when I attempt to publish
published_service = rentals_item.publish()
File "C:\Users\tkravits\Desktop\Rentals\interpreter_3.7\lib\site-packages\arcgis\gis\__init__.py", line 8865, in publish
serviceitem_id = self._check_publish_status(ret, folder)
File "C:\Users\tkravits\Desktop\Rentals\interpreter_3.7\lib\site-packages\arcgis\gis\__init__.py", line 9092, in _check_publish_status
raise Exception("Job failed.")
Exception: Job failed.
However it shows up as a hosted layer and a geojson file within my content, but when I view the hosted layer in the Map Viewer it zooms to the extent of the area, but there is no data found in the rental property map. I tested the geojson using geojson.io and it displays perfectly with the data intact. Here's a snippet of what shows up below.
I got the feature visible that was in your example. Maybe there is something wrong on some of the features? Can you get them visible if you publish everything manually? Not to the map directly but add as content file and then publish it as a service? Does that service has all the features?
I assume that you cannot share the data publicly for me to test.
So if I add the geojson file manually (upload a file) to the map, it works. If I add them as content and host it as a feature layer (manually), it also fails. Same "There was an error" message that goes up. The field names populate correctly, but there is no data attached to it. Similar to that picture posted above.
Unfortunately, I can't really share this data but I greatly appreciate you helping me.
That sounds like that there might be something wrong in the publish part of the ArcGIS REST services for the GeoJson since it works for the webmaps but not for the manual or automated publishing workflow. Since the python Api is basically just a wrapper around the same services used with the ArcGIS Online UI, its highly pointing that way. Maybe folks from the Python API / REST API could clarify that...
|
https://community.esri.com/t5/arcgis-api-for-python-questions/geojson-hosted-layer-error/m-p/847353
|
CC-MAIN-2021-39
|
refinedweb
| 906
| 57.47
|
[Date Index]
[Thread Index]
[Author Index]
Re: Pattern matching
John Leary wrote:
>.
Here's one way to do it: implement a matchTemplatesQ function that
yields true if any of the templates is matched.
Note that matchTemplatesQ depends on listTemplates which is not given as
an argument -- Personally I don't have a problem with polution of the
global namespace, but you'll probably get some followup on this...
matchTemplatesQ[s_String] :=
Or @@ ((MatchQ[Characters[s], Characters[#] /. "?" -> _]) & /@
listTemplates)
Select[listData, matchTemplatesQ]
Out:
{"400HGXX--", "960KG1D--"}
The mystical @@, /@ and ( # )& stuff is just a shorthand for Apply,
Map and Function, which you might want to look up in help.
Hope this helps
/Janus--
||
Janus Wesenberg _||_
Ph.D. Student at Quantop ( ) jaw@^^^^^^^^^
\ /
||
|
http://forums.wolfram.com/mathgroup/archive/2002/Apr/msg00414.html
|
CC-MAIN-2014-15
|
refinedweb
| 119
| 72.46
|
Code you and fail to build code that has warnings in it.
Many of these warnings don’t impact how your code runs. They just ask you “are you sure this is what you are meaning to do?”
For example, if you leave out a “break” in a switch/case block, the compiler can warn you about that:
x = 1; switch( x ) { case 1: printf("x is one\n"); // did I mean to not have a break here? case 2: printf("x is two\n"); break; default: printf("I don't know what X is\n"); break; }
This code would print:
x is one x is two
…because without the “break” in the “case 1”, the code drops down to the following case. I found several places in our embedded TCP/IP stack where this was being done intentionally, and the author had left comments like “/* falls through below */” to let future observers know their intent. But, with warnings cranked up, it would no longer build for me, even though it was perfectly fine code working as designed.
I found there was a GCC thing you could do where you put in “//no break” as a comment and it removes that warning. I expect that are many more “yes, I really mean to do this” comments GCC supports, but I have not looked in to it yet.
Size (of int) matters
Another issue I would see would be warnings when you used the wrong specifier in a printf. Code might compile fine without warning on a PC, but generate all kinds of warnings on a different architecture where an “int” might be a different size. For example:
int answer = 42; printf("The answer is %d\n", answer);
On my PC, “%d” can print an “int” type just fine. But, if I had used a “long” data type, it would error out:
long answer = 42; printf("The answer is %d\n", answer);
This produces this warning/error:
error: format '%d' expects argument of type 'int', but argument 2 has type 'long int' [-Werror=format=]|
You need to use the “l” (long) specifier (“%ld”) to be correct:
long answer = 42; printf("The answer is %ld\n", answer);
I found that code that compiled without warnings on the PC would not do the same on one of my embedded target devices.
%u versus %d: Fight!
Another warning I had to deal with was printf() and using “%d” versus “%u”. Most code I see always uses %d, which is for a signed value which can be positive or negative. It seems works just fine is you print an unsigned integer type:
unsigned int z; z = 100; printf("z is %d\n", z);
Even though the data type for z is unsigned, the value is positive so it prints out a positive number. After all, a signed value can be positive.
But, it is more correct to use “%u” when printing unsigned values. And, here is an example of why it is important to use the proper specifier… Consider this:
#include <limits.h> // for UINT_MAX unsigned int x; x = UINT_MAX; // largest unsigned int printf("x using %%d is %d\n", x); printf("x using %%u is %u\n", x);
This prints:
x using %d is -1 x using %u is 4294967295
In this case, %d is not giving you what you expect. For a 32-bit int (in this example), ULONG_MAX of 4294967295 is all bits set:
11111111 11111111 11111111 11111111
That represents a -1 if the value was a signed integer, and that’s what %d is told it is. Thus, while %d works fine for smaller values, any value large enough to set that end bit (that represents a negative value for a signed int) will produce incorrect results.
So, yeah, it will work if you *know* you are never printing values that large, but %u would still be the proper one to use when printing unsigned integers… And you won’t get that warning :)
It would be nice if compilers and lint programs agreed on comments that mark “No, I really meant to do this” situations. Some flavor of lint I used wanted /* FALLTHROUGH */ to mark intentional case fallthroughs.
OTOH, I think Go has the right idea. You don’t have a special statement to break; instead, you have a fallthrough statement required to fall through. As a consequence:
1. The more common case, not falling through, is the short one.
2. The less common case is explicitly pointed out–makes control flow bugs less likely.
3. It avoids the major C irritant of using the same [expletive] keyword for getting out of a switch statement and getting out of a loop. In C, if you loop around a switch statement and in some cases want to get out of the loop, all your alternatives are all ugly.
The Go implementation makes sense. I need to find a free Lint for us to start using at work. I have our code compiling without errors now (all, extra) but I had to ignore the tcp/ip stack we use since it’s …. not. Lint could find more issues that the compiler won’t.
splint, aka the lint formerly known as lclint, is your friend.
Sigh…. it looks like it’s not around any more. has a list of lint tools for various languages. It includes both open source and proprietary programs. Sadly, I don’t think any open source lint can support MISRA, which is liable to be of interest to you.
Do you use clang? Check out clang-tidy.
I am stuck in GCC and Eclipse World again.
If you want to get hard core, check out
|
https://subethasoftware.com/2017/12/04/c-warnings-d-versus-u-and-more-c-fun/
|
CC-MAIN-2018-17
|
refinedweb
| 945
| 76.35
|
72063/how-to-override-the-django-admin-translation
I'm trying to override the default translations of Django's admin site.
I'm using Django 1.6. My settings.py contains:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# ...
LANGUAGE_CODE = 'nl'
USE_I18N = True
USE_L10N = True
LOCALE_PATHS = (os.path.join(BASE_DIR, "locale"),)
I have copied the file django/contrib/admin/locale/nl/LC_MESSAGES/django.po to my_project/locale/nl/LC_MESSAGES/django.po and I've made some changes to it.
Next, I have run python manage.py compilemessages and python manage.py runserver.
When I visit localhost:8000/admin, however, I'm still seeing Django's default admin translations. What am I doing wrong?
Hello @kartik,
Just as you can override a Django-provided admin template by duplicating the template's name and directory structure within our own project, you can override Django-provided admin translations by duplicating a .po file's name and directory structure within our project.
Django's admin translations live in django/contrib/admin/locale/ and are organized by language in directories named [language code]/LC_MESSAGES/. These individual language directories contain two .po files, django.po and djangojs.po, and their respective compiled .mo files. You will be overriding the .po files, and compiling our own .mo files.
The first thing you have to do is enable translations in settings, and tell Django where you store our translation files.
settings.py
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# ...
LANGUAGE_CODE = 'nl-NL'
USE_I18N = True
USE_L10N = True
LOCALE_PATHS = (os.path.join(BASE_DIR, "locale"),)
Hope this works!!
Thanks!!
Hello @kartik,
To be more specific, in admin.py of any ...READ MORE
In the database, I want to add ...READ MORE
Hello @kartik,
The << part is wrong, use < instead:
$ ./manage.py shell ...READ MORE
Hello @kartik,
Try this in your queryset:
print my_queryset.query
For ...READ MORE
You can also use the random library's ...READ MORE
Syntax :
list. count(value)
Code:
colors = ['red', 'green', ...READ MORE
Enumerate() method adds a counter to an ...READ MORE
You can simply the built-in function in ...READ MORE
Hello @kartik,
Set show_change_link to True (False by default) in your inline ...READ MORE
Hello @kartik,
You can override templates/admin/index.html and add the JavaScript ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in.
|
https://www.edureka.co/community/72063/how-to-override-the-django-admin-translation?show=72064
|
CC-MAIN-2022-27
|
refinedweb
| 403
| 62.64
|
Red herring is something to distract someone from the real issue.]]>
Outrageous! The chances of dying from these trigers is 1:1,624,927.000.And all the bomb threats at my school are triggers I bet.]]>
whats this red herring you speak of?]]>
me again. just letting everyone know i live in california and its only 9:27 here, not 11:27, so im not up too late:)]]>
I'm doing a debate in school that cell phones should be allowed in school, and this is one of my "enemy's" defenses. Any ideas on how to convince others that this wont happen in a school?]]>
"So it becomes patriotic to stop returning phone calls?"
You know, that would improve my quality of life immeasurably.]]>
So it becomes patriotic to stop returning phone calls? That's the probable real agenda, somebody wants his boss to quit bugging him with phone calls.
Since other people's cell phones irritate me, how about this bonehead idea? Have the government buy up autodialers to repeatedly call all cell phone numbers around the clock, again and again, so as to trigger bombs prematurely? Sounds good, doesn't it? The newsies would love it -- if it bleeds, it leads. (And people would turn the damn things off, pleasing me to no end.)
@jnf:
Maybe this isn't as obvious as I thought; a lot of apparently intelligent people are missing the yawning, jumbo-sized problem in the scheme. The problem isn't that it couldn't work; it could. The problem isn't (just) that it's dangerous to the bomber (although it is). The problem:
> 1) not everyone calls back numbers anyways, and even if they do, you cannot determine when they will.
Yes -- and this is the fundamental problem! The terrorist is using an elaborate, high-tech, forensics-rich solution to get a random initiation time! That's dumb: the point of using a cell phone is to get exact control over the device, right up to initiation. If the terrorist doesn't care when it goes off, he could do it with a parking meter reminder or an alarm clock or a smouldering cigarette or any of a dozen other cheap, simple solutions which additionally give him some time to get clear.
All talk of ANI spoofing etc is a red herring [1]; if they just used a timer they could get the same effect and yet guarantee the phone network would have no record at all.
> This could be countered easily by just increasing the number of people called, the more people called,
> the higher the chance of someone calling back/the higher the chance of someone calling back soon.
That doesn't solve the problem, just shifts it slightly. The distribution function for detonation time is replaced by its "extreme value distribution", a problem well known from reliability theory. Then by making N outgoing calls the terrorist [2]:
* decreases the average detonation time by a factor of N;
* greatly reduces the chance of total failure; but
* increases the odds of an "own goal" by a factor of N times.
> 2.) Some people will answer the phone. This is good for them, simply start to say something important then hangup
> and wait for them to callback.
If the terrorists did that, then with high probability the dupe will either call back immediately or not at all -- the two worst possible results (for the bad guys)!
___
1. ANI spoofing by VOIP by itself is probably _not_ good enough to stop them finding the terrorists; the police can figure which VOIP gateway they came through, then go after their IP logs. But in any case I seriously doubt that these killers are anything remotely like that sophisticated. And it's a red herring, the idea is still dumb even if they manage to perfectly conceal the origin of their call.
2. Assuming N is not extremely large, the call return time is exponentially distributed, and that the time the terrorist takes to get away is at least several times quicker than the average call return time. The second assumption is generally a good approximation. If the first or third assumption is false, the scheme is almost guaranteed to fail every time.
This is not such a ridiculuous statement from the Thai authorities. What they're saying is that just because they find the person who triggered the bomb, and maybe he is a good match for a terrorism profile, this doesn't mean they have a prime suspect.]]>
As most people here noticed straight away, the supposed terrorist plan outlined by Sora-at Klinpratum (the Thai minister, hereinafter "SaK") is the work of an idiot. So one might wonder, why does SaK apparently believe it? Maybe, just maybe, the terrorists _are_ idiots* and it is true. But then, even more curiously, why is SaK trying to stop it when it is likely to reduce casualties whilst increasing the chance of a terrorist "own goal"?
Musing about this I chanced on a simple but much cleverer attack scenario which could be thwarted by SaK making this statement. If this speculation is true, then SaK's statement is a white lie designed to foil the plot without revealing the source of information about it. Moreover, the false statement would be effective at thwarting the plot even if everyone ignored it and continued to return missed calls at the same rate as ever.
Of course I am rather reluctant to publish the idea so I can't be sure if it is evilly brilliant or I am just going quietly mad. However the point is, I suppose, that just because someone says something foolish, doesn't mean he's a fool.
____
* It is of course a great danger to underestimate your opponents, and I am sure some members of the pan-Islamist grand coalition are quite clever. But AQ-and-affiliates _tactics_ often seem to me to be surprisingly INflexible at the foot soldier level, and I wouldn't be especially surprised if these devices were being made by some guy slavishly following a xeroxed, dog-eared recipe, and it has simply never occurred to him that there are other ways to do it.
While I agree this does in fact sound like a bad 80's movie, when you think about it some, its really not a bad idea and it is pretty clever. I mean, you have a couple factors to deal with here:
1) not everyone calls back numbers anyways, and even if they do, you cannot determine when they will. This could be countered easily by just increasing the number of people called, the more people called, the higher the chance of someone calling back/the higher the chance of someone calling back soon.
2.) Some people will answer the phone. This is good for them, simply start to say something important then hangup and wait for them to callback.
3.) In regards to everyone commenting on the inability of the person to stay alive. This is a foolish premise. In addition to ani's being easily spoofed, you then open up holes like 'call forwarding'. I know call forwarding was used quite a bit previously to avoid being traced, and I'd be surprised to find out it isn't still used a lot.
and finally
4.) I think this is them being paranoid, however they are also trying to stay one step ahead of the game- that said, i don't think this is really any safer than just buying two cellphones, attaching one to the bomb and the other to call with from a secluded location, thus even though this is possible, and clever to boot, it wouldn't survive long as there are easier/traditional and most importantly, more effective ways of doing the same thing.]]>
Wondering since when a labor minister considered to be an anti-terrorist expert.
Yet returning missed calls from unknown numbers is actually a dumb idea anyway, besides those "terrorism" rubbish :)]]>
@ Troy
>.
A single ring won't do it, you could rig the trigger to go off on the second or third (or N for whatever value of N you want) ring.
After three or four incidences of having my phone ring at 3:45 in the morning, I'd cancel my service.
Of course, so would a great many cell phone users, I'd imagine. Now all legitimate users of cell phones have dropped the service due to annoyances, so all the remaining cell phone users must be terrorists. Maybe it's not such a bad idea after all :)]]>
@ Tank
> This non-problem has killed about 1000 people to date chump.
Which "non-problem"? The inability to prevent remotely triggered explosive devices from being deployed? Or the ability to use cell phones to trigger such a device?
The train of logic you're implying here is: bombs have killed 1,000 people. These bombs were triggered with cell phones. Ergo, eliminating cell phones as a possible trigger device would have prevented those 1,000 deaths.
That's absurd on the face of it.
> The reason you get to dismiss other people's security measures out of hand
> is that you aren't concerned by addressing the security problem.
Define the security problem, and the solution becomes self-evident. In this particular case, the security problem's definition (IMHO) is pretty well stated in my earlier post -> Posted by: Pat Cahalan at November 29, 2005 06:41 PM
The problem is that there is *no* solution. If you spend resources limiting cell phone use as triggers, the only result is that terrorists will migrate to a different trigger device. This doesn't impede terrorists at all, it just limits our ability to use cell phones, or it wastes colossal amounts of resources implementing curbs on *one possible* trigger mechanism. These wasted resources would be better spent on virtually *anything*.
> If the only input people like you and the author of this blog have is "ID cards won't help"
> you really are only pretending to be involved in evaluating security measures and are
> of absolutely no use to anybody.
As opposed to the implementers of the Thai phone registry, who wasted money implementing a program to limit one trigger device, a program which is easily circumventable?
You may or may not be correct that my input (at least) has no value. However, my "no-value" input doesn't waste resources, so it's certainly of greater value than those who design silly nationwide cell phone registries.]]>.
Then there's just the problem of someone gaining access to the procedure/algorithm for these "random" calls, and timing their attack between calls.
I'm curious how the police identify who placed the triggering call, though... is it possible to ensure the bomb renders the triggering cell/sim unidentifiable? Then there's just the time of call to go by, which is pretty circumstantial.]]>
@ Mike Sherwood
Quote "The worst part of all of these solutions to non-problems is that they blur the line between normal and stark raving lunacy."
This non-problem has killed about 1000 people to date chump.
The reason you get to dismiss other people's security measures out of hand is that you aren't concerned by addressing the security problem. If nothing at all was done by the Thai police this would be fine by you because you were not aware there was a problem in the first place and don't care if there is.
Just like how much I care if there are locks on the doors of you home. I don't.
The Thai police on the other hand do have a security problem to address and unlike you they are dealing with what they know about the attacks carried out to date.
If the only input people like you and the author of this blog have is "ID cards won't help" you really are only pretending to be involved in evaluating security measures and are of absolutely no use to anybody.]]>
tangent ->
I agree with Michael Ash's sentiment above... what this article is really telling us is not "here's another threat!", but "our so-called solution to a threat stinks!"]]>
Problem:
How to trigger an explosive device.
Solutions:
* Mechanical on device (e.g., clocks, tamper triggers, fuses, etc.) - advantages of simplicity, disadvantages of granular control.
* Electromagnetic (e.g. radios, cell phones, 802.11a/b/g, bluetooth devices, microwave, etc.) - advantages of granular control, disadvantages of complexity.
Problem:
How to prevent a terrorist from setting off an explosive device
Solutions:
* Halt all access to bomb making materials
* Halt all access to potential targets
* Halt all access to trigger devices
No implementable solutions.
New Problem:
How to impair the ability of a terrorist to set off an explosive device
Solutions:
* Limit access to all bomb making materials
* Limit access to all potential targets
* Limit access to all trigger devices
All solutions present the same difficulties, namely:
* Limiting access requires authentication/authorization processes that are resource intensive.
* Limiting access requires full coverage for each class of limitation (it does little good to severely limit one set of chemicals that can be used to create an explosive if other, unlimited chemicals, can produce a suitable replacement explosive).
* Without full coverage of the class, you are implementing authentication/authorization processes that are expensive and simultaneously of limited value.
Assuming, for example, that it would be technically feasible to remove "cell phones" from the list of possible trigger devices, people who want to trigger an explosive device will simply find another trigger. There are 7 examples at the beginning of this post that represent a fraction of the possible ways to trigger an explosive device.
It's a stupid threat because you don't know when the bomb will go off. It is extremely rare that just having the bomb go off is okay without any regard to timing. Obviously, to place the call from the cell phone, the bomber and bomb must be very close, and if someone where to ring the phone, they'd kill the bomber. As said before, a timer is easier, cheaper and safer for the bomber.
Second, cell phones are easily stolen, and most can be activiated without much identity info.
And why wouldn't the bomber just call the phone using either a stolen phone or a public pay phone?]]>
Hmm... there is another angle...
From the point of view of the anonymous callee, if I believed in this threat I think I'd try to be sure to be ready to call back as quickly as possible...]]>
Sounds just the slightest bit risky, not knowing whether the call will be returned before you've got clear, or maybe never...]]>
This is absurd. The point of using a cell phone as a trigger is to be able to detonate the bomb remotely and on demand as opposed to a pre-programmed time. (such as when you deem the crowd has reached the right size, there are many cars on the street, etc.)
If you are going to leave the timing to a total stranger, you might as well use an alarm clock and set the alarm randomly.
"The worst part of all of these solutions to non-problems is that they blur the line between normal and stark raving lunacy."
Amen.]]>
The worst part of all of these solutions to non-problems is that they blur the line between normal and stark raving lunacy. When people who are supposed to be in a position of authority are acting like this, the conspiracy theories start looking a lot more realistic.
The whole anti-terrorism frenzy reminds me of the movie "Brazil". We're spending a lot of time and money on creating larger government bureaocracies for everything. I wonder how long it will be before we start having things blow up - not from terrorists, but from disrepair and ignoring the most obvious maintenance due to everyone being sent off on fear driven tangents.
Every actual event generates a thousand ideas of what might happen that need to be defended against. If generating fear is the goal, the current system has a very good return on investment. Unfortunately, that's our opponents' goal.]]>
Why is this a movie-plot threat? The idea that you should not call back when you get a call from an unknown number is stupid, of course, but in general, I'd view this more as an interesting way to "work the system" - a reason why increased surveillance and data accumulation will not actually make us safer (but rather lead to terrorists etc. coming up with new tricks again).]]>
Stupid. Let's say I'm a terrorist. I build a bomb and hook it up to a cell phone. I grab my personal cell phone and call my friend who could be anywhere. I tell him to find a payphone and call back the bomb number. But this has made me think. What if the cell phone companies agree to randomly call every cell phone at the same time? Just one ring then hang up. I'm sure the cell phone company could spoof any random number they want. Once the bomb triggering device becomes unreliable then it won't be used anymore.]]>
So let em get this straight. I am a terrorist who has risked life and limb to build a bomb, and has plotted for months to do so. I have selected a location to bomb, designed to get a maximum kill rate, thus earning high credibility for my cell. I have designed a sophisiticated trigger system based on the decision of a random person to return (or not) my random call at a time completely out of my control. Assuming the police don't find the package first, what guarantee do I have the return call won't come in at 4:00 a.m., effectively killing a hotel lobby and a stray dog? I would be the laughing stock of the terrorist world.
Those who point out that this is feasible are missing the point entirely. The real question is, "Would this advance the goals of the terrorists?". If it doesn't advance their cause, they are not likely to spend their time doing it.]]>
Yes, bombs can be triggered via cell phones, but I can't see any other way to combat against it than turning the whole network down (or alternatively have the general public on a separate cluster and shut that down instead).
However, in an emergency, it can be argued that the good guys will benefit more if the network is up rather than down.
If someone's going to use cell phones as bomb triggers it would seem stupid to me not to rig it with secondary means of triggering it just in case the primary means go down (a timer perhaps? how about a motion detector to make it go off if anyone approaches it? or monitoring certain freqs for whatever RF?).
The possibilities are endless and it's impossible trying to defend against everything imaginable.
Let me get this straight. The "terrorist" calls, I answer, they hang up. Why would I call back? I'd assume it was a wrong number and go on with life.
Really, if they wanted to exploit this as a trigger mechanism, they would hardly need the involvement of random individuals. Simply go buy 2 pre-paid phones, strap one to the device and call it from the other. Or steal 2 phones.
Although it could prove interesting under this "plan" if instead of Joe Random the calls that triggered the bombs came from political aids. It shouldn't be too hard to find the cel numbers of some low-level government officials.]]>
@Tim
Well put. Just want to say I second your opinion.]]>
Bombs in Thailand were detonated using cellphone and it's likly those terrorists will get more sophisticated.]]>
No movie plot, but a book plot:]]>
Terrorists already have a very good, cheap, reliable way to trigger a bomb. They call it man.]]>
I agree with Bruce. This is ridiculous. There are already so many other ways of calling a mobile phone untraceably that are considerably more reliable (buy a pay-as-you go phone, or one on a stolen credit card, call the phone from a phone box) and can still finger someone else for the crime (steal someone's cellphone).
It's like Bruce is always saying: you've got to consider the cost vs benefit. In this case they're suggesting that the whole country not return unanswered calls on the minute chance that some villan might be dumb enough to use this technique rather than the other, superior ones open to him.
It's just not worth it. This is the thing: most of these movie-plot scenarios *could* possibly work, but that doesn't mean that we should act on them, as anybody with half a brain could come up with *hundreds* of them. We can't act on them all, we should only act on those whose cost/benefit ratio seems worth it.]]>
after cellphones and timers are outlawed, the next frontier will be retro alarm clocks. when the alarm goes off, the little "wind alarm" key on the back of the clock turns around. just tie a string from this key to your bomb trigger. when alarm clocks are outlawed, only outlaws will get to work on time.]]>
."
I think the odds your callback triggering a bomb, and therefor your odds of being interrogated, are so close to zero as not to make any difference, so that's not really a consideration.
However, I do think that this "security measure" will have exactly zero effect on terrorism in Thailand. It's a movie-plot threat because it tries to predict the minor details of a terrorist plot, rather than focus on the broad threat of terrorism.]]>
This seems like a non-issue to me. The reason? The terrorists have no reason what so ever to use this method.
If the intention is to simply blow up the bomb they might as well use a timer that can’t be traced and is less likely malfunction. There is little need to use a phone to call.
If the intention is to time and coordinate this system doesn’t work, as they have no way to be sure when/where/if the bombs are actually detonated.
If the intention is to confuse the authorities about the source of the attack there are far more effective methods.
In the end, there is probably another reason for this “security measure��?.
However, what I first thought was that the terrorists were going to use the lack of a call to mobile phone to trigger a bomb. This gives more interesting effects, such as planting a bomb somewhere well hidden and having it detonate after the terrorist is arrested.
Definately plausible. All you have to do is clone a SIM card.]]>
This is classic.
The government institutes a huge, draconian registration program, which inconveniences a great many people and badly hurts anonymity, in the name of fighting terrorism.
Two weeks later, the government says, "remember that registration thing, and how it was supposed to cut back on terrorism? Well, there's a really easy way to get around it. Please try not to cooperate with this really easy way."
Why bother with effective security measures when highly-visible ones are so easy?]]>
I agree with Moshe, I don't see why this is implausible. Bombers in Iraq already use various types of cell-phone triggers. This just seems like another variant on that. I don't know if it's possible to block cell calls from everybody but a whitelist of trusted sources but this might circumvent that nicely, especially combined with the easily forged caller-id system. Also if you do it enough, you weaken the trust the police (and juries) have in tracking cell triggered bombs.]]>
And so the next thought process to make its way into the vacuous skulls of lawmakers:
"omg! omg! Timers aren't traceable like cellphones! AHH! We must outlaw timers!!"]]>
@Phillip:
At that rate you might as well just use your timer as the trigger. Keep it simple.
What I want to know is why someone would BOTHER to use a cell phone to trigger a bomb. What's the point? If you can't trust your suiciders to blow themselves up, what makes you think they're going to:
A: carry the bomb
B: go to the right place
If you want to drop a bomb to explode later, why not use a timer? Cheaper, simpler, just as likely to get caught, and you don't risk leaving a paper trail.]]>
Sorry, I don't understand why this is a movie-plot threat. The government is tracking cell phone calls in an effort to catch the people who trigger bombs using cell phones -- we agree that bombs do go off this way, correct?.
Reminder to non-telephony folks: caller ID's can be forged.
I won't argue about whether the measure will be effective or not. Can it be circumvented? Are the Thai police stripping anonymity from cell phone purchases? And a hundred other question. But the bottom line is that calls trigger bombs, and they're trying to prevent explosions.]]>
@Clive and Joseph
I agree the "threat" is rediculous. But as a counter-measure to being blown up by an early call back a terrorist could install an "arming delay" on the device so it won't be armed until X minutes. Thus if the call came in prematurely, it wouldn't trigger until X minutes were up.
Or...he could just call his innocent person AFTER the phone is in place and AFTER he is clear of the device. All he'd have to do is spoof the caller ID. From what I've read....it's not that hard.]]>
As a "Terorist who had intentions to survive the explosion" I would not like to do this.
The random person I called might call back just as I finish wiring my phone in and befor/as I have the chance to place it.
A person who has no intention of surviving the blast would not bother with this...
So it's a bit of a silly idea one way or another.]]>
This just in: Authorities warn the public that buying soda may trigger a bomb.
It may have been possible for a bomb to be wired to the following systems, so the public is warned never to use them:
Soda machines, Red Box movie rental systems, parking meters, pay phones, and doorbells.
Did anyone ever think "Maybe the random phone guy will call back before I am far enough away from the bomb?" I would be sure to call someone on vacation that isn't going to return the call for a while.]]>
|
https://www.schneier.com/blog/archives/2005/11/missed_cellpohn.xml
|
CC-MAIN-2017-17
|
refinedweb
| 4,516
| 70.23
|
I am having a hard time getting this program (my homework assignment) to compile. I have looked it over a million times. The program is supose to read an inventory of an art gallery from "art.dat" into a struct (the Type and Place have to be enum types), and then a user has to be able to type in an artist name and get an output of all of the pieces of work that are listed for that artist.
I NEED HELP PLEASE!!! WHAT AM I DOING WRONG!!!
#include<iostream> #include<fstream> #include<cctype> using namespace std; enum Type {OIL, WATERCOLOR, PASTEL, ACRYLIC, PRINT, COLORPHOTO, BWPHOTO}; enum Place {MAIN, GREEN, BLUE, NORTH, SOUTH, ENTRY, BALCONY}; struct Size { int Height; int Width; }; struct ArtWork { string Artist; string Title; Type Medium; Size WorkSize; Place Room; float Price; }; const int MAX_ARTWORK = 120; void search(ArtWork&); int main() { char YN; bool test; ArtWork collection[MAX_ARTWORK]; ifstream inFile; inFile.open("art.dat"); for(int i=0; i < MAX_ARTWORK; i++) { inFile.get(collection[i].Artist); inFile.get(collection[i].Title); inFile.get(collection[i].Medium); inFile.get(collection[i].WorkSize); inFile.get(collection[i].Room); inFile.get(collection[i].Price); } test = true; do { search(collection[]); cout << "Would you like to look up another artist? (y/n)" << endl; cin >> YN; if (tolower(YN) == 'n') { inFile.close(); return 0; } } while (test == true); } void search(ArtWork&collection[]) { string artist, medium, room; int i; cout << "Enter artist name: " << endl; cin >> artist; cout << "Artwork found by that Artist:" << endl; for(i=0; i < MAX_ARTWORK; i++) { int count = 0; if (collection[i].Artist == artist) { cout << "Title: " << collection[i].Title << endl; switch (collection[i].Medium) { case OIL : medium = "Oil"; break; case WATERCOLOR: medium = "Watercolor"; break; case PASTEL: medium = "Pastel"; break; case ACRYLIC: medium = "Acrylic"; break; case PRINT: medium = "Print"; break; case COLORPHOTO: medium = "Color Photo"; break; case BWPHOTO: medium = "Black & White Photo"; } cout << "Medium: " << medium << endl; cout << "Work Size: " << collection[i].WorkSize.Height << "X" << collection[i].WorkSize.Width << endl; switch (collection[i].Room) { case MAIN: room = "Main"; break; case GREEN: room = "Green"; break; case BLUE: room = "Blue"; break; case NORTH: room = "North"; break; case SOUTH: room = "South"; break; case ENTRY: room = "Entry"; break; case BALCONY: room = "Balcony"; } cout << "Room: " << room << endl; cout << "Price: " << collection[i].Price << endl; count= count++; } } if (count == 0) cout << "There was no artwork found by that artist." << endl; return; }
|
https://www.daniweb.com/programming/software-development/threads/99632/i-need-help-with-homework
|
CC-MAIN-2017-13
|
refinedweb
| 391
| 61.26
|
Contents
Abstract
This PEP describes a simple protocol for requesting a frozen, immutable copy of a mutable object. It also defines a new built-in function which uses this protocol to provide an immutable copy on any cooperating object.
Rejection Notice
This PEP was rejected. For a rationale, see this thread on python-dev [1].
Rationale
Built-in objects such dictionaries and sets accept only immutable objects as keys. This means that mutable objects like lists cannot be used as keys to a dictionary. However, a Python programmer can convert a list to a tuple; the two objects are similar, but the latter is immutable, and can be used as a dictionary key.
It is conceivable that third party objects also have similar mutable and immutable counterparts, and it would be useful to have a standard protocol for conversion of such objects.
sets.Set objects expose a "protocol for automatic conversion to immutable" so that you can create sets.Sets of sets.Sets. PEP 218 deliberately dropped this feature from built-in sets. This PEP advances that the feature is still useful and proposes a standard mechanism for its support.
Proposal
It is proposed that a new built-in function called freeze() is added.
If freeze() is passed an immutable object, as determined by hash() on that object not raising a TypeError, then the object is returned directly.
If freeze() is passed a mutable object (i.e. hash() of that object raises a TypeError), then freeze() will call that object's __freeze__() method to get an immutable copy. If the object does not have a __freeze__() method, then a TypeError is raised.
Sample implementations
Here is a Python implementation of the freeze() built-in:
def freeze(obj): try: hash(obj) return obj except TypeError: freezer = getattr(obj, '__freeze__', None) if freezer: return freezer() raise TypeError('object is not freezable')``
Here are some code samples which show the intended semantics:
class xset(set): def __freeze__(self): return frozenset(self) class xlist(list): def __freeze__(self): return tuple(self) class imdict(dict): def __hash__(self): return id(self) def _immutable(self, *args, **kws): raise TypeError('object is immutable') __setitem__ = _immutable __delitem__ = _immutable clear = _immutable update = _immutable setdefault = _immutable pop = _immutable popitem = _immutable class xdict(dict): def __freeze__(self): return imdict(self) >>> s = set([1, 2, 3]) >>> {s: 4} Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: set objects are unhashable >>> t = freeze(s) Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/tmp/python-lWCjBK.py", line 9, in freeze TypeError: object is not freezable >>> t = xset(s) >>> u = freeze(t) >>> {u: 4} {frozenset([1, 2, 3]): 4} >>>>> freeze(x) is x True >>> d = xdict(a=7, b=8, c=9) >>> hash(d) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: dict objects are unhashable >>> hash(freeze(d)) -1210776116 >>> {d: 4} Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: dict objects are unhashable >>> {freeze(d): 4} {{'a': 7, 'c': 9, 'b': 8}: 4}
Reference implementation
Patch 1335812 [2] provides the C implementation of this feature. It adds the freeze() built-in, along with implementations of the __freeze__() method for lists and sets. Dictionaries are not easily freezable in current Python, so an implementation of dict.__freeze__() is not provided yet.
Open issues
- Should we define a similar protocol for thawing frozen objects?
- Should dicts and sets automatically freeze their mutable keys?
- Should we support "temporary freezing" (perhaps with a method called __congeal__()) a la __as_temporarily_immutable__() in sets.Set?
- For backward compatibility with sets.Set, should we support __as_immutable__()? Or should __freeze__() just be renamed to __as_immutable__()?
|
https://legacy.python.org/dev/peps/pep-0351/
|
CC-MAIN-2019-04
|
refinedweb
| 606
| 61.77
|
Last weekend, I spent a good 30 minutes trying to figure out why I wasn't hitting a breakpoint in a method. Admittedly, I wasn't very familiar with the code since I hadn't written it. It turned out that the method wasn't being called from anywhere, so it was essentially "dead code". I wanted to remove the method in order to clean up the code but I wasn't 100% sure whether I would break anything. The only option was to use trial and error which meant that I commented out the method, rebuilt the code and ran through the scenario to verify that that the method was not being used. However, I still had a nagging feeling that maybe the code was being called through some other mechanism.
Well, it turns out that you can use Code Analysis to take out much of the guess work with it comes to dealing with dead code. But first, a definition is in order.
There are several definitions of dead code including i) redundant code ii) unreachable code and iii) unused code. Code Analysis in Visual Studio Team System can tell you about the following types of dead code:
In the sections below, I'm going to explain each of these types of dead code using real world examples.
This type of dead code is pretty easy to understand. If you have a private method that is not called from anywhere inside your class, Code Analysis will warn you about it, as shown here:
warning : CA1811 : Microsoft.Performance : 'SearchData.NotifyPropertyChanged(string)' appears to have no upstream public or protected callers.
In order to fix this issue, you can either add code to call the method or remove the method entirely. In the following example from the Patient Monitoring WPF sample application, the NotifyPropertyChanged private method is not called from any other code.
1: private void NotifyPropertyChanged(string propName)
2: {
3: if (PropertyChanged != null)
4: {
5: PropertyChanged(this, new PropertyChangedEventArgs(propName));
6: }
7: }
Typically, if you declare a local variable but don't assign anything to it, the compiler will warn you about it. However, if you do assign a value to the local variable, the compiler no longer complains even if you never use the variable. Take a look at the following example from the WPF Patient Monitoring sample application which declares and initializes the local variable dob but never uses it. This could be a real bug that should be investigated further.
1: public SeriesDataItem(SeriesDataItems itemParent, double itemValue)
3: _itemParent = itemParent;
4: DependencyObject dob = new DependencyObject();
5: this.SetValue(SeriesDataItem.ValueProperty, itemValue);
6: }
Code Analysis will warn you about this type of dead code:
warning : CA1804 : Microsoft.Performance : 'SeriesDataItem.SeriesDataItem(SeriesDataItems, double)' declares a variable, 'dob', of type 'DependencyObject', which is never used or is only assigned to. Use this variable or remove it.
In the example below, the field _filename is declared and initialized but it's not used anywhere in the assembly. Code Analysis will warn the developer with the following warning and also provides a suggestion as how to resolve the issue.
warning : CA1823 : Microsoft.Performance : It appears that field 'PatientVitals._filename' is never used or is only ever assigned to. Use this field or remove it.
This type of warning could be a bug in the code that should be investigated further.
1: public class PatientVitals
2: {
3: private readonly char[] COMMA_SEPARATOR = new char[] { ',' };
4: private Dictionary<string, Waveform> _waveforms = new Dictionary<string, Waveform>();
5: private string _filename;
6:
7: public PatientVitals(string filename)
8: {
9: this._filename = filename;
10: this.ReadWaveformData(filename);
11: }
12:
13: // rest of class not shown
This type of dead code might actually be a symptom of a real bug in the code. In the following example, the parameter nextValue is not used anywhere inside the method.
1: private void ScrollPoints(double nextValue)
3: DrawSeries();
4:
5: if (_chartPoints.Count == _chartPoints.Capacity)
6: {
7: _chartClock.Controller.SkipToFill();
8: _chartClock.Controller.Begin();
9: }
10: }
It's always worrisome when a parameter is passed to a method but never used. If you have this type dead code, code analysis will warn you about it. It should definitely be investigated further.
warning : CA1801 : Microsoft.Usage : Parameter 'nextValue' of 'Chart.ScrollPoints(double)' is never used. Remove the parameter or use it in the method body.
This type of dead code is much less common than the other types mentioned above. If you declare an inner class but do not instantiate it, Code Analysis will warn you with the following message:
warning : CA1812 : Microsoft.Performance : 'Order.OrderItem' is an internal class that is apparently never instantiated. If so, remove the code from the assembly. If this class is intended to contain only static methods, consider adding a private constructor to prevent the compiler from generating a default constructor.
In the following example, the inner class OrderItem is never instantiated from the Order class.
1: public class Order
3: private List<OrderItem> orderItems = new List<OrderItem>();
5: public Order()
7: }
8:
9: private class OrderItem
10: {
11: }
12: }
Habib Heydarian.
|
http://blogs.msdn.com/b/habibh/archive/2009/07/31/discover-dead-code-in-your-application-using-code-analysis.aspx
|
CC-MAIN-2014-52
|
refinedweb
| 846
| 55.84
|
I've been working on a Timer Android app. And at the end of every round it rings a bell .mp3. The app works smoothly with no issues it does the count down and all. But the media player randomly stops playing the bell ( _player) after certain rounds of repeat. Please help me.
Following is the snippet of parts where the media player is implemented. Again, this is not full code but just the media player implementations in the code.
public class MainTimerActivity : AppCompatActivity { private static MediaPlayer _10fx, _8fx, _7fx,_6fx,_5fx, _4fx, _3fx, _2fx, _1fx, _player, _player2; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.Main_Timer); this.Window.SetFlags(WindowManagerFlags.KeepScreenOn, WindowManagerFlags.KeepScreenOn); } void TimeBoyMain() { TIMERFLAG = true; if (bbellstring == "true") { _player = MediaPlayer.Create(this, Resource.Raw.startding); _player.Start(); } } }
Thank you!
Answers
Hi,
Have you found any solution? I've got the same problem.. I'm playing an mp3 sample song coming from Deezer. And it stop randomply (after around 10 or 15 samples played)
Do you have any solution?
|
https://forums.xamarin.com/discussion/83136/the-mediaplayer-stops-playing-randomly-please-help
|
CC-MAIN-2018-05
|
refinedweb
| 175
| 51.85
|
They like me, they really, really like me... ok, well, maybe not so much, but the good folks at Microsoft, specifically Beth Massi, Program Manager, VS Core Community, must like me because she posted an article I submitted to her on the Visual Basic Developer Center Community Page.
In it I cover all the in's and out's of using the System.Net.Mail namespace to send email from within your .NET Application. Topics such as sending attachments, CC, BCC, specifying the reply-to address, setting message priority, requesting a return receipt, using delivery notification, sending email asynchronously, and so on. You can check out the article here.
Have a day. :-|
You...
Oh this is just to funny to keep to myself!! I can't believe I hadn't seen this before. Let me fill you in... Rod Paddock, Editor of CoDe Magazine, my business partner, my good friend, and best damn coder I know has REALLY changed since the last time I saw him. Here I thought I knew what there is is to know about him but obviously Justice Gray sees him a whole lot differently than I do!! Check this out!
Have a day. :-|
With a title like that you might thing I'm going to go into a touching story about a friend with Multiple sclerosis or maybe a story about Microsoft in an OS war with Linux or something but NO! This is a story of a more ludicrous nature. I'm talking about the DevTeach 2007 - West Coast: Battle of the Metros. Oh this is just too funny. Seems that fellow GeeksWithBlogs blogger D'Arcy Lussier has come up with the ultimate battle for DevTeach 2007 in Vancouver. So, who's your choice to take home the crown, Shaun Walker or Justice Gray?????
I just finished wrapping up an article on how to send email from within a Windows or Web application with the System.Net.Mail namespace. One of the things I uncovered is that you can send email through the gmail smtp server. Of course you need to have a GMail account first...
Imports System.Net.Mail
'Start by creating a mail message object
Dim MyMailMessage As New MailMessage()
'From requires an instance of the MailAddress type
MyMailMessage.From = New MailAddress("from_address_here@gmail.com")
'To is a collection of MailAddress types
MyMailMessage.To.Add("to_address_here@domain_name_here")
MyMailMessage.Subject = "GMail Test"
MyMailMessage.Body = "This is the test text for Gmail email"
'Create the SMTPClient object and specify the SMTP GMail server
Dim SMTPServer As New SmtpClient("smtp.gmail.com")
SMTPServer.Port = 587
SMTPServer.Credentials = New System.Net.NetworkCredential("account uid", " account pwd")
SMTPServer.EnableSsl = True
Try
SMTPServer.Send(MyMailMessage)
MessageBox.Show("Email Sent")
Catch ex As SmtpException
MessageBox.Show(ex.Message)
End Try
Just thought I'd pass that little tidbit on.
.
Big news....
Visual Studio 2008 ("Orcas"), Windows Server 2008 ("Longhorn"), and SQL Server 2008 ("Katmai") will all be shipping on February 27, 2008 according to Kevin Turner, Microsoft COO at the Worldwide Partner Conference 2007.
I!
We wouldn't all be card-carrying members of the technology business (geeks, nerds, dweebs, etc.) if we didn't do a [enter your favorite search engine here] search on our name to see what comes up. I can tell you that there are quite a few Jim Duffy's out there in the world. I remember years ago, maybe in the 80's, there was a commercial (maybe a public service announcement?) on ABC television here in the U.S. that opened with a man on the screen saying "Hi, I'm Jim Duffy, President of ABC television" and I thought "wow, I'm a bigshot TV executive!".
Well, I've taken than a little farther by utilizing Google Alerts to keep track of when my name or my company's name, TakeNote Technologies is mentioned in blog posts, etc. An interesting alert arrived in my inbox this morning. It seems that I'm quite an expert in nutrition. :-)
For your own good, I'd suggest that some of you, ummmmm, how do I put this, "less active" card-carrying members take a closer look at some of those articles. I know I'm going to.
I know you've done it so let me hear what you've found when you've searched for your name. Anything interesting???
Yes, I am a very proud uncle. My niece Emily plays the violin and is attending the prestigious Eastern Music Festival music school in Greensboro, NC this summer. I was incredibly fortunate to be able to catch one of her orchestra concerts Friday night, July 6th. WOW!! These 14-21 yr old kids are fantastic! After two weeks of study/training, they sounded incredible. My niece, a high skrewl senior this fall, played 10th chair violin Friday night. I couldn't be more proud of her.
Check out the rest of the dates on the calendar for the Eastern Music Festival. If you're anywhere near Greensboro, NC and can catch a concert, you won't be disappointed.
I'm proud to announce, well, I'm proud to announce on behalf of my company, TakeNote Technologies, that Chris Love has been added to our list of instructors. You may know Chris from his blog or all the great work he's done with the Triangle .NET User Group (TRINUG).
Chris is going to be teaching TakeNote's upcoming August .NET classes including
VBN101: Programming With Visual Basic 2005 (August 13 & 14)
VBN301: Developing ASP.NET 2.0 Web Apps With Visual Basic 2005 (August 15 - 17)
Head over to our online registration page if you or someone from your organization is interested in attending.
Welcome aboard Chris!
Just in case you're new to the blog reading world, here's a link to a list of Tech Blogs That Don't Suck.
You're welcome.
The first segment was dominated by iPhone content. My co-host Spencer went down to the Apple store in Durham (yes, the same Durham from the movie Bull Durham with Kevin Costner and Susan Sarandon) and got his hands on one for the first time. He didn't actually buy one, just tried it out. He was impressed and is waiting for that form factor to be applied to the next gen on iPod. A number of companies and individuals are already hard at work trying to figure out how to unlock the phone. Our first call was even iPhone related... geeez, enough of the iPhone already!
We had a number of interesting calls including one from a guy who wanted our help in speeding up his machine. We figured it was a virus or spyware of some type but before calling us he decided to take matters into his own hands and try to remedy the situation. He said he went looking through the Add/Remove Programs dialog and started removing programs he didn't recognize or remember installing. He said one program that he didn't recognize was the Microsoft .NET Framework 1.1 so away it went. He said he also saw the Microsoft .NET 2.0 Framework but hadn't removed that yet. I advised he NOT uninstall that one. :-)
We also had a call from a guy who's laptop display will only work when he presses just above the F5 key on boot up. Yikes! Sounds like a connector problem to me!
Anyway, feel free to check out the show yourself and download it from here.
Well Beth Massi has been quite the busy little Microsoftie since joining the evil empire. :-) She has put together an ongoing series of "How Do I" videos for helping people learn and work with Visual Basic. SUUUUUH-WEEEEET! GREAT JOB BETH!
Have a day.
Wow.... what an excellent blog post. I found the link to this incredibly informative post from Scott Guthrie today on fellow GeeksWithBlogs blogger D'Arcy Lussier's blog today and knew I had to make sure I let readers of my blog know about this post. This post in an excellent resource and repository of information on ASP.NET 2.0 security, membership features, links, and so on.
Why is it that every electronic device needs to have it's own specific power cord? Ok, I'll even be more specific. Why is it that every laptop computer I own has a different power cord?? Shouldn't there be a standard or something that says "All laptop power cords look and work like this." You can expand this to cell phones as well. Every cell phone I've ever owned has a completely different power cord and connector than any of the others, even those from the same manufacturer!
The advent of wireless battery recharging show promise but still, it sure would be nice if power cords for the same type of device (laptops, cell phones, PDAs, cable modems, routers, cameras, MP3 players, etc.) were all standardized based on the type of device. That way when you buy a new toy you could have the option of buying a power cord to go with it. Have you even noticed the power cord for your desktop computer? They're interchangeable. Yes, desktop power cords all look the same. Yeah, I know it has to do with all the inverters, transformers, and other electro-mumbo jumbo stuff being housed in the desktop computer power supply and all but couldn't they do the same with the other devices or figure out a way to standardize the power cords and connectors??? I mean come on!!.
It's been a month or so now since I decided to get my Motorola Q phone and I must say I'm loving this phone. I like the keyboard layout, reception, and ability to download and select themes. Being from South Florida, though not a UM alum, I'm sporting the theme below on my phone these days.
I found this theme here and you'll find plenty of others here and here too!
I just got an email from Al, one of our listeners from this morning's Computers 2K7 radio show, and he found another resource dealing with this issue.
Thanks Al!
Not much else to say about this other than wow... that is not good! On a number of occasions we've told callers to the Computers 2K7 radio show to open up and dust out their computers but man, this is awful!
For those of you who don't know, for years now I've been one of the in-studio co-hosts for Computers 2K7, a call-in radio show on Sunday mornings from 8am - 10am on 850 The Buzz in Raleigh, NC. We had some good calls and talked about a number of topics this morning. Each week the show is available for download on the Computers 2K7 page.
Problem with XP Auto Login and the .NET Framework
We had a caller who was experiencing a problem with the auto login feature of XP and the .NET Framework. From Start -> Run enter Control Userpasswords2 to bring up this dialog. The check box near the top of the dialog specifies is you want to auto login or not.
She said she couldn't get the auto login feature working because the .NET Framework was installed on her machine. She uninstalled it and XP's auto login worked fine. She needed the .NET Framework for software on her machine so she reinstalled it. I said I hadn't heard of that problem before but I did some research and it does indeed exist. I found a Microsoft Support article on the subject and it appears to be an issue related to the .NET Framework 1.1. The fix appears to be installing the Microsoft .NET Framework 1.1 Service Pack 1. That should be an available option through Windows Update.
Here are links to a few of the stories I reported about.
Headless zombie wanders San Francisco! It's incredible what you can find on Google Street View! Be careful next time you're wondering around San Francisco!
Google Maps has introduced their new drag and drop driving directions feature... very cool stuff indeed! You enter your beginning and ending destinations and Google Maps provides driving directions. Nothing new there. The new feature is that you can drag and drop points along the route to reconfigure your route and a floating ticker automatically updates the distance and duration of the trip.
Jack PC: The Wall Socket PC Yeah, I know it only runs WinCE but the idea is pretty cool. A machine you plug into an outlet, use some wireless peripherals, and viola! you same precious desk and/or floor space. One flash hard drives become the norm something like this starts to look very viable.
As is usually the case, the topic of anti-virus software came up. We recommend our listeners download and install the free version of AVG Anti-virus.
As he mentioned during the show, Amnon burned a couple of his fingers on a generator this week!
OUCH!!!
"That's it for today's show... don't forget to backup your hard drive and update your anti-virus scanner. We'll see you again next Sunday at 8 on 850 The Buzz"
|
http://geekswithblogs.net/TakeNote/archive/2007/07.aspx
|
CC-MAIN-2014-15
|
refinedweb
| 2,220
| 74.19
|
On Feb 23, 2005, at 4:51 PM, David Jencks wrote:
> I think this is what I mean by a security builder. However, I haven't
> figured out a very extensible way to choose the builder based on
> namespace while having the entire document validated. There's
> probably some way to do it elegantly, but I haven't found it yet.
I'm not sure it is that hard. At the bottom of the xsd we simply put
something like this
<xs:element
From what I understand (and my xml parser knowledge is pretty weak),
the xml parser will allow any xml element, but the element will itself
have to be internally valid. For this scenario, that is all we need.
We just want to support extra optional data. Will that work, or does
it result in some inelegant or unworkable code?
-dain
|
http://mail-archives.apache.org/mod_mbox/geronimo-dev/200502.mbox/%3Cace226ec223f95e244f6712c4deec31f@gluecode.com%3E
|
CC-MAIN-2017-26
|
refinedweb
| 143
| 71.04
|
We==?
We==?
This only works for powers of two (and frequently only positive ones) because they have the unique property of having only one bit set to '1' in their binary representation. Because no other class of numbers shares this property, you can't create bitwise-and expressions for most modulus expressions.
First of all, it's actually not accurate to say that
x % 2 == x & 1
Simple counterexample:
x = -1. In many languages, including Java,
-1 % 2 == -1. That is,
% is not necessarily the traditional mathematical definition of modulo. Java calls it the "remainder operator", for example.
With regards to bitwise optimization, only modulo powers of two can "easily" be done in bitwise arithmetics. Generally speaking, only modulo powers of base b can "easily" be done with base b representation of numbers.
In base 10, for example, for non-negative
N,
N mod 10^k is just taking the least significant
k digits.
Not using the bitwise-and (
&) operator in binary, there is not. Sketch of proof:
Suppose there were a value k such that
x & k == x % (k + 1), but k != 2^n - 1. Then if x == k, the expression
x & k seems to "operate correctly" and the result is k. Now, consider x == k-i: if there were any "0" bits in k, there is some i greater than 0 which k-i may only be expressed with 1-bits in those positions. (E.g., 1011 (11) must become 0111 (7) when 100 (4) has been subtracted from it, in this case the 000 bit becomes 100 when i=4.) If a bit from the expression of k must change from zero to one to represent k-i, then it cannot correctly calculate x % (k+1), which in this case should be k-i, but there is no way for bitwise boolean and to produce that value given the mask.
Using bitwise_and, bitwise_or, and bitwise_not you can modify any bit configurations to another bit configurations (i.e. these set of operators are "functionally complete"). However, for operations like modulus, the general formula would be necessarily be quite complicated, I wouldn't even bother trying to recreate it.
There are moduli other than powers of 2 for which efficient algorithms exist.
For example, if x is 32 bits unsigned int then x % 3 = popcnt (x & 0x55555555) - popcnt (x & 0xaaaaaaaa)
In this specific case (mod 7), we still can replace %7 with bitwise operators:
// Return X%7 for X >= 0. int mod7(int x) { while (x > 7) x = (x&7) + (x>>3); return (x == 7)?0:x; }
It works because 8%7 = 1. Obviously, this code is probably less efficient than a simple x%7, and certainly less readable.
|
http://ansaurus.com/question/3072665-bitwise-and-in-place-of-modulus-operator
|
CC-MAIN-2017-47
|
refinedweb
| 450
| 61.16
|
Subject: Re: [boost] [Boost-announce] [metaparse] Review period starts May 25th and ends June 7th
From: Michael Caisse (mcaisse-lists_at_[hidden])
Date: 2015-06-02 16:37:10
On 06/02/2015 11:58 AM, Niall Douglas wrote:
> On 2 Jun 2015 at 21:28, Peter Dimov wrote:
>
>
> The precedent for handling this is very well understood.
Can you please cite specific examples of this "precedent"?
>
> If during the early part of review it becomes obvious Rejection votes
> are occurring due to presentation problems, the precedent is to
> withdraw the library from review, make the fixes, and start the
I don't recall this happening. Despite what some people might want to
think, the review process is not an equatable voting process. It is a
process in which a competent review manager solicits community feedback
and then makes an educated decision. The review manager's job is not to
tally votes.
> review again with the fixed edition. I certainly don't like libraries
> changing during review, and I also don't like two editions of a
Abel has not submitted a second version for review by the community. He
was gracious enough to show what the other version might look like at
your prodding. The more amazing thing to me is that the original version
is the older Boost directory structure and some reviewers are confused
by that.
>
> I think peer reviews are very like academic paper peer reviews: it's
Boost reviews have nothing to do with academic paper reviews.
>
>.
I've only been active in the Boost community for 10-years, but let me
help correct some of your assertions. It is not uncommon for libraries
to need a restructure of directories and namespaces *after* approval.
The goal is that authors present a very high quality library without
having to completely boostify it before finding out if it will be
accepted. Directory structures and namespaces are not a requirement of a
review. CI testing is also not a requirement for a review to be
successful. You are free to voice your opinion and to write documents
that promote it; however, you cannot force your requirements onto the
process.
michael
-- Michael Caisse ciere consulting ciere.com
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
|
https://lists.boost.org/Archives/boost/2015/06/223044.php
|
CC-MAIN-2021-17
|
refinedweb
| 389
| 63.19
|
By Gary simon - Nov 04, 2016
When you develop Angular apps, you'll find that you may want to alter the appearance of certain HTML elements based on certain conditions that occur. The way you handle these situations is through class binding and style binding.
But first, if you prefer to watch a video tutorial on this subject:
There are 2 methods of class and style binding. One method is based on changing a single class or style, while the other is based on changing multiple classes or styles.
First, we'll tackle the easier of the two, which is changing a single property.
Changing a single class is fairly straight forward. We first have to attach the class prefix along with the associated class name, to the HTML element(s) that we want to affect:
import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <button class="my-btn" [class.extraclass]="someProperty">Call to Action</button> `, styles: [` .my-btn { font-size:1.7em; } .extraclass { background: black; color: white; } `] }) export class AppComponent { someProperty = true; }
As shown above, we add class and then a . followed by the class name, to a given HTML element. Then
Then we define the class name in the styles property of the Component metadata.
And finally, we define the property of "someProperty" (you can name this whatever you like) in the component class. Typically, this property would be defined or not defined based on logic in your app.
Changing a single style is very similar to the process of changing a single class. In fact, the only line that has to change is the HTML defining the button in the template property of the component metadata.
//.. other code <button class="my-btn" [style.border]="someProperty ? '5px solid yellow' : 'none'">Call to Action 2</button> //.. other code
If you want to append or remove multiple classes through class binding, you have to use a different approach. You must use the NgClass directive. Here's how you use it:
//.. component metadata <button class="my-btn" [ngClass]="setClasses()">Call to Action</button> , styles: [` .my-btn { font-size:1.7em; } .extraclass { background: black; color: white; } .anotherclass { font-weight:bold; } `] }) export class AppComponent { someProperty = true; anotherProperty = true; setClasses() { let classes = { extraclass: this.someProperty, anotherclass: this.anotherProperty, }; return classes; } }
We attach the [ngClass] directive to the HTML element. Then we specify a method such as "setClasses()".
We then must define this method in our app component. "extraclass" will be added to the classes attribute of the HTML element if this.someProperty is defined, and the same applies to the anotherclass CSS class.
Note: You can also use !this.someProperty
Once again, the process for changing multiple styles is very similar to changing multiple classes. Below I will note the key differences:
//.. component code <button class="my-btn" [ngStyle]="setStyles()">Call to Action</button> //.. component code //.. class code setStyles() { let styles = { // CSS property names 'font-style': this.someProperty ? 'italic' : 'normal', // italic 'font-weight': this.anotherProperty ? 'bold' : 'normal', // normal }; return styles; }
So instead of using the ngClass directive, we use ngStyle. Then we define the inline CSS property and value pairs based on the existence of multiple properties.
And there you have it! That's how you change CSS properties by utilizing angular style binding and class binding.
|
https://coursetro.com/posts/code/24/Angular-2-Class-&-Style-Binding-Tutorial
|
CC-MAIN-2017-26
|
refinedweb
| 544
| 58.58
|
Authorization process of YouTube Data API
Reading time: 45 minutes | Coding time: 10 minutes
In this article, we will go through the Authorization process of YouTube Data API and understand the use of various tokens like client secret key, authorization token, refresh token and much more. It use OAuth2.
The sub-topics we covered are:
- Getting Youtube Data API key
- Understanding Refresh Tokens
- Client Side WorkFlow of tokens
- Server Side WorkFlow of tokens
- Python demo using API key and using OAuth Authentication
Youtube data API or simply YouTube API is an API service by Google to let us interact with the youtube.com servers directly. YouTube data API is basically used to directly interact with the YouTube services through some API . You can use it to upload videos, manage playlists or simply comment or like a video or you can also use it for searching for content you can search for videos channels playlists.
YouTube data API also provides many functionalities which are not available directly on the YouTube website But they can be achieved by using the YouTube Data API.
The methods of Youtube API accepts various parameters which are used to cusotmize the requests according to needs.
There are Youtube API libraries for almost all programming languages but in this case we will be using python.
Read the Documentation of Youtube Data API from here
Getting Youtube Data API key
To start with, we will need to have a google account and obtain credentials (i.e. API key) on the to access the Youtube Data API, following these steps:
- In order to create an API key you need to have a Google developers console project so in order to create that you have to simply go to the url console.developers.google.com
- log in with your Google account.
- Click “create a new project”
- Fill out the form, and click “Create”
- click on enable and it is enabling the API for the Youtube API project
- In the next page, click on “API key” and select the restrictions use wish to put on the api access. Basically select youtube data api v3 because we only need to access this api
- Scroll down and click “Create”. Then copy your “API Key”.
There are two types of Youtube Data API. Basically whatever task that can be done on youtube.com without logging into the google account.
Understanding Refresh Tokens
- Refresh token is a special type of token used in Restful API's. It is a long life token that is used only for authorisation server.
- Typically we can use access tokens against multiple resources. This means if this access token is a bearer token and the authorisation server was hacked so that it were controlled by an attacker, the access token can be reused against other resources and the attacker can now get the resources.
- Refresh token is generated to solve this problem as it's a long lifetime token, that's only used against authorization server. Since it's only used against the authorization server the risk of it being stolen is substantially lower the client can use it against the token endpoint to get a new access token. It's like refreshing the access token that's why it is called refresh token.
Generating refresh tokens for Youtube Data API
- The first thing we'll do is browse to .The OAuth playground is a tool hosted on Google developer site that lets developers see authorization flow step by step and see how API calls are made at the HTTP layer
- We will generate a live refresh token that we can exchange for access tokens to make YouTube data API
- We need to configure the OAuth playground to use our client secret and client ID. We can find our client ID and client secret from the Google API console
- Click the Settings button and check the boxes using use your own off credentials and make sure the access type is set to offline because this is what we need to ensure that we receive a long-lived refresh token and not a short-lived access token.
- We present it with two fields - one for client ID and one for client secret.
- Copy-paste the values over from the API console there's one more thing we need to set up.
- Let's click on edit settings if we haven't set this yet .
- Click update and now let's go back off to playground and select the api's authorize.
- Select the YouTube analytics API a read-only scope and the YouTube data API v3 .
- Now, click authorize api's will be forwarded to a page we'll need to grant access if we're in charge multiple channels will first be presented with an
- account picker.
- Click accept and continue we now have an authorization code which we can use six change for a refresh token and access token.
- Click exchange authorization code for tokens.
- The Oauth playground will populate the refresh token and access token fields after making the API call .
- We can start using these immediately but the value wants to save our scripts is in the Refresh token field as we can see the access token will expire in about one hour the official Google API clients will all handle obtaining an access token for us as long as we supply a client ID, client secrets and refresh token.
Client Side WorkFlow of tokens
- The user is first redirected to Google's OAuth 2.0 server to start the authentication process.
- The user is asked for permission whether to grant the application, the requested access. The user can then consent or refuse to grant access to your application.
- If the user approves the access request, then the response contains an authorization code otherwise, the response contains an error message saying access denied.
- The authorization code can be exchanged for an access token which can be used to access the youtube user data.
- After obtaining an access token, our application can use that token to authorize API requests for a user account.
- When we use the refresh token for the authorization to obtain an access token, the access token represents the combined authorization and can be used for any of its scopes.
- OAuth handles the refresh tokens internally by exchanging it for access tokens for authorization. Refresh tokens are long life tokens so we can maintain the user session for a longer time.
Server Side WorkFlow of tokens
- The Google OAuth server authenticates the user and obtains consent from us for our application to access the requested scopes. The response is sent back to our application using the redirect URL you specified.
- The OAuth server receives our application's access request by using the URL (Scope) specified in the request and sends a response accordingly.
- The OAuth server uses the client secret mechanism as a means of authorizing a client, the application requesting an access token exchanges the client secret for the access token.The client secret must be kept confidential as it can be used to authenticate as a person and access the data. Only once the Users are authenticated (proven that they are whom they say they are), they are granted access to the API.
- After the OAuth server receives the authorisation code contained in our client secret json file, it can exchange the authorization code for an access token.
- Example of responses from the Google OAuth server:
An error response:
An authorization code response:
Dependency required
The next thing that we are going to need so you can use the Google API Python client for directly sending the request to the YouTube data API through some already written functions so what I'm going to do is I'm just gonna make a very simple pip
command
Following dependency is required to access the youtube api. Install it using the command given below.
pip install google-api-python-client
Google API Python client is actually a Python client for dealing with the Google API and we're going to use that for interacting with the YouTube data API.
Google API Python client is the standard library for python to handle youtube data API related tasks.
Code 1 : Using API Key
Now what we are going to do is from APIclient.discovery, import build function. Build is actually a very interesting function which will simply create the resource object in the Google API Python client which can be used to interact with any Google API.
Assign the api key which you have copied from the google developer's console to a variable, say api_key.
from apiclient.discovery import build api_key="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
Now, we will create a youtube resource object. For doing that we have to just use build function. We have to just name the API that we want to interact with so let's say I want to interact with the YouTube API so youtube and we can also provide which version of the API will interact with. In this case we are using version 3 of the youtube data api to interact. We will also pass the developer key that is the api_key as the parameter. The api key acts as the credential for accessing the api.
youtube = build('youtube', 'v3', developerKey=api_key)
Youtube is actually a resource object which can be used for interacting with the YouTube Data API. This is how we can set a project for starting to interact with the YouTube Data API. We can call various functions using youtube resource object to access and use various functionalities of the Youtube Data API.
Code 2 : Using OAuth Authentication
If you are trying to deal with some protected resources some private resources of a user for example the permission of a user to like a video or comment on a video so for that kind of cases we need a better authentication framework and that's why we have something called OAuth 2.0. Oauth 2.0 is an authentication framework which provides a flow to the applications through which they can gain limited access to a user's protected resources. First we are going to import all the dependencies used.
Build is the same as used in the above case.InstalledAppFlow is a function that lets us specify the scope and client secret for the Oauth authenticcation to access the youtube data API.
from apiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow
We will request user content consent so that the user can access so that app can access the users data so for that we need the oath client ID .This is basically allowing us to be able to use the OAuth flow for our application so for that we can simply select our application type as other because we are using a simple Python script and let me name it as "youtube_api" to create it. This client secret we just created. In order to use them you have to just click on this download button you can simply download a JSON file or for a client secret and then you have to simply put it in your project folder. Now we'll specify the client secret file path to access it and the scope URL to specify the scopeof the application.
client secret is a json format file used for providing details of the user to process the authentication. The structure of the client secret json is as follows -
Client Secret File example:
{ "installed":{ "client_id":"XXXXXXXXXXXXXXXXXXX", "project_id":"youtubeapi-264219", "auth_uri":"", "token_uri":"", "auth_provider_x509_cert_url":"", "client_secret":"XXXXXXXXXXXXXXXXXXX", "redirect_uris":[ "urn:ietf:wg:oauth:2.0:oob", "" ] } }
CLIENT_SECRET_FILE = '/client_secret_1.json' SCOPES = ['']
Now it's time to run the authentication flow so for that first of all, we create the flow object and now we will run the flow and we will be getting the credentials once that flow is complete and finally we will create a YouTube resource object by using the build function. We have to specify that we need to use version 3. Now we'll be giving the credentials so reusing the credentials argument for creating this youtube resource . Let us run it so we got a URL to visit so we are going to click on this URL to authorize this application .
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES) credentials = flow.run_console() youtube = build('youtube', 'v3', credentials=credentials)
To perform a demo we will be liking a video using our authenticated google account.We will pass the youtube video id which can be found in the youtube video URL. For example in this case i have taken url of this video:. We can pass 'like','dislike' or 'none' as the value of rating parameter to perform the respective tasks.
Now we will execute the script to send a request to the youtube server to like ths particular video.
youtube.videos().rate(rating='like', id='YbJOTdZBX1g').execute()
|
https://iq.opengenus.org/authorization-process-of-youtube-data-api/
|
CC-MAIN-2020-24
|
refinedweb
| 2,147
| 58.01
|
Simple ADO Database Read, Insert, Update and Delete using C#.
Introduction
Accessing databases is a common part of most applications and with the introduction of C# and ADO.NET, has become quite simple. This article will demonstrate the four most basic database operations.
- Reading data. This includes various data types such as integers, strings and dates.
- Writing data. As with reading we will write these common types. This will be done using a SQL statement.
- Updating or modifying data. Again we will use a simple SQL statement.
- Deleting data. Using SQL.
These operations will be performed against a Microsoft Access 2000 database, however SQL or other ADO data sources could be used by simply changing the connection string.
Getting started;
- Right click on the Solution explorer - References branch.
- Select Add reference.
- Select the .NET Framework tab.
- Double click on the System.data.dll entry.
- Select OK.
- System.Data should now appear in the References list of the Solution explorer.";
Reading data
Now things get interesting. Reading is done using the ADODataReader class. (See Chris Maunder's article The ADO.NET ADODataReader class for more info on this class. ) The steps to perform the read are;
- We open the database with an ADOConnection.
ADOConnection conn = new ADOConnection(DB_CONN_STRING); conn.Open();
- We create a SQL statement to define the data to be retrieved. This command is executed to return an ADODataReader object. Note the out keyword in the Execute method. This is C# talk for pass by reference.
ADODataReader dr; ADOCommand cmd = new ADOCommand( "SELECT * FROM Person", conn ); cmd.Execute( out dr);
- We loop through each record in the ADODataReader until we are done. Note: The data is returned directly as a string and the field name is used to indicate the field to read.
while( dr.Read() ) { System.Console.WriteLine( dr["FirstName"] ); }
- We clean up.(); }
Reading different data types.
int nOrdinalAge = dr.GetOrdinal( "Age" ); if( dr.IsNull( nOrdinalAge ) ) { System.Console.WriteLine( " Age : Not given!" ); } else { int nAge = dr.GetInt32( nOrdinalAge ); System.Console.WriteLine( " Age : " + nAge ); }
Insert, Modify, Delete and other SQL commands.
Inserting
The above code inserted a record by building a SQL command which was later executed. Some things to note in the formatting of the command are;
- Numerical values are presented directly. No single quotes (').
- Strings are presented wrapped in single quotes ('blah').
- Be sure the strings do not include any embedded single or double quotes. This will upset things.
- Date and times are presented wrapped in single quotes in international format ('YYYYY/MM/DD HH:MM:SS').
Modifying'";
Deleting.
String sSQLCommand = "DELETE FROM Person WHERE FirstName = 'Bobo'";
About the sample code.
Conclusion.
Te das cuenta theMonster auriculares que tiene sin duda una protección considerablePosted by cheneason on 06/04/2013 01:52pm
[url=]auriculares beats[/url] Hvis man ville præcisere, hvad præcist udrette audio transskription tjenesteudbydere samt transskribere tjenester udføre, svaret er, som de fuldføre opgaven med at konvertere musik information i elektronisk fil info. Hvis det overhovedet er muligt, kan en uddannet transcriptionist lytte til lyd tape løsninger, der har brug for at konvertere, og derefter dokumentere dem i en elektronisk digital fil, der kan helt sikkert være en sætning fil eller tilknyttede fil formatering. [url=]Comprar beats baratos[=]auriculares beats[/url] Denne nye forretninger med salget af den seneste teknologiske udvikling og kvalitetsudvikling i beats af forskellige mærker er en ganske næring til en. Kompatibilitet er også en grund, der gør folk kører efter de nye versioner på markedet. Beats by Dre er en af de mest populære mærker, når det kommer til hovedtelefoner af højeste kvalitet. News viser, at de har et partnerskab med Apple om at levere et eksklusivt sæt hovedtelefoner der er helt mindre i antal, men ganske højt i prisklasse. Monster beats er også en anden vigtig mærke i serien.Reply
c# DatabasePosted by arith_s on 01/17/2010 03:45
System.Data.ADO not found!....?Posted by gilly914 on 02/02/2008 10:01am
How come my Visual Studio cannot find the namespace System.Data.ADO??? I added the System.Data reference, but it didn't solve the problem...
System.Data.ADO does not existPosted by dcrooks on 10/18/2009 11:28am
The System.Data.ADO was removed from the beta. Need to look at these: System.Data System.Data.SqlClient System.Data.OleDb System.Data.OdbcReply
stupid, but still doesn't work...Posted by gilly914 on 02/02/2008 04:17pm
I checked the comments, and found out my silly mistake, but now the code still won't run! I seem to have problems with the ConnectionString parameter... I used what is given in the article but with my file : DB_CONN_STRING = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=C:\\temp\\db1.mdb"; ..and i can't find what seems to cause the problem. Can someone help me???Reply
Insert statementPosted by sarathshiva_19 on 02/02/2006 08:02am
Hi, I get an exception box saying "syntax error in insert into statement" when I try to execute the following code, the exception is thrown when I call the executenonquery method in the try block. Any input on this is highly appreciated. Thanks and regards, --sarath. sarathshiva_19@rediffmail.com OleDbConnection conn = new OleDbConnection ("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=..\\..\\ePrescription.mdb"); OleDbCommand myOleDbCommand = new OleDbCommand("INSERT INTO UserTable (UserName, PassWord, Address, CreationDate, Name, Salutation, PhoneNumber, Email) VALUES ( ' s ' , ' s ' , ' Cunningham Road ' , ' 18:08:43-02/00/06 ' , ' name ' , ' Mr ' , 'sdfgsfdg ' , ' s@s.com ' )", conn); conn.Open(); try { myOleDbCommand.ExecuteNonQuery(); } catch (System.Exception err) { MessageBox.Show ("" + err.ToString()); } finally { // Close the connection if it is open if (conn.State==ConnectionState.Open) { conn.Close(); } }Reply
How can I use variables in the INSERT command?Posted by Legacy on 02/25/2004 12:00am
Originally posted by: Kevin Cahn
I've created similar code in JAVA2. I can insert hardcoded data in my database without any problems. However, in a real world application you will want to be able to insert data from variables into the database. After all, if you were only going to insert hardcoded data, then you could just go into the database and type the data in. How can I insert variable data into a database using SQL commands?
Thanks,
Kevin
Variables in INSERT commandPosted by marcnz on 01/08/2005 03:10am
Here is an example: private void fnInsertDate(string pCat) { ... OleDbCommand dCmd = new OleDbCommand("INSERT INTO category(catname)VALUES ('" + pCat + "')", dCon); ... } Hope this help.Reply
How can I use variables in the INSERT command?Posted by wdicks on 11/10/2004 06:18am
This has been my question too! Does anyone know the answer to this?Reply
Synchronised updatesPosted by Legacy on 10/21/2003 12:00am
Originally posted by: zee
What happens when two people access the application at once and one updates another reads. There is a possibility of reading incorrect data. In java I would synchronise, what do you do in C#?Reply
databasePosted by Legacy on 06/20/2003 12:00am
Originally posted by: A.RAMA KRISHNA
Gr8Posted by Legacy on 06/06/2003 12:00am
Originally posted by: jehanzeb khan
hi,Reply
well i read this and it really helped my problem. But to be very frank C# sucks. Java is the best.
nothingPosted by Legacy on 01/18/2002 12:00am
Originally posted by: cy
Want a real world applicationPosted by Legacy on 09/14/2001 12:00am
Originally posted by: Jayant Bahulekar
Can you give us a real world application?
in this applications the insert/update and delete statements are hardcoded..
Can you please brief on how to write same application as interactive, where user can add/modify/delete a required record.
Regards
JayantReply
|
http://www.codeguru.com/csharp/csharp/cs_data/article.php/c4211/Simple-ADO-Database-Read-Insert-Update-and-Delete-using-C.htm
|
CC-MAIN-2017-17
|
refinedweb
| 1,292
| 59.9
|
Previous: Inventory Ids for Source, Up: Getting Started
Just to Review: If you've been following the examples in the earlier chapters, we now have:
Your arch User ID In Introducing Yourself to arch, you set an
ID string that
arch uses to identify you.
Your First Archive In Creating a New Archive, you created
your first archive and made that your default archive. In
Starting a New Project you added the
hello-world project to
that archive.
Your Initial Source Tree In Starting a New Source Tree you
began to initialize the sources for
hello-world as an
arch project
tree and in Inventory Ids for Source you assigned inventory
ids to the source files in that project.
Now it's finally time to import the sources for
hello-world into
your archive. That will happen in two steps:
(1) create a log
(2) import the sources.
You're about to create a new revision of
hello-world in your
archive: a record of how that project looked at a particular point in
time.
Whenever you create a new revision, the first step is to create a log file for that revision:
% cd ~/wd/hello-world % tla make-log ++log.hello-world--mainline--0.1--lord@emf.net--2003-example
The output from that command is the name of a file which you must now edit. Initially it contains:
Summary: Keywords:
You should fill out this file just like an email message. Add a short
description of the revision in the
Summary: field, and a full
description in the body. Just as in email, the body must be separated
from the headers by a blank line. When you're done, the log might look
like this:
Summary: initial import Keywords: This is the initial import of `hello-world', the killer app that will propel our new .com company to a successful IPO.
Usage Note for vi Fans: The default filename of log messages starts
with the character
+.
vi is a non-standard program in the sense
that it treats arguments starting with
+ as options rather than
ordinary arguments. Therefore, you should be sure to type the
filename for
vi starting with
./, as in:
% vi ./++log.hello-world--mainline--0.1--lord@emf.net--2003-example
or you could simply:
% vi `tla make-log`
Shortcut Note: This section describes the "long way" to make the
log entry to go with your initial import. There is a short-cut that
can let you skip this step: the
-L and
-s options to
tla import.
We've walked though the long way here but later you might want to try
tla import -H to learn about the shortcut'.
Finally, we can ask
arch to add our source to the archive:
% tla import [....]
Note: If you have received an error along the lines of apparent source files lack inventory ids These apparent source files lack inventory ids, please reread Inventory Ids for Source and either add each file or change the id-tagging-method to names.
We can observe the side effects of that command in a few ways.
For one thing, we can ask
arch what revisions exist in the archive
for our project:
% tla revisions hello-world--mainline--0.1 base-0
In fact, we can get more detail:
% tla revisions --summary --creator --date \ hello-world--mainline--0.1 base-0 2003-01-28 00:45:50 GMT Tom (testing) Lord <lord@emf.net> initial import
What's changed in the project tree? Recall that we have something called a patch log:
% tla log-versions lord@emf.net--2003-example/hello-world--mainline--0.1
Now it has an entry:
% tla logs hello-world--mainline--0.1 base-0 % tla logs --summary --creator --date \ hello-world--mainline--0.1 base-0 2003-01-28 00:45:50 GMT Tom (testing) Lord <lord@emf.net> initial import % tla cat-log hello-world--mainline--0.1--base-0.
import created a new revision in the archive. Note that the
revision it created is called
base-0 and that we can form a longer
name for that revision by prepending the category, branch, and
version:
hello-world--mainline--0.1--base-0 ^^^^^^^^^^^ ^^^^^^^^ ^^^ ^^^^^^ | | | | | | | patch level name | | | | | version number | | | branch name | category name
If we add in the archive name, we get something called a qualified revision name fully qualified revision name, which is a globally unique identifier for the revision:
lord@emf.net--2003-example/hello-world--mainline--0.1--base-0 ^^^^^^^^^^^^^^^^^^^^^^^^^^ | archive name
Fully qualified names will be of increasing importance as you learn about distributed repositories in later chapters.
Let's look at what
import did to the archive:
# cd to the directory for the version we are working # on: # % cd ~/archives % cd 2003-example/ % cd hello-world/ % cd hello-world--mainline/ % cd hello-world--mainline--0.1/ % ls base-0
It created a new
base-0 directory for the revision.
% cd base-0 % ls +revision-lock hello-world--mainline--0.1--base-0.src.tar.gz log
As always, the
+revision-lock file is something
arch uses
internally to keep the archive in a consistent state under all
circumstances.
The
log file is a copy of the log message you wrote, with some
additional headers added:
% cat log.
Finally, the compressed tar file is a copy of the source files in your project tree:
% tar ztf hello-world--mainline--0.1--base-0.src.tar.gz hello-world--mainline--0.1--base-0/ hello-world--mainline--0.1--base-0/hw.c hello-world--mainline--0.1--base-0/main.c hello-world--mainline--0.1--base-0/{arch}/ hello-world--mainline--0.1--base-0/{arch}/.arch-project-tree hello-world--mainline--0.1--base-0/{arch}/=tagging-method hello-world--mainline--0.1--base-0/{arch}/hello-world/ [....]
You should notice that the tar file does not include every file from your project tree. Specifically, it contains those files that are listed by:
% cd ~/wd/hello-world % tla inventory --source --both --all [....]
Finally, if you poke around in the
{arch} subdirectory of your
project tree, you'll see two new items:
% ls ++default-version =tagging-method ++pristine-trees hello-world
The directory
++pristine-trees contains (at some depth) a copy of
the tree you just imported. This is a cached copy used by other
arch commands. (Note: In future releases of
arch, it is likely
that the
++pristine-trees subdirectory will be replaced by a
different mechanism.)
If you dig around in the
hello-world (patch log) directory, you
can find a local copy of the log file for the revision you just
created (with extra headers added to that log file).
|
http://www.gnu.org/software/gnu-arch/tutorial/Importing-the-First-Revision.html
|
CC-MAIN-2015-22
|
refinedweb
| 1,112
| 61.16
|
If you’re reading this article, it’s probably because you already know about or have heard of container orchestration. But if it’s the first time you’ve come across the term, the main point of this article is to show you how to implement amazing, container-based software architecture, so welcome. Check out my second post on how to deploy a Java 8 Spring Boot application on a Kubernetes cluster.
When I started to use container microservices (specifically, using docker containers), I was happy and thought my applications were amazing. As I learned more, though, I understood that when my applications are managing individual containers the container runtime APIs work properly without any trouble, but when managing applications that could have hundreds of containers working across multiple servers or hosts they are inadequate. So my applications weren’t exactly as amazing as I had thought. I needed something to manage the containers, because they needed to be connected to the outside world for tasks such as load balancing, distribution and scheduling. As my applications started to be used by more and more people, my services weren’t able to support a lot of requests; I was nervous because the result of all my effort seemed to be collapsing. But, as you might have already guessed, this is the part of the story where “Kubernetes” comes in.
Kubernetes is an open source orchestrator developed by Google for deploying containerized applications. It provides developers and DevOps with the software they need to build and deploy distributed, scalable, and reliable systems.
Ok, so maybe you are asking yourself, “How could Kubernetes help me?” Personally, Kubernetes helped me with one constant in the life of every application: change. The only applications that do not change are dead ones; as long as an application is alive, new requirements will come in, more code will be shipped, and it will be packaged and deployed. This is the normal lifecycle of all applications, and developers around the world have to take this reality into account when looking for solutions.
If you’re wondering how Kubernetes is structured, let me explain it quickly:
● The smallest unit is the node. A node is a worker machine, a VM or physical machine, depending on the cluster.
● A group of nodes is a cluster.
● A container image wraps an application and its dependencies.
● One or more containers are wrapped into a higher-level structure called a “pod.”
● Pods are usually managed by one more layer of abstraction: deployment.
● A group of pods working as a load balancer to direct traffic to running containers is called “services.”
● A framework responsible for ensuring that a specific number of pod replicas are scheduled and running at any given time is a “replication controller.”
● The key-value tags (i.e. the names) assigned to identify pods, services, and replication controllers are known as “labels.”
When I decided to develop applications that run in multiple operating environments, including dedicated on-prem servers and public clouds such as Azure and AWS, my first obstacle was infrastructure lock-in. Traditionally, applications and the technologies that make them work have been closely tied to the subjacent infrastructure, so it was expensive to use other deployment models despite their potential advantages. This meant that applications tended to become dependent on a particular environment, leading to performance issues. Kubernetes eliminates infrastructure lock-in by offering core capabilities for containers without imposing constraints. It achieves this through a combination of features within the platform itself (pods and services).
My next challenge was to find something to manage my containers. I wanted my applications to be broken down into smaller parts with clear separation of functionality. The abstraction layer provided an individual container image that made me fundamentally rethink how distributed applications are built. This modular focus allows for faster development by smaller teams that are responsible for specific containers. All this sounds good, so far, but this can’t be achieved by containers alone; there needs to be a system for integrating and orchestrating these modular parts. Kubernetes achieves this in part by using pods, or a set of containers that are managed as a single application. The containers exchange resources such as kernel namespaces, IP addresses and file systems. By allowing containers to be placed in this manner, Kubernetes effectively removes the temptation to cram too much functionality into a just one container image.
Another important thing that Kubernetes has offered me is the ability to speed up the process of building, testing, and releasing software with “Kubernetes Controllers.” Thanks to these controllers, I can resolve complicated tasks such as:
● Visibility: I can easily recognize in-process, completed and failed deployments with state querying capabilities.
● Version control: I was able to update deployed pods using newer versions of application images and roll back to an earlier deployment if the current version was not stable.
● Scalability: I was amazed by what Kubernetes can do; applications can be deployed for the first time in a scalable way across pods, and deployments can be scaled in or out at any time.
● Deployment timing: I was able to stop a deployment at any time and resume it later.
As I researched — and played a little bit — with Kubernetes, I found that other orchestration and management tools have emerged such as AWS EC2, Docker Swarm, Apache Mesos and Marathon. Obviously, each one has its benefits, but I have noticed that they are starting to copy each other in functionality and features. Kubernetes, meanwhile, remains hugely popular due to its innovation, big open source community, and architecture.
Without Kubernetes, I would have probably been forced to create my own update workflows, software deployment and scaling; in others words, I would have had to put in a lot more time and effort. Kubernetes enables us to squeeze the maximum utility out containers and set up cloud-native applications that can work anywhere with self-contained, cloud-specific requirements.
Stay tuned for more posts on Kubernetes!
|
https://gorillalogic.com/blog/kubernetes-container-orchestration/
|
CC-MAIN-2021-21
|
refinedweb
| 999
| 51.18
|
Walkthrough: Generating Code by using Text Templates
Code generation allows you to produce program code that is strongly typed, and yet can be easily changed when the source model changes. Contrast this with the alternative technique of writing a completely generic program that accepts a configuration file, which is more flexible, but results in code that is neither so easy to read and change, nor has such good performance. This walkthrough demonstrates this benefit.
The System.Xml namespace provides comprehensive tools for loading an XML document and then navigating it freely in memory. Unfortunately, all the nodes have the same type, XmlNode. It is therefore very easy to make programming mistakes such as expecting the wrong type of child node, or the wrong attributes.
In this example project, a template reads a sample XML file, and generates classes that correspond to each type of node. In the hand-written code, you can use these classes to navigate the XML file. You can also run your application on any other files that use the same node types. The purpose of the sample XML file is to provide examples of all the node types that you want your application to deal with.
Here is the sample file:
<?xml version="1.0" encoding="utf-8" ?> <catalog> <artist id ="Mike%20Nash" name="Mike Nash Quartet"> <song id ="MikeNashJazzBeforeTeatime">Jazz Before Teatime</song> <song id ="MikeNashJazzAfterBreakfast">Jazz After Breakfast</song> </artist> <artist id ="Euan%20Garden" name="Euan Garden"> <song id ="GardenScottishCountry">Scottish Country Garden</song> </artist> </catalog>
In the project that this walkthrough constructs, you can write code such as the following, and IntelliSense prompts you with the correct attribute and child names as you type:
Contrast this with the untyped code that you might write without the template:
In the strongly typed version, a change to the XML schema will result in changes to the classes. The compiler will highlight the parts of the application code that must be changed. In the untyped version that uses generic XML code, there is no such support.
In this project, a single template file is used to generate the classes that make the typed version possible.
You can apply this technique to any code project. This walkthrough uses a C# project, and for the purposes of testing we use a console application.
To create the project
On the File menu click New and then click Project.
Click the Visual C# node, and then in the Templates pane, click Console Application.
The purpose of this file is to provide samples of the XML node types that you want your application to be able to read. It could be a file that will be used for testing your application. The template will produce a C# class for each node type in this file.
The file should be part of the project so that the template can read it, but it will not be built into the compiled application.
To add an XML file
In Solution Explorer, right-click the project, click Add and then Click New Item.
In the Add New Item dialog box, select XML File from the Templates pane.
Add your sample content to the file.
For this walkthrough, name the file exampleXml.xml. Set the content of the file to be the XML shown in the previous section.
..
Add a C# file to your project and write in it a sample of the code that you want to be able to write. For example:
using System; namespace MyProject { class CodeGeneratorTest { public void TestMethod() { Catalog catalog = new Catalog(@"..\..\exampleXml.xml"); foreach (Artist artist in catalog.Artist) { Console.WriteLine(artist.name); foreach (Song song in artist.Song) { Console.WriteLine(" " + song.Text); } } } } }
At this stage, this code will fail to compile. As you write the template, you will generate classes that allow it to succeed.
A more comprehensive test could check the output of this test function against the known content of the example XML file. But in this walkthrough, we will be satisfied when the test method compiles.
Add a text template file, and set the output extension to ".cs".
To add a text template file to your project
In Solution Explorer, right-click the project, click Add, and then click New Item.
In the Add New Item dialog box select Text Template from the Templates pane.
In the file, in the template directive, change the hostspecific attribute to true.
This change will enable the template code to gain access to the Visual Studio services.
In the output directive, change the extension attribute to ".cs", so that the template generates a C# file. In a Visual Basic project, you would change it to ".vb".
.
Notice that a .cs file appears in Solution Explorer as a subsidiary of the template file. You can see it by clicking [+] next to the name of the template file. This file is generated from the template file whenever you save or move the focus away from the template file. The generated file will be compiled as part of your project.
For convenience while you develop the template file, arrange the windows of the template file and the generated file so that you can see them next to each other. This lets you see immediately the output of your template. You will also notice that when your template generates invalid C# code, errors will appear in the error message window.
Any edits you perform directly in the generated file will be lost whenever you save the template file. You should therefore either avoid editing the generated file, or edit it only for short experiments. It is sometimes useful to try a short fragment of code in the generated file, where IntelliSense is in operation, and then copy it to the template file.
Following the best advice on agile development, we will develop the template in small steps, clearing some of the errors at each increment, until the test code compiles and runs correctly.
The test code requires a class for each node in the file. Therefore, some of the compilation errors will go away if you append these lines to the template, and then save it:
This helps you see what is required, but the declarations should be generated from the node types in the sample XML file. Delete these experimental lines from the template.
To read the XML file and generate class declarations, replace the template content with the following template code:
<#@ template debug="false" hostspecific="true" language="C#" #> <#@ output extension=".cs" #> <#@ assembly name="System.Xml"#> <#@ import namespace="System.Xml" #> <# XmlDocument doc = new XmlDocument(); // Replace this file path with yours: doc.Load(@"C:\MySolution\MyProject\exampleXml.xml"); foreach (XmlNode node in doc.SelectNodes("//*")) { #> public partial class <#= node.Name #> {} <# } #>
Replace the file path with the correct path for your project.
Notice the code block delimiters <#...#>. These delimiters bracket a fragment of the program code that generates the text. The expression block delimiters <#=...#> bracket an expression that can be evaluated to a string.
When you are writing a template that generates source code for your application, you are dealing with two separate program texts. The program inside the code block delimiters runs every time that you save the template or move the focus to another window. The text that it generates, which appears outside the delimiters, is copied to the generated file and becomes part of your application code.
The <#@assembly#> directive behaves like a reference, making the assembly available to the template code. The list of assemblies seen by the template is separate from the list of References in the application project.
The <#@import#> directive acts like a using statement, allowing you to use the short names of classes in the imported namespace.
Unfortunately, although this template generates code, it produces a class declaration for every node in the example XML file, so that if there are several instances of the <song> node, several declarations of the class song will appear.
Many text templates follow a pattern in which the first part of the template reads the source file, and the second part generates the template. We need to read all of the example file to summarize the node types that it contains, and then generate the class declarations. Another <#@import#> is needed so that we can use Dictionary<>:
<#@ template debug="false" hostspecific="true" language="C#" #> <#@ output extension=".cs" #> <#@ assembly name="System.Xml"#> <#@ import namespace="System.Xml" #> <#@ import namespace="System.Collections.Generic" #> <# // Read the model file XmlDocument doc = new XmlDocument(); doc.Load(@"C:\MySolution\MyProject\exampleXml.xml"); Dictionary <string, string> nodeTypes = new Dictionary<string, string>(); foreach (XmlNode node in doc.SelectNodes("//*")) { nodeTypes[node.Name] = ""; } // Generate the code foreach (string nodeName in nodeTypes.Keys) { #> public partial class <#= nodeName #> {} <# } #>
A class feature control block is a block in which you can define auxiliary methods. The block is delimited by <#+...#> and it must appear as the last block in the file.
If you prefer class names to begin with an uppercase letter, you can replace the last part of the template with the following template code:
At this stage, the generated .cs file contains the following declarations:
More details such as properties for the child nodes, attributes, and inner text can be added using the same approach.
Setting the hostspecific attribute of the <#@template#> directive allows the template to obtain access to the Visual Studio API. The template can use this to obtain the location of the project files, to avoid using an absolute file path in the template code.
<#@ template debug="false" hostspecific="true" language="C#" #> ... <#@ assembly name="EnvDTE" #> ..."));
The following template content generates code that allows the test code to compile and run.
<#@ template debug="false" hostspecific="true" language="C#" #> <#@ output extension=".cs" #> <#@ assembly name="System.Xml" #> <#@ assembly name="EnvDTE" #> <#@ import namespace="System.Xml" #> <#@ import namespace="System.Collections.Generic" #> using System; using System.Collections.Generic; using System.Linq; using System.Xml; namespace MyProject { <# // Map node name --> child name --> child node type Dictionary<string, Dictionary<string, XmlNodeType>> nodeTypes = new Dictionary<string, Dictionary<string, XmlNodeType>>(); // The Visual Studio host, to get the local file path.")); // Inspect all the nodes in the document. // The example might contain many nodes of the same type, // so make a dictionary of node types and their children. foreach (XmlNode node in doc.SelectNodes("//*")) { Dictionary<string, XmlNodeType> subs = null; if (!nodeTypes.TryGetValue(node.Name, out subs)) { subs = new Dictionary<string, XmlNodeType>(); nodeTypes.Add(node.Name, subs); } foreach (XmlNode child in node.ChildNodes) { subs[child.Name] = child.NodeType; } foreach (XmlNode child in node.Attributes) { subs[child.Name] = child.NodeType; } } // Generate a class for each node type. foreach (string className in nodeTypes.Keys) { // Capitalize the first character of the name. #> partial class <#= UpperInitial(className) #> { private XmlNode thisNode; public <#= UpperInitial(className) #>(XmlNode node) { thisNode = node; } <# // Generate a property for each child. foreach (string childName in nodeTypes[className].Keys) { // Allow for different types of child. switch (nodeTypes[className][childName]) { // Child nodes: case XmlNodeType.Element: #> public IEnumerable<<#=UpperInitial(childName)#>><#=UpperInitial(childName) #> { get { foreach (XmlNode node in thisNode.SelectNodes("<#=childName#>")) yield return new <#=UpperInitial(childName)#>(node); } } <# break; // Child attributes: case XmlNodeType.Attribute: #> public string <#=childName #> { get { return thisNode.Attributes["<#=childName#>"].Value; } } <# break; // Plain text: case XmlNodeType.Text: #> public string Text { get { return thisNode.InnerText; } } <# break; } // switch } // foreach class child // End of the generated class: #> } <# } // foreach class // Add a constructor for the root class // that accepts an XML filename. string rootClassName = doc.SelectSingleNode("*").Name; #> partial class <#= UpperInitial(rootClassName) #> { public <#= UpperInitial(rootClassName) #>(string fileName) { XmlDocument doc = new XmlDocument(); doc.Load(fileName); thisNode = doc.SelectSingleNode("<#=rootClassName#>"); } } } <#+ private string UpperInitial(string name) { return name[0].ToString().ToUpperInvariant() + name.Substring(1); } #>
In the main of the console application, the following lines will execute the test method. Press F5 to run the program in debug mode:
The application can now be written in strongly-typed style, using the generated classes instead of using generic XML code.
When the XML schema changes, new classes can easily be generated. The compiler will tell the developer where the application code must be updated.
To regenerate the classes when the example XML file is changed, click Transform All Templates in the Solution Explorer toolbar.
This walkthrough demonstrates several techniques and benefits of code generation:
Code generation is the creation of part of the source code of your application from a model. The model contains information in a form suited to the application domain, and may change over the lifetime of the application.
Strong typing is one benefit of code generation. While the model represents information in a form more suitable to the user, the generated code allows other parts of the application to deal with the information using a set of types.
IntelliSense and the compiler help you create code that adheres to the schema of the model, both when you write new code and when the schema is updated.
The addition of a single uncomplicated template file to a project can provide these benefits.
A text template can be developed and tested rapidly and incrementally.
In this walkthrough, the program code is actually generated from an instance of the model, a representative example of the XML files that the application will process. In a more formal approach, the XML schema would be the input to the template, in the form of an .xsd file or a domain-specific language definition. That approach would make it easier for the template to determine characteristics such as the multiplicity of a relationship.
If you have seen template transformation or compilation errors in the Error List, or if the output file was not generated correctly, you can troubleshoot the text template with the techniques described in Generating Files with the TextTransform Utility.
|
https://msdn.microsoft.com/en-us/library/dd820614.aspx
|
CC-MAIN-2016-07
|
refinedweb
| 2,260
| 56.55
|
Since Groovy 1.7.1 we can use the
sum() method on an array of objects. We already could use it for collections and iterators, but this has been extended to array of objects. The
sum() can take a closure as an argument. The result of the closure is used to add the values together. Finally we can use an initial value for the sum.
def n = 0..5 as Integer[] assert n instanceof Integer[] assert 0 + 1 + 2 + 3 + 4 + 5 == n.sum() assert 10 + 0 + 1 + 2 + 3 + 4 + 5 == n.sum(10) assert 0 + 10 + 20 + 30 + 40 + 50 == n.sum { it * 10 } assert 10 + 0 + 10 + 20 + 30 + 40 + 50 == n.sum(10, { it * 10 })
|
https://blog.mrhaki.com/2010/04/groovy-goodness-sum-values-in-object.html
|
CC-MAIN-2022-05
|
refinedweb
| 119
| 87.52
|
I've downloaded sfml from NuGet to develop with it in C#. I'm using the 2019 community version for C# and version 2.5 for sfml. With the code:
using SFML.Graphics; using SFML.Window; namespace sfml_test { class Program { static void Main() { RenderWindow window = new RenderWindow(new VideoMode(200, 200), "test"); CircleShape cs = new CircleShape(100.0f); cs.FillColor = Color.Green; window.SetActive(); while (window.IsOpen) { window.Clear(); window.DispatchEvents(); window.Draw(cs); window.Display(); } } } }
I get the following error:
System.DllNotFoundException: 'Can't load DLL csfml-graphics: Can't find given module. (Exception of HRESULT: 0x8007007E)'
I know that there already are some answers to similar questions, but these questions have been answered in 2010, with programs that don't seem to support Windows 10 (like Dependency Walker, I also did not understand the explanations.
Any help will be greatly appreciated and thank you in advance!
P.S. I'm trying to make a 2D ray tracer in C# and need a window to display it on. Most of the windows I can find are used for UI (Windows.Forms, GTK#) or are meant to work for 3D (OpenTK). Any suggestions are welcomed.
User contributions licensed under CC BY-SA 3.0
|
https://windows-hexerror.linestarve.com/q/so61736887-SystemDllNotFoundException-cant-load-sfmlgraphics
|
CC-MAIN-2020-34
|
refinedweb
| 204
| 60.31
|
Opened 10 years ago
Last modified 11 days ago
#6148 new New feature
Add generic support for database schemas
Description
There is frequently a need for Django to access data from tables in other schemas; this is especially true when building Django apps on top of legacy databases. Currently, the proposed solution is to add support for the
set search_path command (#1051) via custom initialization sql (#6064). This is a good solution for PostgreSQL users, but it will not solve the problem in Oracle, which has no analogue of
set search_path.
Solving the problem in a generic way will require adding a per-app or per-model db_schema option, in order to issue SQL queries using the syntax
"schema_name"."table_name". This may also require more advanced introspection (at least in Oracle) to determine whether the table already exists when running management commands.
A current workaround in Oracle is to manually create private synonyms inside the Django schema, referencing the necessary tables from other schemas. However, the management commands do not currently recognize the existence of synonyms via introspection. Additionally, the synonym solution may not be sufficiently generic in the long term.
Attachments (17)
Change History (194)
comment:1 Changed 9 years ago by
Changed 9 years ago by
comment:2 Changed 9 years ago by
I added support for using db_schema = 'whatever' in models.
It works for mysql at least but that's the only one I know about.
comment:3 Changed 9 years ago by
Changed 9 years ago by
remade some stuff and added testing and doc. Tested with mysql and sqlite so far
comment:4 Changed 9 years ago by
comment:5 Changed 9 years ago by
Changed 9 years ago by
Still some issues when testing, not the test themself
comment:6 Changed 9 years ago by
There are still some issues with testing. See discussion at
Changed 9 years ago by
Works with postgres and mysql but testing only works on postgres due to mysqls schema implementation.
comment:7 follow-up: 16 Changed 9 years ago by
I don't have time to fix this right now... Better someone else does it.
comment:8 Changed 9 years ago by
Restoring triage stage to Accepted.
comment:9 Changed 9 years ago by
comment:10 Changed 9 years ago by
comment:11 Changed 9 years ago by
comment:12 Changed 9 years ago by
comment:13 Changed 9 years ago by
comment:14 Changed 8 years ago by
comment:15 Changed 8 years ago by
comment:16 follow-up: 17 Changed 8 years ago by
Replying to crippledcanary:
I don't have time to fix this right now... Better someone else does it.
Fixing this should change all the logic at
django.db.backends.create_test_db, as for MySQL schemas are not really schemas, but databases - therefore, there should be not one, but several
test_* databases.
I'm interested in fixing this so schema support can be checked in (really needed on PostgreSQL), but want feedback from MySQL users.
So, are MySQL databases really equivalents of schemas? If databases are like schemas, it would need to patch model's db_schemas to
test_schemaname while testing. I don't like the idea of monkeypatching names for tests, as custom SQL will fail with different "schema" (not really) names. Isn't cleaner to fallback to less features for MySQL (as we do for SQLite)?
comment:17 Changed 8 years ago by
So, are MySQL databases really equivalents of schemas? If databases are like schemas, it would need to patch model's db_schemas to
test_schemanamewhile testing. I don't like the idea of monkeypatching names for tests, as custom SQL will fail with different "schema" (not really) names. Isn't cleaner to fallback to less features for MySQL (as we do for SQLite)?
Just few notes from a random reader:
- I had a look at MySQL manual and the
CREATE SCHEMAcommand is synonym to
CREATE DATABASE(see 12.1.6. CREATE DATABASE Syntax). The database name is rather flexible and can contain any character except
NUL(
\0) - the name is coded in a special way for the file system (see 8.2.3. Mapping of Identifiers to File Names).
- The patch contains
DROP SCHEMA
IF EXISTSextension for PostgreSQL as well, but it has been supported since the 8.2 version. Maybe it could be noted somewhere.
comment:18 Changed 8 years ago by
- Also the
SHOW SCHEMAScommand is a synonym to
SHOW DATABASES(see 12.5.5.11. SHOW DATABASES Syntax).
comment:19 Changed 8 years ago by
comment:20 Changed 8 years ago by
I would suggest to drop the MySQL support, because when you drop the database, you normally (PostgreSQL) drop also the schemas together. But because MySQL doesn't support real schemas, you cannot say which "schema" belongs to which "database" - so you don't know what to drop. Maybe some Django dev can decide (I'm not the one) :-)
comment:21 Changed 8 years ago by
I think it's an error to forbid PostgreSQL users access to the feature because MySQL implementation doesn't match. I'm in favor of dropping MySQL support to get this ready for commit.
comment:22 Changed 8 years ago by
I've just looked at the patch a little bit more and I see problem with inconsistently using the schema in table names - there is a problem with syncing:
What is the full list of existing tables? Should it be with the schema in the name or without? The problem can be seen in the
syncdb.py part that adds
+ # Add model defined schema tables if anny + if model._meta.db_schema: + tables += connection.introspection.schema_table_names(model._meta.db_schema)
This adds all tables from the specified schema to the known list of tables (but without the schema name). Those tables could be unrelated to the DB search path! This is compared to
db_table(that includes the schema) on lines 68-69
if connection.introspection.table_name_converter(model._meta.db_table) in tables: continue
The same applies to the
sql.py part of the patch.
I also miss the possibility to define global
DATABASE_SCHEMA.
There is certainly at least one problem in syncing now. Maybe it is possible to fix it easily, but it means to think about it more in depth (to have in mind the user specified schema and the DB search path). Maybe the only fix is to disallow the per model schema definition and to allow only the global one, but as I'm not expert in this area, I might be wrong :-)
Changed 8 years ago by
comment:23 follow-up:.
I've also fixed up a number of areas that were still passing around raw table names, including I think the case that oldium pointed out. Finally, I've made the necessary changes in the Oracle backend to get this to work.
I'm not too keen on dropping MySQL support just because it's difficult to test. To the end-user, Django is not in the business of creating and dropping schemas, and so it shouldn't matter what a schema actually represents as long as we can reference the tables inside it. Testing is also complicated in Oracle where "schema" is basically synonymous with "user", and I don't have the test fully working yet there either.
comment.
Please have a look at my patch for your patch (applies after you one), I've found some quotation problems, also the index name in
CREATE INDEX in PostgreSQL cannot contain schema name, because the index is always created in the same schema as the parent table (see 8.2.13 CREATE INDEX).
Changed 8 years ago by
Incremental patch that fixes CREATE INDEX problems, some quotations and supports new global settings.DATABASE_SCHEMA
comment:25 Changed 8 years ago by
comment:26 Changed 8 years ago by
comment:27 Changed 8 years ago by
Hi again all, nice to see that there is some interest.
I started working on this one again and you can keep track of progress at[[BR]]
I had some issues applying the patches but that is fixed and added some new stuff as well. I totally agree with the global DATABASE_SCHEMA and the qualified_name attribute that combines them.
The changes I made so far enables syncing again but I want to do some more work before posting another patch. I will eventually turn up as user "kmpm" here as well, to keep usernames in sync :-)
comment:28 Changed 8 years ago by
comment:29 Changed 8 years ago by
1.2 isn't decided yet... sorry
comment:30 Changed 8 years ago by
The correct branch for my work on this is
and nothing else
comment:31 Changed 8 years ago by
comment:32 Changed 8 years ago by
Hi, nice to see that this is finally being worked on.
The most elegant solution from my perspective would be if I could specify in my project-wide settings that I want to use schemas, and then I would get a generic schema implementation.
Then the database layer would create a schema for each app, so that instead of:
- auth_group (table)
- auth_user (table)
- auth_message (table)
- etc...
it would instead create it thus:
- auth (schema)
- group (table)
- user (table)
- message (table)
with the names all shorter and nicer.
But it should also allow per-app or per-model schema option to explicitly specify what you want to ease support of legacy databases etc.
Is what I am describing what is being worked on, or are you only making it so that you have to specify for every single model or app that you want it to live in a schema?
-thanks
comment:33 Changed 8 years ago by
comment:34 Changed 8 years ago by
comment:35 Changed 8 years ago by
comment:36 Changed 8 years ago by
comment:37 follow-up: 38 Changed 8 years ago by
Is what I am describing what is being worked on, or are you only making it so that you have to specify for every single model or app that you want it to live in a schema?
-thanks).
comment:38 Changed 8 years ago by).
That kind of support would still not benefit the majority of those that crave schema support, i.e. those that are trying to make django work with a legacy postgresql database, and those that are used to having tables sorted nicely into schemas.
Developers that are used to postgresql use schemas to keep their db tidy and managable, that is the foremost reason to use schemas. I don't see many usecases for what you are implementing over having each site in it's own database, although I'm sure there are some.
Would it be hard to implement my suggestion into your changes?
i.e. allowing each app to override the site-wide schema, and possibly each model also?
By the way, I don't mean to come of harsh, I'm really grateful for your work
comment:39 follow-up: 40 Changed 8 years ago by
The app specific schema might for example be specified in the init.py file in the apps root folder, or in a settings.py file in that folder, or just use the apps name. That would solve 99% of use cases IMO.
Of course we would need a setting USE_SCHEMAS to allow reuse of applications in non schema environments and to allow for an empty site-wide schema name.
comment:40 follow-up: 41 Changed 8 years ago by
The app specific schema might for example be specified in the init.py file in the apps root folder, or in a settings.py file in that folder, or just use the apps name. That would solve 99% of use cases IMO.
This is something for application-specific settings; I don't know if this is supported in Django currently. Anyway, each model in your application can have the schema specified explicitly, it could be also some application constant - like this:
APP_SCHEMA = "myschema" class MyModel(models.Model): ... class Meta: db_schema = APP_SCHEMA
comment:41 Changed 8 years ago by
class Meta:
db_schema = APP_SCHEMA
Is this something you have already implemented?
Can you provide a patch that would work with the current django development version? Or do you sync your github branch to the development version often?
This would certainly get things done, although it would be much more convenient to be able to have an app specific setting. Or have a global settings variable USE_APP_NAMES_AS_SCHEMA_NAMES = True. This would allow to put the standard django apps and 3rd party apps also into schemas.
comment:42 follow-up: 43 Changed 8 years ago by
class Meta:
db_schema = APP_SCHEMA
Is this something you have already implemented?
The db_schema is already implemented in attached patches. There is no magic included, you just define a variable APP_SCHEMA (or any other name) at the top of the file and use it later on.
Can you provide a patch that would work with the current django development version? Or do you sync your github branch to the development version often?
I don't have anything at the moment, maybe kmpm (alias crippledcanary) has more.
comment:43 follow-up:?
What do you think about the USE_APP_NAMES_AS_SCHEMA_NAMES idea? Is it doable?
comment:44 Changed 8 years ago by
sorry for not keeping this one up to date.
The only thing supported for now is db_schema setting per model.
I really would like some of the db related tickets to be solved first. Don't have the numbers now but there are some multi-db and GSOC ones that change more and related stuff that we realy shoud wait for. Thats at least my +1.
And if anyone want's to pick this ticket up, please do.
comment?
You need the last two patches - generic-db_schema-r11231.diff and generic-db_schema-update.patch.
What do you think about the USE_APP_NAMES_AS_SCHEMA_NAMES idea? Is it doable?
I don't know about new features mentioned by kmpm, I'm currently busy with other things (non-Django). You are free to dive deeper into it :-)
comment:46 Changed 8 years ago by
For anyone looking for a quick work-around, MariusBoo noted that you can define your table like this:
db_table = '"django"."company"'
This will fool the quote function to think that your table is properly quoted. This also means that you have to specify the schema for each table manually.
I just verified that this solution works with r10837 and r11802 and PostgreSQL 8.3.8.
comment:47 follow-up: 51 Changed 8 years ago by
That would only work with read operation. When you trying to write to the db, it would failed because the Django assume the sequence as
"schema.tablename"_column_id_seq, so you have to escape it as
'schema\".\"tablename'.
Specifying schema for each table is not a problem for me - explicit and no magic, just make it 'official' and documented.
Changed 8 years ago by
Patch for trunk revision 11827
comment:48 Changed 8 years ago by
Here goes...
The attached 'generic-db_schema-r11827.diff' is applicable to a recent trunk but I know there are failing tests with this one.
Especially when it comes to o2o and m2m relations.
I will try to sort them out as time goes but feel free to help. Identifying bugs and writing tests would be great.
I haven't tested the global db_schema settings at all but I will get there. I just wanted to get a patch out that doesnt conflict to much with trunk.
comment:49 Changed 8 years ago by
As I just found out... all of those m2m and o2o tests fail on a clean trunk as well. So for now the code seems to be in shape.
Changed 8 years ago by
fixes a m2m issue
comment:50 Changed 8 years ago by
Ok. Fixed a issue with m2m models where the ends of the relation were in different schemas.
I would like to get some help on mysql testing. Test database creation is dangerous because mysql has an alias between 'create database' and 'create schema' so if someone uses the same schema in tests as in dev/production then the table might get recreated, data altered or in best case testing fails.
comment:51 follow-up: 52 Changed 8 years ago by
That would only work with read operation. When you trying to write to the db, it would failed because the Django assume the sequence as
"schema.tablename"_column_id_seq, so you have to escape it as
'schema\".\"tablename'.
A minor annoyance in the quote trick is that creating indexes with the
db_index field attribute doesn't work:
Installing index for myschema.mymodel model Failed to install index for myschema.mymodel model: syntax error at or near "." LINE 1: CREATE INDEX "myschema"."mymodel_myfield" ON ... ^
comment:52 Changed 8 years ago by
comment:53 Changed 8 years ago by
Changed 8 years ago by
comment:54 follow-up: 55 Changed 8 years ago by
Last patch (
generic-db_schema-r11871.diff) when applied to the exact revisio it was generatd against, gives the following results:
- sqlite3 (patch should be a noop): 21 failures, 12 errors of 1171 tests
- PostgreSQL (8.3): 21 failures, 13 errors of 1172 tests
I've been working on this and reached the following state:
- Updated the patch to the last revision in Django trunk just before the multi-db landing: r11951.
- Fixed several bugs so the Django test suite runs on both PostgreSQL and sqlite3 without any error introduced by the patch.
See
6148-generic-schema-support-r11951.diff (download it to be able to review it).
I believe the next steps needed would be:
- Test against MySQL and Oracle and fix any problems so they also reach zero errors.
- Add more tests?
- Port to trunk as of now (post multi-db), hopefully we will be able to do that in the feature freeze period after 1.2beta1
IMHO if we do the effort on this we can provide a working patch against 1.2 so testers can play and report back w/o much trouble and then aim for inclusion in Django 1.3.
comment:55 Changed 8 years ago by
Changed 8 years ago by
comment:56 Changed 8 years ago by
I've updated the patch to a revision after the landing of multi-db.
TODO:
- Test against MySQL and Oracle and fix any problems so they also reach zero errors.
- Definitely add more tests, currently the
schemasmodeltests app is very basic.
Changed 8 years ago by
comment:57 Changed 8 years ago by
I ran the Django test suite both with and without the patch on r12426. On my Debian Lenny box the test suite is awfully slow (takes 3½h) and has several failures even without the patch. The above attachment shows the one failure which exists only when the patch is in use. IIRC this is identical to the results I got earlier with the patch against r11951.
comment:58 Changed 8 years ago by
Someone else better do it
comment:59 Changed 8 years ago by
Changed 8 years ago by
comment:60 Changed 8 years ago by
Patch has been updated to trunk as of now. It still passes the Django test suite under postgreSQL 8.3 (including schema-specific test added by the patch) and sqlite3 (it contains some commented out logging code that will be removed later). Next steps:
- Convert doctests added by the patch to unittest
- Expand the tests
- Review existing schemas/tables introspection code (as it was done with the syncdb code for this trunk merge)
- Try to see what happens with MySQL
Any help with MySQL and Oracle is welcome.
comment:61 follow-up: 63 Changed 7 years ago by
Ramiro: one nit, your patch contains some stuff specific to you, ie, opening a log file in your home directory.
comment:62 Changed 7 years ago by
comment:63 Changed 7 years ago by
Ramiro: one nit, your patch contains some stuff specific to you, ie, opening a log file in your home directory.
Yes, but that debugging function isn't being called from anywhere else so it's a no on and no log file is created. I've left that code in the work in progress patch on purpose because it isn't ready for review, particularly I was debugging an interaction I was seeing between the new multiple schema code and #12286 (reopened and fixed since then).
comment:64 Changed 7 years ago by
The latest patch (6148-r12948.diff) includes code in django/db/models/options.py (~line 106) in the Options.contribute_to_class method. The code looks like:
# Construct qualified table name. self.qualified_name = connection.ops.prep_db_table(self.db_schema, self.db_table) if self.qualified_name == connection.ops.quote_name(self.db_table): # If unchanged, the backend doesn't support schemas. self.db_schema = ''
The problem is when this is applied to the latest (post multi-db) code from svn, the
connection object refers to the default database. As a result the
prep_db_table() and
quote_name() methods used may be the wrong ones for this model. A quick fix would be to import connections and router from django.db instead of connection and then to query router for the correct database to use and then finally to get that from the connections dictionary before using it as shown above. Apart from the import line change this should be all that is needed before
connection is used:
connection = connections[router.db_for_read(cls)]
However in this discussion on django-developers forum, Russell Magee pointed out that
connection should not be used in Options at all. He feels that the unpatched code also has a bug since it uses
connection to get the max_name_length and uses it to truncate the db_table member. He opened ticket #13528 for that issue.
Apart from the quick fix I cannot see an easy way to avoid this issue. The
qualified_name member could be dropped from Options and the qualified table name could be calculated everywhere it is needed but that would mean a lot of changes to the code to replace all references to qualified_name. Also using qualified_name is quicker since it is calculated once and reused, it would be a pity to lose that. Perhaps qualified_name could be hidden behind a method that lazy-loads the member variable the first time it is used. Unfortunately I am not familiar enough with the database layer design to know if this is possible or even a good idea.
Changed 7 years ago by
comment:65 Changed 7 years ago by
Patch
6148-r13366.diff contains:
- Post-r13363 updates.
- Implemented compatibility with multi-db as outlined by Peter Long (plong). I propose we wait for the core dev team to decide the strategy to be used to get connection-specific information out of the model's
_metaOptions instance (#13528, and the Query refactoring GSoC 2010 project).
- Converted all tests to unit tests. They still need to be expanded.
Test suite passes for sqlite3 and postgresql 8.3 (modulo the unrelated #13799 failure currently present in trunk).
comment:66 Changed 7 years ago by
When installing the patched r13366 I receive the following message:
byte-compiling /usr/local/python/lib/python2.6/site-packages/django/db/backends/oracle/creation.py to creation.pyc
SyntaxError: ('non-default argument follows default argument', ('/usr/local/python/lib/python2.6/site-packages/django/db/backends/oracle/creation.py', 70, None, 'def _create_test_db(self, verbosity=1, autoclobber=False, schema):\n'))
comment:67 follow-up: 68 Changed 7 years ago by
comment:68 Changed 7 years ago by
comment:69 Changed 7 years ago by
comment:70 Changed 7 years ago by
comment:71 Changed 7 years ago by
comment:72 Changed 7 years ago by
comment:73 Changed 7 years ago by
I saw you've just changed the current status to 'new'. I'm really interested to achieve this feature and become it a core-integrated one. Is there anything I can do to help?
Many thanks.
comment:74 Changed 7 years ago by
comment:75 Changed 7 years ago by
I cannot assign a schema to m2m-tables. Tables like
- auth_group_permissions
- django_flatpages_sites
...and so on are still in my public-Schema.
I'm using PostgreSQL 8.4 with PostGIS Extension.
Another problem is the incompatibility with PostGIS: every geometry-related colums isn't added to the table.
Changed 7 years ago by
m2m-Tables
comment:76 Changed 7 years ago by
comment:77 Changed 7 years ago by
comment:78 Changed 7 years ago by
comment:79 Changed 7 years ago by
comment:80 Changed 7 years ago by
comment:81 Changed 6 years ago by
comment:82 Changed 6 years ago by
comment:83 Changed 6 years ago by
looks like svn did not pull in all of the trunk changes. updated again and re-ran diff. attached new diff.
comment:84 Changed 6 years ago by
comment:85 Changed 6 years ago by
Pretty nasty bug in this still - if you run tests which are left incomplete, Django will ask 'if you would like to try deleting the test database 'TEST DATABASE - the problem is that the _destroy_test_schemas method is connecting using your normal alias, which will hit your working database.
comment:86 Changed 6 years ago by
comment:87 Changed 6 years ago by
comment:88 Changed 6 years ago by
comment:89 Changed 6 years ago by
comment:90 Changed 6 years ago by
comment:91 Changed 6 years ago by
Just a note, in case it's needed. The analogue of
set search_path in Oracle is:
alter session set current_schema = SCHEMA
comment:92 Changed 6 years ago by
comment:93 Changed 6 years ago by
I have the same need, at the moment I'm trying to use this postgresql specific "hack"
comment:94 Changed 6 years ago by
comment:95 Changed 6 years ago by
The best solution I found was to configure postgresql to set a default
"search_path" for the user I connect as from Django:
ALTER USER "djangouser" SET search_path to schema1, schema2, public;
All the django tables get created in
"schema1" and there is zero additional configuration required on the Django side.
comment:96 Changed 6 years ago by
comment:97 follow-up:... :)
The second question is if there is any core developer willing to support my work? I hope there is somebody interested, as otherwise it can be pretty hard to actually get the work finished and into core.
As said, I won't start working on this before I have time to do so. This means at least a month before I can start polishing the patch, likely a bit more.
comment... :)
When using raw SQL, I already assume that it's preferable to use the model introspection APIs to substitute in all table names, field names, etc, rather than hardcoding them, so I don't have any problem with that requirement.
I suppose it's a bit of an issue that
._meta is undocumented and technically private API, but it's already pretty well recognized that large swaths of it are de facto public (and I think there may even be a ticket for cleaning it up and documenting parts of it).
comment:99 Changed 6 years ago by
comment:100 Changed 6 years ago by
comment:101 Changed 6 years ago by
Initial status report for the work on this ticket. Using Meta: db_schema is somewhat working on PostgreSQL. Other backends will not work at all currently (even without schemas). Lacks most tests and many features, and of course lacks all polish.
Implementing the feature fully is much larger amount of work than one would expect. Luckily it seems there aren't any really hard problems left.
I started from the latest patch in this ticket. There was one big mistake in that patch: there is no way to have a ._meta.qualified_name which would be directly usable in queries. Different backends need different quoting etc for the qualified_name, thus it can only be resolved at the compiler.py stage.
To fix this, I change model._meta.qualified_name to a tuple (db_schema, db_table), where db_schema can be None. As a result of this, the patch implementation has a pretty big change to alias usage in queries: where currently first instance of each table will use the plain table name (ie. no alias at all), the schema support branch changes this in a way where even the first occurrence of the table will get an alias. There are two reasons:
- The implementation would get somewhat nasty without this: for example any column could either have alias, or qualified_name as the prefix, and one would need to check this each time when quoting the name. Same for where clause entries, order_by entries, aggregates and so on.
- I wonder if users really want to see queries like:
select "some_schema"."some_table"."col1", "some_schema"."some_table"."col2", "some_schema"."some_table"."col3" from "some_schema"."some_table" where "some_schema"."some_table"."col1" = 1
instead of:
select T1."col1", T1."col2", T1."col3" from "some_schema"."some_table" T1 where T1."col1" = 1
In addition I believe the always-alias implementation will make SQL generation faster and cleaner. The downside? .extra() users will have a fun time rewriting every: "some_table"."col1" to T1."col1".
So, the question is if the always-alias implementation has any chance of getting in. I really think it will result in cleaner queries in SQL, and it will simplify query generation. The generated query string should be an implementation detail, and .extra users will need to adapt to the changing queries.
If the above is seen as backwards incompatible, I will have to think of a way to get the old behavior back. This will likely come with a performance penalty, which is unfortunate as generating the column list is even currently somewhat slow for wide tables.
The work can be found from. The bulk of the work resides in database introspection, and I haven't even touched oracle or mysql yet...
Sidenote: sql/query.py rev_join_map is now removed. There wasn't enough usages for it to keep it around. It was used in .combine() where it is easily replaced by using alias_map directly, and in .relabel_aliases, where it gave a really small performance boost.
comment:102 Changed 6 years ago by
Status report: more work uploaded to github. Now there is no always-alias or rev_join_map removal. The test suite now passes on pgsql and sqlite. MySQL is the next target. There is some major items still left (apart of supporting mysql and oracle):
- Each database alias should have an user-settable default SCHEMA. In addition SCHEMA_PREFIX is needed for Oracle and MySQL testing.
- on SQLite the dbtable should be prefixed with the schema (as in '%s_%s'). This is to support running tests using schemas on sqlite.
- The above two items will cause some refactoring to introspection, creation and query running.
- The creation and introspection APIs need to be reviewed and probably refactored.
- Support for renaming schemas for testing (dbschema 'dbschema1' will become 'test_default_dbschema1' and so on, that is 'test_%s_%s' % (connection_alias, dbschema)). Needed for backends where Django's database NAME and schemas live in the same namespace (MySQL, Oracle).
- Documentation
- And finally some more tests.
So, work is advancing but this feature is _much_ bigger than I anticipated. Again: work can be found from. The feature should be already fully usable on PostgreSQL (using settings.DEFAULT_SCHEMA and model.Meta db_schema).
I think using always-alias would be a good idea, but it is backwards incompatible. Maybe if .extra() could be deprecated in some way, then adding always-alias to queries would work. I will create another ticket for query.rev_join_map removal.
comment:103 Changed 6 years ago by
comment:104 Changed 6 years ago by
Unfortunately a new and somewhat annoying problem found. Initial sql (the raw sql in app/sql/*.sql files) is going to be problematic. The problem is that because project settings can change the qualified table names (by DEFAULT_SCHEMA or 'SCHEMA' in connection settings) you can no longer know what the table name is in the raw SQL file. In addition, on MySQL and Oracle the qualified table name will need to be changed in test runs to avoid namespace collisions, making it impossible to write a raw SQL file even if you know the settings' default schema.
When using raw SQL in Python you now need to use connection.qname(model), which will return a correctly quoted qualified table name for the model's table. However, in the initial SQL files you can not do that. I think I will not fix this for the initial implementation. Current use of the raw SQL files will work, but when using schema support you will have problems especially on Oracle and MySQL. This could perhaps be fixed later on by having for example ##schemaname## placeholder in the raw SQL files which is then replaced by the in-use schema name. But, as said, this is a problem for later times.
Current status of the feature: SQLite now has faked schema support, the schema name is just appended to the table's name. Both settings.DEFAULT_SCHEMA and per-alias SCHEMA configurations now work in addition to the Meta: db_schema. Introspection and database creation work fully, and full test suite pass on both SQLite and PostgreSQL even when global settings defines a custom schema (except for the above mentioned initial raw SQL issue). Making the tests pass involved a lot of raw SQL rewriting from "select * from sometable" to "select * from %s" % connection.qname(SomeModel). MySQL and Oracle are still totally broken.
EDIT: Good news everybody! I just realized that initial SQL can't be used in testing, so initial SQL in testing isn't a problem :)
comment:105 Changed 6 years ago by
But at least PostgreSQL allows you to set schema search path. Wouldn't this help with raw SQL?
comment:106 Changed 6 years ago by
mitar: Yes it would. However I don't think it is Django's business to change seatch_path, at least if not explicitly asked. In addition, you will have no problems on PostgreSQL except if you plan to install the same application in multiple schemas which could happen to 3rd party apps for example. Testing will not be a problem on PostgreSQL except in the previous case.
It isn't hard to write proper raw SQL which works in testing, you need to do cursor.execute("SELECT * FROM %s WHERE id = %%s" % connection.qname(ModelClass), (id_val,)). You do not need to do this connection.qname transformation if you do not plan to support schemas. Everything will work just as before in that case.
It would actually make sense to also have a connection.cols(ModelClass) -> named_tuple, as this would help in writing proper SQL with qualified names (DRY also).
Current situation: MySQL, PostgreSQL and SQLite all pass full test suite when running under custom schema. The django/db/backends changes will need to be reviewed and there is some need for a rewrite. It is bit of a mess at the moment. Supporting Oracle should also be pretty straightforward, as MySQL and Oracle have similar schema support from Django's perspective.
The docs should not advertise this feature too much. For most applications you really don't want to use schemas. On SQLite the schema support is just a compatibility hack, on MySQL you definitely do not want to run with global custom schema (use different database instead). However, on PostgreSQL and Oracle this could be really valuable especially for hand-written/legacy schemas.
comment:107 Changed 6 years ago by
comment:108 Changed 6 years ago by
comment:109 follow-up: 110 Changed 6 years ago by
I now have something that passes all the likely-to-break tests on all four core backends. Running the full test suite on all backends takes a lot of time, so I haven't done that. Code at github.
The patch is rather large (+1559, -443 lines), and most of that is actual code changes. While lines of code isn't that important, this patch introduces a source of confusion into introspection. Previously, a Model could be identified uniquely by its table name. Unfortunately, there are multiple formats for qualified names:
- (None, table) from models: This format says that the table should reside in database default schema. This can be settings.DEFAULT_SCHEMA or the search_path default schema. The problem is, on PostgreSQL we really do not know what that search path default schema is.
- (someschema, table) from models
- (someschame, table) from database
When we have model with qualified name (foo, tbl) in SQLite it is turned into (None, foo_tbl) in the database (no real schema support on SQLite). On Oracle & MySQL in testing (foo, tbl) -> (default_foo, tbl) for alias default. This is because the production database's schemas and testing schemas live in the same namespace.
The end result of this is that it is really error-prone to do introspection and inspection. If you are asked if table foo, tbl exists you must know if the foo, tbl is from the model, or from database. If it is from a model, you must do conversion to database format first. The problem is, in the patch it isn't at all clear when you have database format, and when you have Model's format. It works, but mostly by luck. My current idea for fixing this is to introduce two namedtuples, DBQname and ModelQName so that it is possible to assert the methods get data in the format they expect.
But the most important question at the moment is how much we want schema support? I am sure this feature would cause headaches for schema migrations for example. Obviously I would like the schema support in core, but I think a final design decision is needed, as the feature as implemented is much larger and complex than one would have thought beforehand. So, I will mark this ticket as design decision needed.
One option would be to have schema support, but not for introspection. The problem with this approach is that you can't use the Django's default test runner, as you will not be able to flush & create the database without any introspection support. In effect, setting model's meta.db_schema to some value would imply managed=False.
Another option is to support this feature only when full schema support is available. That would mean PostgreSQL always, and MySQL and Oracle when you run the tests on different database instance, so that production and testing schemas do not collide. In effect, you would need TEST_PORT and/or TEST_HOST in DATABASES to be set to run the tests on MySQL or Oracle (only when using schema support, of course).
comment:110 Changed 6 years ago by
comment:111 Changed 6 years ago by
Correct. The rule is: use Meta.db_schema or connection's
settings_dict['SCHEMA'] or settings.DEFAULT_SCHEMA.
comment:112 Changed 6 years ago by
The added patch (6148_django1.5.diff) should make it easier to test this feature. Short usage instructions:
- set model specific schema by using Meta.db_schema option (works similarly to db_table, also present for
ManyToManyFields)
- set database specific schema by settings.py DATABASES setting 'SCHEMA'.
- when running raw SQL you will need to use connection.qname to get the schema qualified table name of a model (the tests contain plenty of examples, search for qname in regressiontests/queries/tests.py).
- note that on MySQL and Oracle the schemas is automatically prefixed by the database alias to avoid collisions between production and testing. This is the reason for the above qname usage - you do not know the table's qualified name, and it will be different in testing and production.
- do not test the patch on a database instance containing production data. It is possible that running tests will drop your production schemas instead of testing schemas. This should not happen, but the feature is currently alpha quality...
Otherwise basic usage should work including syncdb. There might be oddities in table creation SQL output from manage.py sql* commands, and inspectdb isn't too well schema aware currently.
comment:113 Changed 5 years ago by
The problem about running raw SQL will be introduced by the app-loading refactor anyways (#3591). The refactor introduces configurable table prefix per app which means a model will no longer know its table name. The problem isn't of course nearly as bad in the app-refactor, as the prefix is fully controllable by the project author. However, for reusable apps the problem is very similar to what is introduced by db-schemas.
I will need to update the patch, as it doesn't apply to head currently.
I don't believe there to be that much actual coding work left anymore. However, I am not sure if we have an agreement if we want this into core. A nice feature, but it also complicates things. For example 3rd party apps dealing directly with raw SQL will need updates (South comes to mind here).
comment:114 Changed 5 years ago by
I updated the patch to current master, it can be found from here.
The patch is currently at ~1700 lines added, 500 removed. So, it is a pretty big patch.
It does work on my select test list on every core db. I have tested it using the following tests: introspection transactions inspectdb fixtures queries extra_regress prefetch_related test_runner aggregation_regress dbschemas
GIS isn't yet dealt with.
Everybody who wishes this feature into core should test the patch. No need for code reviews, just test it for your use case. Testing should be simple: download the code from the branch (by using git directly, virtualenv git magic or using this link:). Preferably run your existing project's tests against the downloaded Django version. You can use DB schemas by either using database alias setting 'SCHEMA': 'my_testing_schema', or by using Model meta attribute db_schema = 'someschema'.
Please, do test this. I will assume there is no interest in this feature if nobody reports any test results.
There is still the question if we want to add the complexity of supporting DB schemas. The complexity comes from three sources:
- Introspection, creation: multischema awareness makes things more complicated here. This will also make life harder for 3rd party apps, South and external database backends come to mind here.
- Different backends have different requirements: PostgreSQL is easy here - it has fully namespaced schemas. Oracle and MySQL do not have these: Django's databases live in the same namespace as schemas. Thus, in testing the schemas must be 'test_' prefixed to avoid collisions. SQLite just uses table name prefixing. As an example of other complexities encountered: Oracle requires creating additional connections to create foreign keys properly. If somebody knows of a way to overcome this, I am all ears.
- Model's name isn't guaranteed to stay the same in testing and in production. This means problems for raw-SQL users (use connection.qname(MyModel) to get a fully qualified name). This also causes some complexities in the patch.
I am going to rebase the branch from time to time. That is, do not base your work on the branch.
comment:115 Changed 5 years ago by
I had some IRC-discussions with Andrew Godwin today. It was agreed that the feature should not aim to support testing on single database instance if the database doesn't support namespaced schemas (only PostgreSQL has them from Django's perspective). This should simplify the implementation somewhat, as there is no need to test-prefix the schema name.
I will try to rewrite the patch without support for test-prefixing the schemas (and also drop support for SQLite's prefix-the-table-name hack totally).
comment:116 Changed 5 years ago by
Catching up now on this ticket, I'll try to do some testing on Oracle soon.
I want to suggest that we also consider foreign-schema creation to be out of scope for databases like Oracle, where schemas and users are the same things. The current code that attempts to do all this through a single configured Oracle connection is a bit naive; it assumes that all users have the same password, and it appears to also assume that the configured Django user has the CREATE ANY TABLE privilege, which would be an unusual production setup.
Instead, a Django user who wants to manage multiple Oracle schemas with Django should set up a separate database connection for each schema. This way we're not trying to create or alter objects belonging to other users. For the REFERENCES issue, there are two cases -- either the referenced schema is not also managed by Django, in which case the user is responsible for ensuring the necessary grants, or both schemas are managed by Django, in which case we might better be able to automate the grant with the using() construct.
comment:117 Changed 5 years ago by
I agree on simplifying the Oracle hacks in the patch. The current patch tries to abstract too much of the differences between the databases away. Lets rip the current patch to absolute minimum, and then continue from there.
The "multiple schemas on Oracle -> multiple defined connections" needs some more thought on how to map the tables to the connections, and how to see that some aliases are just schemas for another alias, so that joins are allowed, and one can save model in schema "other" using the default connection. I hope this can be made to work...
comment:118 Changed 5 years ago by
@akaariai, I have interest in testing your patch with my code. I have a SaaS application and would like each tenant to have a particular schema. To set the schema based on the logged in user, all I have to do is to dynamically set the db.schema setting? Thanks in advance.
comment:119 Changed 5 years ago by
comment:120 Changed 5 years ago by
I guess you will need to do something like this to use custom schema dynamically:
connection.settings_dict = connection.settings_dict.copy() # avoid changing anything global... old_schema = connection.settings_dict['SCHEMA'] connection.settings_dict['SCHEMA'] = wanted_schema
And then of course in "finally:" block reset the 'SCHEMA' back to its original value.
comment:121 Changed 5 years ago by
@akaariai Thanks for the patch! I have a project where I have multiple schemas and some of the tables have foreign keys between them. My environment consists of PostgreSQL and my settings contain multiple entries in
DATABASES
with their own schema defined (as suppose to hard-coded schemas in the model
Meta
classes). I ran the
./manage.py sqlall
command and noticed a couple things:
- there are redundant
CREATE SCHEMA
statements before each
CREATE TABLE
- foreign keys to tables from other schemas do not output the correct schema
comment:122 Changed 5 years ago by
@akaariai just an FYI I forked your repo and am attempting to fix these issues myself. The latter issue I mention above seems to be more deeply rooted in that the
sql*
commands seem to not take in account database routers (since it is not technically a
syncdb
command). This is further confusing since the
sql*
commands take a
--database
parameter. Your concern above regarding third-party apps could be resolved by users defining a router. The
db_for_*
methods are suitable since multiple database entries can be defined for simply defining separate schemas.
I am going to give integrating the database routers a whack.
comment:123 Changed 5 years ago by
I am sure everyone has mused over this many times, but this is a quick outline I came up with, derived from my use case including the primary goals, and a few scenarios/setups with a list of possible solutions (best first).
- Goals
- ability to use a non-default schema given the backend
- transparently route models to their respective schemas given a database
- handle schema creation (?, on the fence about this)
- Scenarios
- single database, one schema
- use the database backend default schema (out-of-box)
- override the
DATABASES['default']['SCHEMA']
- override
DEFAULT_SCHEMAin settings (this is kind of silly to have since it's so simple to define the schema in the database settings above)
- define each model's
db_schemameta option (in my mind, this is only really useful for models that are not intended to be reusable outside a company/guidlines/etc.)
- single database, multiple schemas
- define a router that implements
schema_for_dbwhich returns a valid schema name or
Noneif no preference
- takes a
model,
db, and
**hints
- in case there is some funky setup where a separate set of database settings is not enough, this provides a generic solution which allows re-use of models/app regardless of the database structure, nothing hard-coded on the models themselves
- set each model's
db_schemameta option for ones not in the default schema (garbage)
- multiple databases
- non-issue since schemas do not span across databases
comment:124 Changed 5 years ago by
I have done no work on the manage.py sql* commands at all. I am not surprised they don't work. But, the foreign key issue seems worrisome. Is this from sql* or from the created database? I thought I had nailed the issues with foreign keys but I am not that surprised to find out this isn't true.
There are two ways the schemas can collide: between testing and production databases, and between two different database aliases both using the same schema. So, the "key" for schema must be "in_testing, alias, schema_name".
I am thinking of something like this as the DATABASES format. Assume there are two databases, default and other, and two schemas, schema1 and schema2:
DATABASES = { 'default':{ ... }, 'other': { ... }, 'default:schema1': { # Used in production for default's schema1 schema. }, 'default:schema2': { ... }, 'other:schema1': { ... }, 'other:schema2: { ... }, 'test:default:schema1' { ... }, ... }
Unfortunately this gets large, fast. But, maybe that is how it must be.
For PostgreSQL the schema aliases would not be needed.
The routers approach is interesting because one could do some funny things with it: the typical example is querying a different schema for different clients. Worth investigating more. I know of an immediate use for this, so I am interested...
It is noteworthy that one must be able to do full-db syncs if syncdb support is added. There can be circular cross-schema foreign keys, and these can not be created before both schemas are created. This is impossible to do in single-schema syncs.
comment:125 Changed 5 years ago by
You can take a look at the couple commits () I've added. The latest one makes use of
connection.qname as the primary means of determining the qualified name. This uses a new router method
schema_for_db. I have not updated any tests yet, but for my project locally with multiple schemas all the
sql* commands are working nicely.
comment:126 Changed 5 years ago by
comment:127 Changed 5 years ago by
I didn't have time to go through the changes in full, but on the surface of it they look good.
We will need to find some solution using DATABASES as the definition point for the connections for different schemas on databases where these are needed. I am not at all sure my idea above is the correct approach, it was just one concrete idea of how to define the schemas.
comment:128 Changed 5 years ago by
I agree, the one issue with only using a router is the lack of transparency of which schemas are in use or are available. I had thought about defining multiple database entries for each schema also, but it got a bit unwieldy and it kind of conceptually conflicts with the fact that cross-schema references are possible (at least in postgres).
Thanks for the quick review. I will am going to get the tests up-to-date at the very least and then continue musing over where/how to explicitly define the schemas in the settings.
comment:129 Changed 5 years ago by
Another idea for the DATABASES format:
# for MySQL 'default': { ... 'SCHEMAS': { 'myschema1': {'NAME': 'myschema1'}, 'myschema2': {'NAME': 'myschema2'}, } } # for Oracle 'default': { ... 'SCHEMAS': { 'myschema1': {'USER': 'foo', 'PASSWORD': 'bar'}, 'myschema2': {'USER': 'foo2', 'PASSWORD': 'bar'}, } }
The idea is that one must define just the needed variables for each schema. On Postgres you don't need any additional info -> no need to define schemas. On Oracle, you need user and password, and on MySQL you need at least the database name (and possibly user and password).
One could define similarly TESTING_SCHEMAS.
There is still room for improvement: by default the NAME on MySQL should be the same as the schema's name, and the USER on Oracle likewise. The password on Oracle could be the same as the normal user's password. Thus often one could get away with just defining the TESTING_SCHEMAS. One would need to define the full SCHEMAS only when there are collisions, or some other need to use non-default values - and it is easy enough to spot the collisions, at least in testing.
The above SCHEMAS would be turned to full database aliases when needed (that is, in syncdb situations). They should never be visible to users.
The backend.convert_schema() would work something like this:
def convert_schema(self, schemaname): return self.settings_dict['SCHEMAS']['USER'] # for Oracle
In testing one would overwrite
settings_dict['SCHEMAS'] with
settings_dict['TEST_SCHEMAS'].
comment:130 Changed 5 years ago by
comment:131 Changed 5 years ago by
Here is the latest patch with all the tests up-to-date and rebased with Django HEAD: I have not implemented any of the
SCHEMAS settings above.
comment:132 Changed 5 years ago by
comment:133 Changed 5 years ago by
One remaining issue with how this is implemented is that qualified names that are sometimes referenced prior to a database being selected or a connection is available. All the qualified names being accessed from
model._meta may not actually be fully-qualified since a database has not been selected and thus no schema (this of course assumes the
db_schema options attribute has not been defined).
One possible solution is using the
db_for_read or
db_for_writerouter methods to determine with database within db/models/sql/query.py depending on the compiler being used, but that feels somewhat hideous. I thought a more appropriate place would have been db/models/sql/compiler.py, but that is too late since the qualified names are already referenced (no longer have the model to pass into the router).
Another solution (which seems to be more flexible) would be to store a reference of the model in the
QName object. That way depending on the context of
QName's use, the model will be available. To not break existing code,
QName may need to be a class that behaves like a namedtuple, but has the model as an extra attribute to be used if needed. I will give this a go.
comment:134 Changed 5 years ago by
comment:135 Changed 5 years ago by
I won't likely make it to DjangoCon. But, I will try to keep track of work done in this ticket.
As for now, I think the most important thing is to get the way databases are set up (both the settings side, and how production/test databases are handled) correct.
I am not 100% sure if I understand the routers idea... Still, having the model's opts at hand in the compiler would be nice, there are other uses for that, too.
comment:136 Changed 5 years ago by
comment:137 Changed 5 years ago by
I think the correct way to define the schemas is to have two new database settings, SCHEMA_MAP and TEST_SCHEMA_MAP. The first one is required only Oracle, and it will contain the needed user information for production. You might also need this on MySQL if you have more than one alias on the same DB instance for some reason. The second one is required for Oracle and MySQL, and it contains the information about which schema to use in testing.
So, assuming that you have schemas 'schema1' and 'schema2', then the settings would look like:
DATABASES = { 'default': { 'engine': 'MySQL', ..., 'TEST_SCHEMA_MAP': {'schema1': 'test_default_schema1', 'schema2': 'test_default_schema2'} }, 'other': { 'engine': 'Oracle', ..., 'SCHEMA_MAP': {'schema1': {'user': 'schema1', 'password': 'top_secret'}, 'schema2': {'user': 'schema2', 'password': 'top_secret'}}, 'TEST_SCHEMA_MAP': {'schema1': {'user': 'test_schema1', 'password': 'top_secret'},...} # Or, to mirror the production schemas, just do: 'TEST_SCHEMA_MAP': 'SCHEMA_MAP', } }
How the contents of SCHEMA_MAP and TEST_SCHEMA_MAP are interpreted is DB specific.
comment:138 Changed 5 years ago by
I like
SCHEMAS and
TEST_SCHEMAS better for names, but this configuration looks good. To answer your question from your previous comment, the new router method
schema_for_db is simply to support routing operations to a particular schema (just like you can route operations to a database). For example all the
auth_* and
registration_* models may get routed to the
auth schema, while social media related items might get routed to the
social schema. More interesting scenarios are dealing with multi-tenant databases where each tenant has it's own schema rather than having to manage potentially hundreds or thousands of databases. Or if you are sharding your data to various logical shards across different databases you can route your data based on some modulus.
I am still a bit hesitant with being able to define
db_schema on the
Model.Meta class. I think it will be important to note in the docs that released apps should not define
db_schema on any of the models to ensure it is not imposing any database constraints on the developer.
comment:139 follow-up: 143 Changed 5 years ago by
I just noticed your comment
# Or, to mirror the production schemas, just do:.. that should be the default, so it does not need to be defined explicitly.
comment:140 follow-up: 141 Changed 5 years ago by
The tenant use-case is the one I am most interested in. And, for that reason I do think routers could be pretty good. To support that we should be able to sync the same model to multiple schemas. Actually, somehow we should be able to route a system of models to single schema (that is, you have foreign keys inside each schema created correctly).
It should be exceptionally clear in the docs that one should not confuse routing to different schemas with routing to different databases. The schemas are under control of one db instance, and you can have foreign keys across schemas, and you can use multiple schemas in a single query. This is not at all true when using different database aliases.
Maybe we could aim to have the routers implemented, but assume a single model is installed in only one schema. If a user wants to have it in multiple schemas, we do not try to support this at start. I believe having full support for same model in multiple schemas will be hard to implement.
comment:141 Changed 5 years ago by
Problem appears when you add 'south' to installed apps.
Patched Django 1.4.1
Unfortunately I cannot add traceback because TRAC treats me as spammer
comment:142 Changed 5 years ago by
comment:143 Changed 5 years ago by
I just noticed your comment
# Or, to mirror the production schemas, just do:.. that should be the default, so it does not need to be defined explicitly.
I'm going to disagree and advocate that this option not even be explicitly supported. It's bad enough already that the Oracle backend runs tests on the production-configured database (just in a different tablespace and schema). If you don't use a separate settings.py file with separate connection information for testing, and you mirror the production schemas, then your tests are actually going to run in your production schemas.
The other thing I want to comment on is that SCHEMA_MAP should be completely optional, unless you're running syncdb and have managed tables in those schemas. For day-to-day operation, Django should only be connecting as the Django user and does not need full authentication information for other schemas.
comment:144 Changed 5 years ago by
comment:145 Changed 5 years ago by
comment:146 Changed 5 years ago by
This is clearly accepted, the DDN was about how to implement this feature.
comment:147 Changed 5 years ago by
comment:148 Changed 4 years ago by
comment:149 Changed 4 years ago by
comment:150 Changed 4 years ago by
comment:151 Changed 4 years ago by
I think I now know how to implement the multitenant use case.
Lets introduce a TableRef class. By default it would look something like this:
class TableRef(object): def __init__(self, schema, table, alias): self.schema, self.table, self.alias = schema, table, alias def as_sql(self, qn, connection): schema_ref = (qn(self.schema) + '.') if self.schema else '' table_ref = '%s%s' % (schema_ref, qn(self.table)) if self.alias: return '%s %s' % (table_ref, self.alias) else: return table_ref
If you just set db_table and schema in model.Meta, then you get the above class instantiated and used in queries. But, you can also do:
class DynamicSchemaTableRef(TableRef): @property def schema(self): # Return schema dynamically, based on thread-locals or a router # or whatever you want. The schema would be effective both in # queries and in migrations. So, you could install the same models # to different schemas by using migrations. class SomeModel(models.Model): ... class Meta: db_table = DynamicSchemaTableRef("$placeholder$", 'some_model', None)
Now, when you use SomeModel then references are autogenerated to point to correct schema by DynamicSchemaTableRef.
There are a couple of other use cases. For example:
class SubqueryRef(object): def __init__(self, query, alias): self.schema = None self.query = query self.alias = alias def as_sql(self, qn, connection): return '(%s) %s' % (self.query, self.alias)
Now, add a model:
class MyViewModel(models.Model) col1 = models.IntegerField() col2 = models.CharField() class Meta: managed = False table = SubqueryRef("select t1.somecol as col1, t2.othercol as col2 " " from base_table1 t1 inner join base_table2 t2 on t1.id = t2.t1_id " " where some_conditions", "myviewmodel")
Now, MyViewModel.objects.all() will generate query:
select myviewmodel.col1, myviewmodel.col2 from (select t1.somecol as col1, t2.othercol as col2 from base_table1 t1 inner join base_table2 t2 on t1.id = t2.t1_id where some_conditions) myviewmodel
This allows one to do "views" in Django.
Similarly you could make AuditTableRef that can be used to query arbitrary points in time from audit table and so on. Django doesn't need to encourage these usage patterns, but they are available if you want to.
Two main problems with this approach:
- Somewhat extensive changes needed to sql.*, introspection and migrations. But, for schema support extensive changes are needed anyways.
- There could be some performance problems as this proposal adds again more class instances to simple queries (custom lookups already did that, lets see if anybody complains). Still, I think the problem should be manageable. We could also cache SQL in the table references, so that when no aliasing is needed (the common case) we get SQL generated in a very fast way.
comment:152 Changed 3 years ago by
comment:153 Changed 3 years ago by
comment:154 Changed 3 years ago by
comment:155 follow-ups: 156 159 Changed 3 years ago by
I had an idea about this some time ago. Instead of building support for
class MyModel: ... class Meta: db_schema = 'foobar' db_table = 'sometable'
we should implement something like this
class MyModel: ... class Meta: db_table = SchemaQualifiedTable('sometable', schema='foobar')
The idea is that the model's db_table is actually a class that knows how to produce SQL for itself. This could be used for schema qualified tables, and also for producing SQL view like behavior. That is, you could push in a custom View("select * from foobar") object. Then for QuerySet
MyModel.objects.all()
django would produce SQL
SELECT * FROM (select * from foobar) T1
the SQL inside the parentheses is produced by the View() class.
Even if users can access schema qualified tables by implementing a SchemaQualifiedTable class, we still need a bit more knowledge of the schema inside Django. The SchemaQualifiedTable class would work for existing databases, but the schema attribute of the table class must be supported by Django in some places (for example introspecting if the table already exists, and also automatic creation of the schema in migrations)..
comment:156 follow-up: 157 Changed 3 years ago by
I had an idea about this some time ago. Instead of building support for [...]
This is intriguing but makes sense... Would you by chance have already drafted some code for this idea?
Also, what do you think of the approach in:
Cordially
--
Philippe
comment:157 Changed 3 years ago by
Replying to pombredanne:
Also, what do you think of the approach in:
Setting search path in PostgreSQL is a very common technique in case of multi-tenant applications, a lot of Rails people do it also, but that wouldn't work either in SQLite, nor in MySQL which Django have to support. Also, that project is not capable of handling cross-schema references, which is the most important feature of a true multi-tenant application IMO.
comment:158 Changed 3 years ago by
FWIW, I compiled a list of various implementations of multitenancy in Django, several of which are schema-based:
comment:159 Changed 3 years ago by.
Multi-schema migrations are indeed a hard problem to solve. I think I have a fairly workable solution in place now (Postgres only), at
My approach is a multi-tenancy approach (with some shared tables: usually the user table, the tenant table, and perhaps others), and requires that for all non-shared models, every migration operation that appears to be running on one of those models should be applied to each tenant schema in turn.
In practice, this makes migrations quite slow, even for small numbers of schemata. However, it does allow cross schema relations.
It uses setting the search path rather than explicitly including the schema name in the model.
comment:160 Changed 3 years ago by
comment:161 Changed 3 years ago by
comment:162 Changed 2 years ago by
comment:163 Changed 2 years ago by
comment:164 Changed 2 years ago by
comment:165 Changed 2 years ago by
If we ever want to proceed on this ticket, I think we need to split this to two parts:
- Make core ORM usable with multi-schema setups
- Allow migrations for multi-schema setups
I claim that the first item is easier than one would first imagine, and the correct approach is to make Meta.db_table values respect an interface. The interface has as_sql(compiler, connection). The return value will be the usual 2-tuple containing sql, params. The SQL is either table reference ("a_table"), schema qualified reference ("some_schema"."a_table") or a subquery ("(select * from foobar)"). The possibility to use subqueries will make it much easier to create view-like functionality to Django ORM. The interface also needs an "always_alias" flag, so that Django knows to always generate aliases for schema qualified tables and subqueries.
We can't add a SchemaQualifiedTable class to Django before we have some migrations support (but we can add the above mentioned interface). Support for migrations will be harder to tackle. (How exactly do you create schemas with different databases backends? What about SQLite that doesn't even have schemas?) But just having the ability to use hand-created tables or existing tables in schema-qualified form will be extremely useful. The subqueries will also be a powerful new feature.
I guess we can approach this with a semi-private-api approach. Allow for as_sql() for db_table, and make basic things work (basic queries, update, insert, delete), and then proceed from there. It is possible (but not certain at all) that this doesn't need changes to other places than join generation and the Join + BaseTable classes.
comment:166 Changed 2 years ago by
FWIW: If
db_table and
db_column become a little more complex than simple strings, we could begin to tackle the case-insanity problems of Oracle. While this is not directly related to this ticket, it's another reason to support this approach.
comment:167 Changed 2 years ago by
I've implemented a proof-of-concept approach for the Meta.db_table API. PR shows that one can do some fancy things with this. In fact, multi-schema setups should be supported by the ORM by just those changes. Unfortunately multi-schema migrations are a much harder problem to tackle.
comment:168 Changed 2 years ago by
Updating the ticket flags to put Anssi's pull request in the previous comment in the review queue.
comment:169 Changed 22 months ago by
comment:170 Changed 22 months ago by
comment:171 Changed 21 months ago by
comment:172 Changed 20 months ago by
The pull request for this is still missing a couple of day's worth of work, but all the hard parts seem to be solved.
For initial implementation I am going to skip dynamic schemas and other useful features which aren't essential for minimal implementation.
comment:173 Changed 14 months ago by
Management schemas in the databases could be done using a variable for the name of the schema as currently used for the name of the table (db_table).
In Postgres do not see it so complicated. In Oracle, schemas are associated with users, making it more complicated creation.
Django can assume that schemes should be previously created in the database for that migration is as transparent as possible.
With respect to other databases, no schemas be handled.
comment:174 Changed 7 months ago by
+1 for Postgres only support for now (Oracle can be TBD in a new ticket). Postgres is an open source and freely available database that has other extensions supported in contrib. In built Schema support for postgres will allow for much for flexible and powerful SAAS setups
comment:175 Changed 7 months ago by
IMO the reality is that very few people will have schema creation permissions in Oracle, and if you do, you generally do not want to use that account to install a Django site with migrations. I think assuming that the schema exists works fine for Oracle, given that the schema and test-schema may be set in config (I think part of this functionality already exists). If not, the resulting error is easy to catch.
patch to add support for db_schema in model.meta for mysql at least
|
https://code.djangoproject.com/ticket/6148?cversion=0&cnum_hist=75
|
CC-MAIN-2017-43
|
refinedweb
| 11,779
| 62.48
|
Should you learn more than one language at the same time?
Marco Suárez on November 06, 2017
After a period of inactive code learning or practicing, I achieved to spare some time of my day to get back on track. The thing is that I've al... [Read Full]
I wouldn't recommend learning multiple languages at the same time. Part of getting to know a language is to familiarize yourself with it's syntax and paradigm of thinking. For example, JS or NodeJS is extremely functional while Python or Java aren't. I think it's better to get to know the ecosystem of a language, what functionalities are provided in the core library, which are the popular libraries/frameworks used by other people in the community before moving on to other languages.
I think I would get very muddled in my head if I learnt multiple languages together. Recently, I was getting back on the Python & NodeJS horse at very close intervals. Half the time, I was writing JS code in the Python script and kept getting frustrated when it wouldn't run. I was also googling up some very basic stuff like "How to define functions in Python" because I kept writing
function foo()instead of
def foo():.
Personally I've tried it and it hasn't been productive.
What I have been productive in doing is learning one new language at a time and doing a compare/contrast. For example, my main language is Java, so when it came time to learn Python I went back to projects I've completed in Java and did them again in Python. After some time I wasn't sure how much I was feeling Python, so I hopped on over to C# and did the same thing. Now I'm back on Python, lol. BUT there wasn't a time where I was doing both Python and C# - it was one or the other.
That's my two cents.
When you learn a language, make sure you're learning it to do something -- even if it's just to make a task list. If you pick a "something" that should be done with more than one language naturally (for example, building a website using C# and JavaScript), then it only makes sense to learn more than one language simultaneously. So, yes it's very possible for that to be a good idea, just not the way you're describing it.
Of course you can learn more than one language at a time. You learned more than one subject at a time in school, didn't you?
The important thing is using each language to do something that YOU are intensely interested in, every single day.
For the most part, you should pick one language to learn the fundamentals of programming (ie: loops, if conditionals, objects, classes, etc). Once you understand those concepts, I would say it's fine to explore to your hearts content. The only real change is syntax between languages.
Personally, I would recommend JavaScript since you can do front and back-end development. Once you have those concepts in place, you can jump to something that might be interesting to you like Ruby on Rails, PHP, Python or a specific JS front-end like React, Vue or Angular.
As other people said here, I think learning multiple things at the same time is not a good idea, multitasking is generally not a good way.
I used to learn multiple languages at the same time and the only time it wasn't a bad idea is when I decide to learn the functional paradigm through a language : first a learned multiple language ( Scala, Java 8 Streams, Kotlin ) then I selected one and " forget " the others. That's allow me to select the language I preferred the most and made my learning session less painful.
Hey Marco,
Good question!
I'm the kind of guy who plays all the available characters in a video game and never gets to be a "pro" at any of them. Sure, I might not be super special, but the general knowledge I get from trying all of them helps me in the long run. But this may or may not apply for programming languages, I guess it might depend on the person itself.
Based on my experience, I would recommend finding some documentation, videos or courses about ONE language and don't look back. I love the way Mosh Hamedani teaches in his Udemy courses and that motivated me to finish all the 3 C# courses (beginner, intermediate and advanced) and I don't think I'll ever have a way to repay him how much I learned from him.
Now that I have a higher level of understanding of how things work in C# I can apply them to my day to day work, in which I mainly use Java, because even tho it may not have all the features C# does, I can almost always find the "Java-Way" of doing the same thing, which most importantly improves your research abilities a lot.
You reminded me of an essay I wrote that talked about how knowing other languages (idioms) makes the subsequent easier to learn. Us humans can only learn by comparing the new stuff with the one we already know.
I wouldn't recommend it for (even remotely) similar languages. But for totally dissimilar languages this should be fine. For example I'm currently learning both golang and erlang, and it's as efficient as learning them one at a time. But I wouldn't learn e.g. C and golang at the same time, or even python and golang at the same time.
Also, I wouldn't recommend learning more than one language at a time until you know well at least two - three dissimilar languages (i.e. at least two different paradigms, e.g. structural and OOP)
I wouldn't recommend it. But if you are left with no choice then try to read the concepts behind it rather than the syntax i.e such as HashMap, LinkedList, Classes/Interfaces and so on and then lookup the syntax whenever required.
It depends on your level of experience I think. If you are new to programming you'd probably wish to stick with one language and learn it well before moving on to another one. Otherwise you might get basic concepts confused.
Afterwards though I see no problem in using multiple languages at the same time. Most large projects will tend to include bits in various languages so you can't really avoid it anyway.
I also don't draw much of a distinction between using and learning a language. Beyond the basic syntax, and some speical constructus, you'll need to continually learn the API and best practices of whatever language you are using.
The more often you encounter a language that more you should follow-up on the syntax and look for language-speicfic approaches to solve your problems. It'd be bad to try and force the same syntax, or approach, into all the languages you use.
Well, it depend on you, and more likely on your stage.
When I was learning to code, it would have been disastrous to try to take on more than one language. Is not just because learning a new language can be hard, but because in these stages I was also learning patterns, structures models. I'd even had headaches trying to differentiate javascript from jQuery.
After few years in different positions and technologies, I hasn't been uncommon taking projects with a completely new stack (for me) of technologies and/or IDEs, and tough it always supposed a couple weeks of adaptation, I went trough it more or less transparently.
You might get confused learning multiple programming languages at once. It's best to fully focus on one language at a time. That's just my personal opinion though.
|
https://dev.to/marksasp95/should-you-learn-more-than-one-language-at-the-same-time-9jk/comments
|
CC-MAIN-2019-18
|
refinedweb
| 1,331
| 69.31
|
Image by Damien Roué | Some Rights Reserved
When working with ASP.NET Web Api from a .NET client, one of the more confounding things can be handling the case where errors are returned from the Api. Specifically, unwrapping the various types of errors which may be returned from a specific API action method, and translating the error content into meaningful information for use be the client.
How we handle the various types of errors that may be returned to our Api client applications can be very dependent upon specific application needs, and indeed, the type of client we are building.
In this post we’ll look at some general types of issues we might run into when handing error results client-side, and hopefully find some insight we can apply to specific cases as they arise.
- Create a New ASP.NET Web Api Project in Visual Studio
- The Register Method from the Account Controller
- Making a Flawed Request – Validation Errors
- Unwrapping and Handling Errors and Exceptions in Web Api
- ApiException – a Custom Exception for Api Errors
- Unwrapping Error Responses and Model State Dictionaries
- Error and Exception Handling in the Example Application
- Running Through More Error Scenarios with Error and Exception Handling
- Oh No You did NOT Use Exceptions to Deal with Api Errors!!
- Additional Resources and Items of Interest
Understanding HTTP Response Creation in the ApiController
Most Web Api Action methods will return one of the following:
- Void: If the action method returns void, the HTTP Response created by ASP.NET Web Api will have a 204 status code, meaning “no content.”
- HttpResponseMessage: If the Action method returns an
HttpResponseMessage, then the value will be converted directly into an HTTP response message. We can use the
Request.CreateResponse()method to create instances of
HttpResponseMessage, and we can optionally pass domain models as a method argument, which will then be serialized as part of the resulting HTTP response message.
- IHttpActionResult: Introduced with ASP.NET Web API 2.0, the
IHttpActionResultinterface provides a handy abstraction over the mechanics of creating an
HttpResponseMessage. Also, there are a host of pre-defined implementations for
IHttpActionResultdefined in System.Web.Http.Results, and the
ApiControllerclass provides helper methods which return various forms of
IHttpActionResult, usable directly within the controller.
- Other Type: Any other return type will need to be serialized using an appropriate media formatter.
For more details on the above, see Action Results in Web API 2 by Mike Wasson.
From Web Api 2.0 onward, the recommended return type for most Web Api Action methods is IHttpActionResult unless this type simply doesn’t make sense.
Create a New ASP.NET Web Api Project in Visual Studio
To keep things general and basic, let’s start by spinning up a standard ASP.NET Web Api project using the default Visual Studio Template. If you are new to Web Api, take a moment to review the basics, and get familiar with the project structure and where things live.
Make sure to update the Nuget packages after you create the project.
Create a Basic Console Client Application
Next, let’s put together a very rudimentary client application. Open another instance of Visual Studio, and create a new Console application. Then, use the Nuget package manager to install the ASP.NET Web Api Client Libraries into the solution.
We’re going to use the simple
Register() method as our starting point to see how we might need to unwrap some errors in order to create a more useful error handling model on the client side.
The Register Method from the Account Controller
If we return to our Web Api project and examine the
Register() method, we see the following:
The Register() method from AccountController:
[AllowAnonymous] [Route("Register")] public async Task<IHttpActionResult> Register(RegisterBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user, model.Password); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); }
In the above, we can see that there are a number of options for what might be returned as our
IHttpActionResult.
First, if the Model state is invalid, the
BadRequest() helper method defined as part of the
ApiController class will be called, and will be passed the current
ModelStateDictionary. This represents simple validation, and no additional processes or database requests have been called.
If the Mode State is valid, the
CreateAsync() method of the
UserManager is called, returning an
IdentityResult. If the Succeeded property is not true, then
GetErrorResult() is called, and passed the result of the call to
CreateAsync().
GetErrorResult() is a handy helper method which returns the appropriate
IHttpActionResult for a given error condition.
The GetErrorResult Method from AccountController; }
From the above, we can see we might get back a number of different responses, each with a slightly different content, which should assist the client in determining what went wrong.
Making a Flawed Request – Validation Errors
So, let’s see some of the ways things can go wrong when making a simple POST request to the Register() method from our Console client application.
Add the following code to the console application. Note that we are intentionally making a flawed request. We will pass a valid password and a matching confirmation password, but we will pass an invalid email address. We know that Web Api will not like this, and should kick back a Model State Error as a result.
Flawed Request Code for the Console Client Application: { Console.WriteLine(result.ReasonPhrase); } Console.Read(); }; return response; } }
If we run our Web Api application, wait for it to spin up, and then run our console app, we see the following output:
Console output from the flawed request:
Bad Request
Well, that’s not very helpful.
If we de-serialize the response content to a string, we see there is more information to be had. Update the
Main() method as follows:
De-serialize the Response Content: { string content = result.Content.ReadAsStringAsync().Result; Console.WriteLine(content); } Console.Read(); }
Now, if we run the Console application again, we see the following output:
Output from the Console Application with De-Serialized Response Content:
{"Message":"The request is invalid.","ModelState":{"":["Email 'john' is invalid."]}}
Now, what we see above is JSON. Clearly the JSON object contains a
Message property and a
ModelState property. But the
ModelState property, itself another JSON object, contains an unnamed property, an array containing the error which occurred when validating the model.
Since a JSON object is essentially nothing but a set of key/value pairs, we would normally expect to be able to unroll a JSON object into a
Dictionary<string, object>. However, the nameless property(ies) enumerated in the ModelState dictionary on the server side makes this challenging.
Unwrapping such an object using the Newtonsoft.Json library is doable, but slightly painful. Equally important, an error returned from our API may, or may not have a ModelState dictionary associated with it.
Another Flawed Request – More Validation Errors
Say we figured out that we need to provide a valid email address when we submit our request to the
Register() method. Suppose instead, we are not paying attention and instead enter two slightly different passwords, and also forget that passwords have a minimum length.
Modify the code in the
Main() method again as follows:
Flawed Request with Password Mismatch:
{ "Message":"The request is invalid.", "ModelState": { "model.Password": [ "The Password must be at least 6 characters long."], "model.ConfirmPassword": [ "The password and confirmation password do not match."] } }
In this case, it appears the items in the ModelState Dictionary are represented by valid key/value pairs, and the value for each key is an array.
Server Errors and Exceptions
We’ve seen a few examples of what can happen when the model we are passing with our POST request is invalid. But what happens if our Api is unavailable?
Let’s pretend we finally managed to get our email and our passwords correct, but now the server is off-line.
Stop the Web Api application, and then re-run the Console application. Of course, after a reasonable server time-out, our client application throws an
AggregateException.
What’s an
AggregateException? Well, it is what we get when an exception occurs during execution of an
async method. If we pretend we don’t know WHY our request failed, we would need to dig down into the
InnerExceptions property of the
AggregateException to find some useful information.
In the context of our rudimentary Console application, we will implement some top-level exception handling so that our Console can report the results of any exceptions like this to us.
Update the
Main() method once again, as follows:
Add Exception Handling to the Main() Method of the Console Application:
static void Main(string[] args) { // This is not a valid email address, so the POST should fail: string email = "john@example.com"; string password = "Password@123"; string confirmPassword = "Password@123"; // Add a Try/Catch); } } Console.Read(); }
If we run our console app now, while our Web Api application is offline, we get the following result:
Console Output with Exception Handling and Server Time-Out:
One or more exceptions has occurred: An error occurred while sending the request.
Here, we are informed that “An error occurred while sending the request” which at least tells us something, and averts the application crashing due to an unhandled
AggregateException.
Unwrapping and Handling Errors and Exceptions in Web Api
We’ve seen a few different varieties of errors and exceptions which may arise when registering a user from our client application.
While outputting JSON from the response content is somewhat helpful, I doubt it’s what we are looking for as Console output. What we need is a way to unwrap the various types of response content, and display useful console messages in a clean, concise format that is useful to the user.
While I was putting together a more in-depth, interactive console project for a future article, I implemented a custom exception, and a special method to handle these cases.
ApiException – a Custom Exception for Api Errors
Yeah, yeah, I know. Some of the cases above don’t technically represent “Exceptions” by the hallowed definition of the term. In the case of a simple console application, however, a simple, exception-based system makes sense. Further, unwrapping all of our Api errors up behind a single abstraction makes it easy to demonstrate how to unwrap them.
Mileage may vary according to the specific needs of YOUR application. Obviously, GUI-based applications may extend or expand upon this approach, relying less on Try/Catch and throwing exceptions, and more upon the specifics of the GUI elements available.
Add a class named
ApiException to the Console project, and add the following code:
ApiException – a Custom Exception
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; namespace ApiWithErrorsTest { public class ApiException : Exception { public HttpResponseMessage Response { get; set; } public ApiException(HttpResponseMessage response) { this.Response = response; } public HttpStatusCode StatusCode { get { return this.Response.StatusCode; } } public IEnumerable<string> Errors { get { return this.Data.Values.Cast<string>().ToList(); } } } }
Unwrapping Error Responses and Model State Dictionaries
Next, let’s add a method to our Program which accepts an
HttpResponseMessage as a method argument, and returns an instance of
ApiException. Add the following code the the
Program class of the Console application:
Add the CreateApiException Method the to Program Class:
public static ApiException CreateApiException(HttpResponseMessage response) { var httpErrorObject = response.Content.ReadAsStringAsync().Result; // Create an anonymous object to use as the template for deserialization: var anonymousErrorObject = new { message = "", ModelState = new Dictionary<string, string[]>() }; // Deserialize: var deserializedErrorObject = JsonConvert.DeserializeAnonymousType(httpErrorObject, anonymousErrorObject); // Now wrap into an exception which best fullfills the needs of your application: var ex = new ApiException(response); // Sometimes, there may be Model Errors: if (deserializedErrorObject.ModelState != null) { var errors = deserializedErrorObject.ModelState .Select(kvp => string.Join(". ", kvp.Value)); for (int i = 0; i < errors.Count(); i++) { // Wrap the errors up into the base Exception.Data Dictionary: ex.Data.Add(i, errors.ElementAt(i)); } } // Othertimes, there may not be Model Errors: else { var error = JsonConvert.DeserializeObject<Dictionary<string, string>>(httpErrorObject); foreach (var kvp in error) { // Wrap the errors up into the base Exception.Data Dictionary: ex.Data.Add(kvp.Key, kvp.Value); } } return ex; }
In the above, we get a sense for what goes into unwrapping an
HttpResponseMessage which contains a mode state dictionary.
When the response content includes a property named
ModeState, we unwind the
ModelState dictionary using the magic of LINQ. We knit the string key together with the contents of the value array for each item present, and then add each item to the exception Data dictionary using an integer index for the key.
If no
ModelState property is present in the response content, we simply unwrap the other errors present, and add them to the Data dictionary of the exception.
Error and Exception Handling in the Example Application
We’ve already added some minimal exception handling at the top level of our application. Namely, we have caught and handled
AggregateExceptions which may be thrown by async calls to our api, which are not handled deeper in the call stack.
Now that we have added a custom exception, and a method for unwinding certain types error responses, let’s add some additional exception handling, and see if we can do a little better, farther down.
Update the
Register() method as follows:
Add Handle Errors in the Register() Method:; if(!response.IsSuccessStatusCode) { // Unwrap the response and throw as an Api Exception: var ex = CreateApiException(response); throw ex; } return response; } }
You can see here, we are examining the
HttpStatusCode associated with the response, and if it is anything other than successful, we call our
CreateApiException() method, grab the new
ApiException, and then throw.
In reality, for this simple console example we likely could have gotten by with creating a plain old
System.Exception instead of a custom Exception implementation. However, for anything other than the simplest of cases, the
ApiException will contain useful additional information.
Also, the fact that it is a custom exception allows us to catch
ApiException and handle it specifically, as we will probably want our application to behave differently in response to an error condition in an Api response than we would other exceptions.
Now, all we need to do (for our super-simple example client, anyway) is handle
ApiException specifically in our
Main() method.
Catch ApiException in Main() Method
Now we want to be able to catch any flying ApiExceptions in
Main(). Our Console application, shining example of architecture and complex design requirements that it is, pretty much only needs a single point of error handling to properly unwrap exceptions and write them out as console text!
Add the following code to
Main() :
Handle ApiException in the Main() Method:
static void Main(string[] args) { // This is not a valid email address, so the POST should fail: string email = "john@example.com"; string password = "Password@123"; string confirmPassword = "Password@123"; // Add a Try/Cathc); } } catch(ApiException apiEx) { var sb = new StringBuilder(); sb.AppendLine(" An Error Occurred:"); sb.AppendLine(string.Format(" Status Code: {0}", apiEx.StatusCode.ToString())); sb.AppendLine(" Errors:"); foreach (var error in apiEx.Errors) { sb.AppendLine(" " + error); } // Write the error info to the console: Console.WriteLine(sb.ToString()); } Console.Read(); }
All we are doing in the above is unwinding the
ApiException and transforming the contents for the Data dictionary into console output (with some pretty hackey indentation).
Now let’s see how it all works.
Running Through More Error Scenarios with Error and Exception Handling
Stepping all the way back to the beginning, lets see what happens now if we try to register a user with an invalid email address.
Change our registration values in
Main() back to the following:
// This is not a valid email address, so the POST should fail: string email = "john"; string password = "Password@123"; string confirmPassword = "Password@123";
Run the Web Api application once more. Once it has properly started, run the Console application with the modified registration values. The output to the console should look like this:
Register a User with Invalid Email Address:
An Error Occurred: Status Code: BadRequest Errors: Email 'john' is invalid.
Similarly, if we use a valid email address, but password values which are both too short, and also do not match, we get the following output:
Register a User with Invalid Password:
An Error Occurred: Status Code: BadRequest Errors: The Password must be at least 6 characters long. The password and confirmation password do not match.
Finally, let’s see what happens if we attempt to register the same user more than once.
Change the registration values to the following:
Using Valid Registration Values:
string email = "john@example.com"; string password = "Password@123"; string confirmPassword = "Password@123";
Now, run the console application twice in a row. The first time, the console output should be:
Console Output from Successful User Registration:
The new user john@example.com has been successfully added.
The next time, however, an error result is returned from our Web Api:
Console Output from Duplicate User Registration:
An Error Occurred: Status Code: BadRequest Errors: Name john@example.com is already taken.. Email 'simon@example.com' is already taken.
Oh No You did NOT Use Exceptions to Deal with Api Errors!!
Oh, yes I did . . . at least, in this case. This is a simple, console-based application in which nearly every result needs to end up as text output. Also, I’m just a rebel like that, I guess. Sometimes.
The important thing to realize is how to get the information we need out of the JSON which makes up the response content, and that is not as straightforward as it may seem in this case. How different errors are dealt with will, as always, need to be addressed within terms best suited for your application.
In a good many cases, treating Api errors as exceptions, to me, has merit. Doing so most likely will rub some architecture purists the wrong way (many of the errors incoming in response content don’t really meet the textbook definition of “exception“). That said, for less complex .NET-based Api Client applications, unwrapping the errors from the response content, and throwing as exceptions to be caught by an appropriate handler can save on a lot of duplicate code, and provides a known mechanism for handling problems.
In other cases, or for your own purposes, you may choose to re-work the code above to pull out what you need from the incoming error response, but otherwise deal with the errors without using exceptions.
Register() (and whatever other methods you use to call into your Api) might, in the case of a simple console application, return strings, ready for output. In this case, you could side-step the exception issue.
Needless to say, a good bit of the time, you will likely by calling into your Web Api application not from a desktop .NET application, but instead from a web client, probably using Ajax or something.
That’s a Long and Crazy Post about Dealing with Errors – Wtf?
Well, I am building out a more complex, interactive console-based application in order to demo some concepts in upcoming posts. One of the more irritating aspects of that process was figuring out a reasonable way to deal with the various issues that may arise, when all one has to work with is a command line interface to report output to the user.
This was part of that solution (ok, in the application I’m building, things are a little more complex, a little more organized, and there’s more to it. But here we saw some of the basics).
But . . . Can’t We Just do it Differently on the Server?
Well . . . YES!
In all likelihood, you just might tune up how and what you are pushing out to the client, depending upon the nature of your Web Api and the expected client use case. In this post, I went with the basic, default set-up (and really, we only looked at one method). But, depending upon how your Api will be used, you might very will handle errors and exceptions differently on the server side, which may impact how you handle things on the client side.
Additional Resources and Items of Interest
- Action Results in Web API 2 by Mike Wasson
- Exception Handling in ASP.NET Web API by Mike Wasson
- ASP.NET Identity 2.0: Introduction to Working with Identity 2.0 and Web API 2.2
- C#: Building a Useful, Extensible .NET Console Application Template for Development and Testing
- I am a Programmer, and I can Complicate the #@$% out of a Ball Bearing
- ASP.NET Identity 2.0: Implementing Group-Based Permissions Management
John on GoogleCodeProject
|
http://johnatten.com/2014/09/28/asp-net-web-api-unwrapping-http-error-results-and-model-state-dictionaries-client-side/
|
CC-MAIN-2020-34
|
refinedweb
| 3,453
| 53.21
|
Closed Bug 1335262 Opened 3 years ago Closed 3 years ago
Add max-message-size support for data-channels
Categories
(Core :: WebRTC: Signaling, defect, P2)
Tracking
()
mozilla55
Blocking Flags:
People
(Reporter: drno, Assigned: drno)
References
Details
Attachments
(1 file)
Bug 1160558 added support for sctp-sdp-21 and adds support for parsing the new SDP attribute 'a=max-message-size'. But the value is not taken from the SDP and handed to the SCTP stack. And we are also not emitting max-message-size (since it's optional).
backlog: --- → webrtc/webaudio+
Rank: 25
Assignee: nobody → drno
For the record the plan here is to start emitting a=max-message-size even though we are still offering the old style data channel format. And then we use absence of the max-message-size and if streams is 256 (assuming Chrome always used 1024 like Chrome 58 does today) that we are connected to an old Firefox version which does not support EOR (see bug 979417). Note: this logic is not part of this patch here (so far). I checked that with the presence of a=max-message-size we can still establish data channels with Chrome.
Comment on attachment 8873313 [details] Bug 1335262: read and emit datachannel max-message-size. ::: netwerk/sctp/datachannel/DataChannelProtocol.h:21 (Diff revision 1) > #error "Unsupported compiler" > #endif > > -// Duplicated in fsm.def > -#define WEBRTC_DATACHANNEL_STREAMS_DEFAULT 256 > +#define WEBRTC_DATACHANNEL_STREAMS_DEFAULT 256 > +#define WEBRTC_DATACHANNEL_PORT_DEFAULT 5000 > +#define WEBRTC_DATACHANELL_MAX_MESSAGE_SIZE_DEFAULT 64000 draft-ietf-mmusic-sctp-sdp-26 says the default is 64K. While "K" is indeterminate in definition here, I had assumed it was 65536, not 64000. Suggest checking with Crister/etc about clarifying that.
Attachment #8873313 - Flags: review?(rjesup) → review+
Comment on attachment 8873313 [details] Bug 1335262: read and emit datachannel max-message-size. > draft-ietf-mmusic-sctp-sdp-26 says the default is 64K. While "K" is indeterminate in definition here, I had assumed it was 65536, not 64000. > > Suggest checking with Crister/etc about clarifying that. Pinged Christer. And changed the code to 65536 as I personally don't care.
Christer confirmed that 65535 is/was the intended value (and forwarded the request to update the draft to WG and AD - because it pretty late in draft process).
Pushed by drno@ohlmeier.org: read and emit datachannel max-message-size. r=jesup
Status: NEW → RESOLVED
Closed: 3 years ago
status-firefox55: --- → fixed
Resolution: --- → FIXED
Target Milestone: --- → mozilla55
54 RC build is released. Mark 54 won't fix.
|
https://bugzilla.mozilla.org/show_bug.cgi?id=1335262
|
CC-MAIN-2020-05
|
refinedweb
| 407
| 55.84
|
mbtowc - convert a character to a wide-character code
#include <stdlib.h>
int mbtowc(wchar_t *restrict pwc, const char *restrict s, size_t not a null pointer, mbtowc() shall determine the number of bytes that constitute the character pointed to by s. It shall then determine the wide-character code for the value of type wchar_t that corresponds to that character. (The value of the wide-character code corresponding to the null byte is 0.) If the character is valid and pwc is not a null pointer, mbtowc() shall store the wide-character code in the object pointed to by p shall cause the internal state of the function to be altered as necessary. A call with s as a null pointer shall cause this function to return a non-zero value if encodings have state dependency, and 0 otherwise. If the implementation employs special bytes to change the shift state, these bytes shall not produce separate wide-character codes, but shall be grouped with an adjacent character. Changing the LC_CTYPE category causes the shift state of this function to be unspecified. At most n bytes of the array pointed to by s shall be examined.
The implementation shall behave as if no function defined in this volume of IEEE Std 1003.1-2001 calls mbtowc().
If s is a null pointer, mbtowc() shall return a non-zero or 0 value, if character encodings, respectively, do or do not have state-dependent encodings. If s is not a null pointer, mbtowc() shall either return 0 (if s points to the null byte), or return the number of bytes that constitute the converted character (if the next n or fewer bytes form a valid character), or return .
|
https://pubs.opengroup.org/onlinepubs/009696699/functions/mbtowc.html
|
CC-MAIN-2020-29
|
refinedweb
| 285
| 58.62
|
flutter_barcode_scanner.
Getting Started
Follow the steps for Android and iOS
PLEASE FOLLOW iOS STEPS CAREFULLY
Android
:zap: Don't worry, you don't need to do anything.
iOS - Requires Swift support
Deployment target : 11
1. Fresh start:
- Create a new flutter project. Please check for Include swift support for iOS code.
- After creating new flutter project open
/iosproject in Xcode and set minimum deployment target to 11 and set Swift version to 5.
- After setting up the deployment target and swift version, close the Xcode then run pod install in
/iosin flutter project.
You have done with basic configuration now proceed to section How to use.
2. Adding to existing flutter app:
If your existing ios code is Swift then you just need to do following.
- Set minimum deployment target to 10 and set Swift version to 5.
- Close the Xcode and run pod install in
/iosin flutter project.
- Now proceed to section How to use.
If your existing ios code is Objective-C then you need to do following.
- Create a new flutter project with same name at different location (Don't forget to check Include swift support for iOS code while creating)
- Just copy newly created
/iosfolder from project and replace with existing
/ios.
- Open ios project in Xcode and set minimum deployment target to 11 and set Swift version to 5.
- Run pod install in
/ios
Note: If you did any changes in ios part before, you might need to make these configuration again
How to use ?
To use on iOS, you will need to add the camera usage description.
To do that open the Xcode and add camera usage description in
Info.plist.
<key>NSCameraUsageDescription</key> <string>Camera permission is required for barcode scanning.</string>
After making the changes in Android ans iOS add flutter_barcode_scanner to
pubspec.yaml
dependencies: ... flutter_barcode_scanner: ^1.0.1
One time scan
- You need to import the package first.
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
- Then use the
scanBarcodemethod to access barcode scanning.
String barcodeScanRes = await FlutterBarcodeScanner.scanBarcode( COLOR_CODE, CANCEL_BUTTON_TEXT, isShowFlashIcon, scanMode);
Here in
scanBarcode,
COLOR_CODE is hex-color which is the color of line in barcode overlay you can pass color of your choice,
CANCEL_BUTTON_TEXT is a text of cancel button on screen you can pass text of your choice and language,
isShowFlashIcon is bool value used to show or hide the flash icon,
scanMode is a enum in which user can pass any of
{ QR, BARCODE, DEFAULT }, if nothing is passed it will consider a default value which will be
QR.
It shows the graphics overlay like for barcode and QR.
NOTE: Currently,
scanMode is just to show the graphics overlay for barcode and QR. Any of this mode selected will scan both QR and barcode.
Continuous scan
- If you need to scan barcodes continuously without closing camera use
FlutterBarcodeScanner.getBarcodeStreamReceiverparams will be same like
FlutterBarcodeScanner.scanBarcodee.g.
FlutterBarcodeScanner.getBarcodeStreamReceiver("#ff6666", "Cancel", false, ScanMode.DEFAULT) .listen((barcode) { /// barcode to be used });
Contribution:
would :heart: to see any contribution, if you like :star: repo
|
https://pub.dev/documentation/flutter_barcode_scanner/latest/
|
CC-MAIN-2020-29
|
refinedweb
| 502
| 55.34
|
Asked by:
Razor syntax to complete an MVC form.
Question
- User-1674022954 posted
Hi. I'm very new to using Razor with C# and am conducting this project in order to try to better my understanding of it.
What this application is supposed to do, once completed, is ask the user to input three integers and then print out the sum of those integers. Right now, I have the basic frame of the View and Controller set up. (There is no Model.) The controller is set up to use an HTTP-Post protocol in order to send information to the HTML form.
What I'm struggling with, is the code needed to communicate the data directly to the form, as well as whatever parameters are needed so that ASP.net will ignore the presence of two identically-named controller actions (which I'm told it should be able to do once the Razor syntax is set up properly). Any guidance here would be very helpful.
Controller:
public ActionResult Index(int firstInt = 0, int secondInt = 0, int thirdInt = 0) { return View(); } [HttpPost] public ActionResult Index(int firstInt = 0, int secondInt = 0, int thirdInt = 0) { int sum = firstInt + secondInt + thirdInt; ViewBag.result = sum; }
Index View:
<form action="" method="post"> <table> <tr><td>Enter the 1st Number: <input id="firstInt" name="firstInt" type="text" value="0" /></td></tr> <tr><td>Enter the 2nd Number: <input id="secondInt" name="secondInt" type="text" value="0" /></td></tr> <tr><td>Enter the 3rd Number: <input id="thirdInt" name="thirdInt" type="text" value="0" /></td></tr> <tr> <td><input id="Submit" type="submit" value="submit" /><input id="Reset" type="reset" value="reset" /></td> </tr> <tr> <td>Sum = @ViewBag.result</td> </tr> </table> </form>Wednesday, October 11, 2017 11:40 PM
All replies
- User347430248 posted
Hi The Rarispy,
you can refer example below may help you.
model:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace math123.Models { public class Manish { public int sum(int a, int b) { int c = a + b; return c; } public int sub(int a, int b) { int c = a + b; return c; } public int mul(int a, int b) { int c = a * b; return c; } public int div(int a, int b) { int c = a / b; return c; } } }
controller:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using math123.Models; namespace math123.Controllers { public class manuController : Controller { // // GET: /manu/ public ActionResult Index() { Manish man = new Manish(); man.sum(10,20); man.sub(30, 10); man.mul(10, 50); man.div(100, 5); return View(man); } } }
view:
<%@ Page <script runat="server"> protected void Page_Load(object sender, EventArgs e) { TextBox2.Text = Model.sum(10, 20).ToString(); TextBox3.Text = Model.sub(30, 10).ToString(); TextBox4.Text = Model.mul(10, 50).ToString(); TextBox5.Text = Model.div(100, 5).ToString(); } </script> <html xmlns="" > <head runat="server"> <title>Index</title> </head> <body bgcolor="#008040"> <form id="form1" runat="server"> <div style="background-color: #66CCFF"> Sum of Number <asp:TextBox</asp:TextBox> <br /> Sub of Number <asp:TextBox</asp:TextBox> <br /> Mul of Number <asp:TextBox</asp:TextBox> <br /> Div of Number <asp:TextBox</asp:TextBox> <br /> </div> </form> </body> </html>
Reference:
Arithmetic operation in ASP.NET MVC
Regards
DeepakThursday, October 12, 2017 5:43 AM
- User-1674022954 posted
Thank you for your suggestion, Deepak Panchal. I don't think I can use it though, because the thing I wanted to accomplish with this project was to learn Razor syntax. It's a requirement of the prompt I took that I use Razor syntax and the [HttpPost] method. But thank you anyway.Thursday, October 12, 2017 1:02 PM
- User475983607 posted
thing I wanted to accomplish with this project was to learn Razor syntax. It's a requirement of the prompt I took that I use Razor syntax and the [HttpPost] method. But thank you anyway.
The problem is the example you selected is not good example of using Razor syntax. See the following link to get started with Razor syntax.
Or if you are trying to learn the new Core Razor Pages, see the following link., October 12, 2017 1:49 PM
|
https://social.msdn.microsoft.com/Forums/en-US/1fa89e4f-5415-4b09-886d-67fb76e6fa14/razor-syntax-to-complete-an-mvc-form?forum=aspdotnetwebpages
|
CC-MAIN-2022-05
|
refinedweb
| 695
| 56.45
|
Transformation Languages like XSLT are the most powerful techniques for processing XML documents. Unfortunately XSLT is very ressource-consuming so that you can’t use it to process mass data. That’s why serial transformation languages have been developed that can transform XML documents in linear time and keep only a small part of the XML document in the main memory. Under ABAP Simple Transformations are the most promising technique to speed up XML processing or to deal with huge XML documents. I discussed ST in my weblog series “XML processing in ABAP” (for example Part 6 – Advanced Simple Transformations) and in detail in XML-Datenaustausch in ABAP.
In this blog I will introduce STX (a short form for Streaming Transformations for XML) – a general transformation language for serial XML processing that you can use under Java. STX works event-based, think of it as a kind of XSLT based of SAX2 concepts.
Streaming Transformations for XML.
I will introduce STX and give a very simple and a more complicated example of an STX program. If you want to understand these examples in detail or you want to learn STX in depth I suggest you to read the article An Introduction to Streaming Transformations for XML. At the end I will discuss application areas of STX and topics I want to cover in the following parts of this weblog series.
STX compared to other Transformation Languages
Simple Transformations and STX are both serial and procedural transformation languages in XML syntax. But they are several differences:
- STX is a multi purpose language that can be used to transform XML documents to XML documents as well as to general text streams.
- STX doesn’t support generation of ABAP data like ST does. You have to generate the canonical asXML representation.
- STX is not symmetric.
- STX is Turing complete.
- STX can call other languages like XSLT, Java oder Javascript.
- STX is rule-based.
Le me mention two differences between STX and XSLT:
- STX is a procedural programming language: we can assign variables many times and can perform loops.
- STX uses STXPath as query language. STXPath ist derived vom XPath 2.0 but can access only the ancestors of a certain node.
- STX is event-based: STX templates are executed in the specific order of the input stream.
- STX has no named templates but we can define procedures.
- There are no commands like xslt:for-each that can change the current node.
STX uses the XSLT 1.0 data model – not the one of XSLT 2.0. It supports some features of XSLT 2.0 like multiple output documents and text processing. In fact stx:analyse-text is more powerful than the corresponding command in XSLT 2.0. If you are interested in a scientific investigation of STX I suggest you to read Oliver Becker’s PhD-thesis.
The First Example
The following transformation copies an XML document and renames all elements with name person to individual:
STX commands are defined in the namespace. The main command is stx:transform. Please remark that we use the attribute pass-through="all" of the stx:transform command to copy the complete input XML document to the output stream. For the element person we define a special rule: if it occurs we give out the \ an element named individual. We use stx:process-attributes to copy the attributes of the just processed element person. stx:process-children continues event processing.
The Second Example
Consider following example: an XML document contains a list of business partners and a list of contract information of each business partner:
We want to transform the document above into two separated CSV-datasets. The first dataset contains the information of business partners and the second the corresponding contracts. Both are linked by foreign keys we have to calculate during the transformation. In fact we transform the hirarchical structure of the XML document to relationial data model. Let’s look at the wanted output:
and .
Let me explain the structure. The number 4711 is an external parameter given to the transformation. Then we have a counter for the person, that is used in the second dataset, too. The values F;Maria;Testperson;19660703;12345;Teststadt;Teststr.are defined in the elements person_name, birth_dttm and addr.
The second dataset contains another counter for the contract information (element contract). The attribute ende is optional and we take a default value 99991231 if it is missing. Following transformation solves the task:
.
Let’s have a closer look. We define pass-through="none" to control the output: only literal result elements and output defined by stx:value-of will be copied to the output stream. stx:param defines an external parameter and semikolon and crlf are two variables we use as constants for formatting the output. bpnr and contractnr are two counters we will use later. We define a template with attribute match="/" that is executed at the beginning when the document node is processed. Within that template we delete the content of the two datasets person.txt and contract.txt. Then we start the event-loop and apply the templates of the group bpdaten to the elements in the input stream:
.
The group bpdaten contains a few variables and templates that assign the variables. Each template contains the command stx:process-children to suspend the processing of the current template by processing the children of the current node. Let me cite the STX-specification: “Using SAX2 terms: this instruction splits a template into two parts such that a SAX2 startElement event causes the execution of the first part and the corresponding SAX2 endElement event causes the execution of the second part. There must be always at most one stx:process-children instruction executed during the processing of a template.” The template that matches the bp elements increments the counter for the business partners:
There is one template we use to give out the assigned variables. Please remark that stx:result-document defines the output-stream. Moreover we use a procedure to reformate the date: stx:call-procedure name="format-date":
The procedure format-date is a child of the root element stx:transform and writes a formatted date to the output stream:
We define a second group contracts that is similar to the first one but works on the child-elements of status. It contains variables that are filled by corresponding templates. If elements are optional we assign default variables to the corresponding variables. The template public="yes" attribute in stx:template match="contract" public="yes" makes the template visible from the group bpdaten and declares this template as entry to the group:
Grouping techniques using stx:group this is a very important method for writing more readable as well as maintainable programs. In this program a group corresponds to an entity (business partners resp. contract information). The templates within a group correspond to the child elements of a certain element. While processing the child elements we apply only templates within that group. In fact we can define the visibility of each template of a group (global or local) and the visibility in a wider context, too.
Grouping templates makes the STX programs more maintainable. If there is a “local” change in the XML documents we want to transform we only need to do changes within one group. In Joost grouping also increases performance because we reduce the number of templates that have to be checked for matching a certain element.
Applications of STX Programs
Let me emphasize that if you have to do XML processing there are some tasks that can’t solved under ABAP. In this case you shouldn’t be afraid to use Java to have access to very powerful tools like STX.
Obvious Applications of STX
Besides “local transformations” (renaming elements and attributes) there are obvious tasks for STX, for example:
- Splitting large XML documents into smaller ones.
- Doing preprocessing before using a Simple Transformation that bridges the gap between XML and ABAP.
- Doing postprocessing after using a Simple Transformation that bridges the gap between ABAP and XML.
Complex Transformations
The second example shows the most important techniques if you want to create STX programs. But every serial transformation languages has the same problem: we have only a limited access to the XML document that is processed. In STX we can access the current element, its content and the value of its attributes as well as content and attributes of its ancestors. For complex transformations we have to save elements into buffers to access them later an. In the next part of this weblog series I will implement an XSLT program from my SAP Heft XML-Datenaustausch in ABAP in STX and perform a complex transformation.
Streaming Validations for XML
We do data exchange to link electronic business processes. Often these processes require quality assurances to the data, otherwise we need (sometimes manual) postprocessing. We can use schema languages like W3C XML Schema to model XML documents in a formal language and to check against this formal specificationm but often this is not enough. There are more powerful schema languages like Schematron that allow to define numerical checks of an XML document for example. Unfortunately most Schematron implementations rely on XSLT and have the same ressource problem when dealing with mass data. We can solve this problem by defining a schema language that is similar to Schematron that allows to define assertion about patterns of XML documents but allows an implementation in STX.
In fact I defined such a language and wrote an XSLT transformation that converts those assertions to an STX program. I will introduce that language in future in another blog.
Hope that helps.
Gr8 webblog and I am very much eager to learn this. I have downloaded Joost. Will give a try and contact u if I have any doubts.
Regards,
Prasad U
|
https://blogs.sap.com/2006/07/09/streaming-techniques-for-xml-processing-part-1/
|
CC-MAIN-2019-09
|
refinedweb
| 1,643
| 55.34
|
As the process of creating for the web continues to evolve we see that methods continue to get better. Engineers find ways to take the best parts of the best technologies and merge them together to create a more efficient system.
When fetching data in traditional web platforms, the process is mostly handled by the fetch API, the Axios library, or using a query language like GraphQL. This data is mostly handled at runtime. However, we have seen that while handling data at runtime we may notice that this routine in the application if not handled properly might lead to a larger load time than needed. As a solution, we can take advantage of some abstractions that fetch in some of our data at runtime while optimizing with static content at build time and offers performance advantages.
As with static sites, most of the data is pulled in at build time. In this article, we will be looking at how Gatsby, which is a PWA generator, uses GraphQL to pull in data at build time and also its implications on performance.
Pulling data in Gatsby without GraphQL
Gatsby offers three main methods of creating routes in sites — adding components to a page folder, programmatically creating pages from
gatsby-node.js file with the CreatPages API, and using a plugin that can create pages.
These methods can all be used at the same time or individually and if used correctly will give the best Gatsby experience. To understand the advantages of GraphQL in Gatsby you will look at an example of a creating pages programmatically without GraphQL.
Gatsby allows you to use the createPages API in
gatsby-node.js to programmatically create pages as seen in the code block below:
exports.createPages = ({ actions: { createPage } }) => { createPage({ path: "/page-with-no-graphql/", component: require.resolve("./src/templates/page-with-no-graphql"), context: { title: "Getting data without GraphQL!", content: "<p>This is page content.</p><p>No GraphQL required!</p>", }, }) }
In the code block above, we destructure the
createPage function from the
actions object and pass a path into it. This path is what shows up as the route when the page is being displayed. We also resolve a component which is the template layout the pages are going to fill. Lastly, the context of the pages is what is made available in the template with the
pageContext object.
From the code block below, we can see that in the
/src/templates/page-with-no-graphql file we can access the context in
gatsby.node.js via pageContext:
import React from "react" const WithContext = ({ pageContext }) => ( <section> <h1>{pageContext.title}</h1> <div dangerouslySetInnerHTML={{ __html: pageContext.content }} /> </section> ) export default WithContext
After running
gatsby develop, you’ll see the website at .
The drawback of this method is that we have to continuously change and update the context for every page we want to create. This feels like a task that can never be completed.
Introducing queries to
gatsby-node.js
To solve the drawback of having to manually update the routes for each page created in
gatsby-node.js Gatsby ships with GraphQL which gives you the ability to use queries to get a more descriptive view of the data you are fetching.
To make this process easier, the queries can be generated from a tool called GraphiQL, which is available at after running
gatsby develop.
The queries are generated for you by clicking on the boxes on the left. You can also test the query to see what they return by hitting the play button on the top left. This would display the expected values of the query and give an idea of how to get the value needed. It goes a step further to allow you to visualize the query in a component setting using the code exporter:
In
gatsby-node.js, you can use the GraphQL query you just wrote to generate pages, like this:
exports.createPages = async ({ actions: { createPage }, graphql }) => { const results = await graphql(` { allProductsJson { edges { node { slug } } } } `) results.data.allProductsJson.edges.forEach(edge => { const product = edge.node createPage({ path: `/gql/${product.slug}/`, component: require.resolve("./src/templates/product-graphql.js"), context: { slug: product.slug, }, }) }) }
You need to use the
graphql helper that’s available to the
createPages Node API to execute the query. To make sure that the result of the query comes back before continuing, use
async/await.
The results that come back are very similar to the contents of
data/products.json, so you can loop through the results and create a page for each.
However, note that you’re only passing the
slug in
context — you’ll use this in the template component to load more product data.
As you’ve already seen, the
context argument is made available to the template component in the
pageContext prop. To make queries more powerful, Gatsby also exposes everything in
context as a GraphQL variable, which means you can write a query that says, in plain English, ‘Load data for the product with the slug passed in
context‘.
Here’s what that looks like in practice from the
src/templates/product-graphql.js file:
import React from "react" import { graphql } from "gatsby" import Image from "gatsby-image" export const query = graphql` query($slug: String!) { productsJson(slug: { eq: $slug }) { title description price image { childImageSharp { fluid { ...GatsbyImageSharpFluid } } } } } ` const Product = ({ data }) => { const product = data.productsJson return ( <div> <h1>{product.title}</h1> <Image fluid={product.image.childImageSharp.fluid} alt={product.title} style={{ float: "left", marginRight: "1rem", width: 150 }} /> <p>{product.price}</p> <div dangerouslySetInnerHTML={{ __html: product.description }} /> </div> ) } export default Product
Querying for all fields in the context object of
gatsby-node.js
Imagine a scenario where you could query for all the parameters your template would need in the
gatsby-node.js. What would the implications be? In this section, we will look into this.
In the initial approach, you have seen how the
gatsby-node.js file will have a query block like so:
const queryResults = await graphql(` query AllProducts { allProducts { nodes { id } } } `);
Using the
id as an access point to query for other properties in the template is the default approach. However, suppose you had a list of products with properties you would like to query for. Handling the query entirely from
gatsby-node.js would result in the query looking like this:
exports.createPages = async ({ graphql, actions }) => { const { createPage } = actions; const queryResults = await graphql(` query AllProducts { allProducts { nodes { id name price description } } } `); const productTemplate = path.resolve(`src/templates/product.js`); queryResults.data.allProducts.nodes.forEach(node => { createPage({ path: `/products/${node.id}`, component: productTemplate, context: { // This time the entire product is passed down as context product: node } }); }); }; };
You are now requesting all the data you need in a single query (this requires server-side support to fetch many products in a single database query).
As long as you can pass this data down to the template component via
pageContext, there is no need for the template to make a GraphQL query at all.
Your template
src/templates/product.js file will look something like this :
function Product({ pageContext }) { return ( <div> Name: {pageContext.name} Price: {pageContext.price} Description: {pageContext.description} </div> ) }
Performance implications of querying all fields from
gatsby-node.js
Using the
pageContext props in the template component can come with its performance advantages of getting in all the data you need at build time — from the createPages API. This removes the need to have a GraphQL query in the template component. It does come with the advantage of querying your data from one place after declaring the
context parameter.
However, it doesn’t give you the opportunity to know what exactly you are querying for in the template and if any changes occur in the component query structure in
gatsby-node.js. Hot reload is taken off the table and the site needs to be rebuilt for changes to reflect.
Gatsby stores page metadata (including context) in a redux store (which also means that it stores the memory of the page). For larger sites (either number of pages and/or amount of data that is being passed via page context) this will cause problems. There might be “out of memory” crashes if it’s too much data or degraded performance:
If there is memory pressure, Node.js will try to garbage collect more often, which is a known performance issue.
Page query results are not stored in memory permanently and are being saved to disk immediately after running the query.
I recommend passing “ids” or “slugs” and making full queries in the page template query to avoid this.
Incremental builds trade-off of this method
Another disadvantage of querying all of your data in
gatsby-node.js is that your site has to be rebuilt every time you make a change, so you will not be able to take advantage of incremental builds.
Conclusion
In this blog post, we have looked at how Gatsby uses GraphQL on its data layer to fetch static data at build time. We have also seen the performance implications of querying for all fields in the
gatsby-node.js . I hope that this blog post has helped to unravel the “why” surrounding the relationship between these two technologies and how they help provide an amazing experience for Gatsby users. Happy coding and be sure to check out the Gatsby tutorials..
|
http://blog.logrocket.com/how-graphql-boosts-performance-in-gatsby/
|
CC-MAIN-2020-40
|
refinedweb
| 1,554
| 55.74
|
31907/how-to-delete-a-folder-in-s3-bucket-using-boto3-using-python
You can delete the folder by using a loop to delete all the key inside the folder and then deleting the folder.
Here is a program that will help you understand the way it works.
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('aniketbucketpython')
for obj in bucket.objects.filter(Prefix='aniket1/'):
s3.Object(bucket.name,obj.key).delete()
Hope this works.
See dmitrybelyakov's answer that accounts for pagination requirements of boto3
You can use method of creating object ...READ MORE
You can delete the file from S3 ...READ MORE
You can use the below command
$ aws ...READ MORE
You need to rename your bucket is a particular format that works ...READ MORE
Using Client versioning you can create folders ...READ MORE
OR
Already have an account? Sign in.
|
https://www.edureka.co/community/31907/how-to-delete-a-folder-in-s3-bucket-using-boto3-using-python
|
CC-MAIN-2020-05
|
refinedweb
| 144
| 61.53
|
Search
Search Hi,
I have a project in which I am trying to enter "Marathi" (Indian local language) data in JSP using JSTL and trying to search data... and tries to search then It shows no data from database
STRUTS-display search results - Struts
STRUTS-display search results Hii, I am a beginner in struts..I want to retrieve few records from database and display in jsp page.First i tried... them in jsp.. Search Results Projects
ASAP.
These Struts Project will help you jump the hurdle of learning complex
Struts Technology.
Struts Project highlights:
Struts Project to make learning easy
Using Spring framework in your application
Project in STRUTS
Struts Hibernate Integration
string and presses search button.
Struts framework process the request... and you can download and
start working on it for your project or to learn Struts... and
integrate it with the Struts.
Writing Web Client to Search the database
saritha project - Struts
struts
struts shopping cart project in struts with oracle database connection shopping cart project in struts with oracle database connection
Have a look at the following link:
Struts Shopping Cart using MySQL
TYBsc IT final project (MOBILE BASED SMS SEARCH ENGIN)
TYBsc IT final project (MOBILE BASED SMS SEARCH ENGIN) How to send sms pc to mobile using JSP & Servelet
TYBsc IT final project (MOBILE BASED SMS SEARCH ENGIN)
TYBsc IT final project (MOBILE BASED SMS SEARCH ENGIN) How to send... completed. so i requested to you pls answer my question. My project name is MOBILE BASED SMS SEARCH EN
AJAX Search
AJAX Search I have to create a project where the user enters a letter in a text box and all the names starting with that letter are retrieved. I'm using PHP and MYSQL as the database. Can somebody please suggest me the AJAX
Need Project
Need Project How to develop School management project by using Struts Framework? Please give me suggestion and sample examples for my project
search functionality with in application
search functionality with in application I have created on web based web site in struts. i want to give user functionality for search any link... and can perform search with in application. i have heard about search engine .can
simple java search engine
simple java search engine i have already downloaded the project simple java search engine.but i am not able to run it.can anyone help me.i have.... This is needed for every one.
The project is simple search engine, which searches
search filter and JTable
search filter and JTable I first im not speak englis very well, so my question is:
how can i make search data in JTable of java?
i wan to search... java.sql.*;
import java.awt.event.*;
import javax.swing.*;
class Search{
public
Binary Search Tree
Binary Search Tree Question-1 )
Modify the BinarySearchTree class... are serializable.Test your class with a project that serializable a BinarySearchTree object, and another project that deserializes and prints that object
Binary Search Tree
Binary Search Tree Question-1 ) Modify the BinarySearchTree class so... are serializable.Test your class with a project that serializable a BinarySearchTree object, and another project that deserializes and prints that object
MINI PROJECT
MINI PROJECT CAN ANYONE POST A MINI PROJECT IN JAVA?
Hi...
You can have the following projects as per ur requirement. Free and easy... management in struts
search
search how to develop search box and how to retrive data from database..
Please visit the following link:
Search box
B+ trees search
B+ trees search Can anyone send the code for implementing the B+ trees searching on a oracle database?
please your answer will be useful for my project
SEARCH
SEARCH how can we do search in jsp...?
option for search criteria like name and DOB...
Please visit the following links:
struts - Struts
struts Hi,
i want to develop a struts application,iam using eclipse... you. hi,
to add jar files -
1. right click on your project.
2... functionality u want to use in your project. There is no standard list of jar files
Major Search Engines List
, Netscape Search and Lycos to name just a few. Open
Directory Project...
Major Search Engine Lists
Listing of 10 Top Search Engines
Form with a search filter in spring mvc?
Form with a search filter in spring mvc? Hi
I am new to Spring MVC, I have created a spring project which is displaying the list from database into my jsp page, Now in the same jsp page at the right hand corner I have a search
search - Java Server Faces Questions
search hello!
my project is document search system. Im am suppose to search keywords for my document by the scanning the document itself and the criteria is if any word appears more than ten times in the document i application - Struts
struts login application form code Hi, As i'm new to struts can anyone send me the coding for developing a login form application which involves a database search like checking user name in database
Submitting Web site to search engine
Registering Your Web Site
To Search Engines.... 85% of
Internet users find sites through search engines, so each search... to the
search engines and directories. Once you register your site
Android Application Project
Android Application Project Hi,
How to create Android Application Project with following features:
Select list of music station
Play the the selected station
Save station in the list
Search stations of interest based
Java Project - Development process
Java Project Hello Sir I want Java Project for Time Table of Buses.that helps to search specific Bus Time and also add ,Update,Delete the Bus Routes. Back End MS Access
Plz Give Me
hibernate web project - Hibernate
hibernate web project hi friends,very good morning,how to develop and execute web project using myeclipse ide.plz give me step-by-step procedure.../hibernate/runninge-xample.shtml
Search bar application
Search bar application
In this tutorial, will be creating a Search screen, which have a table view with a search bar. Table should display all the data if search field is empty other wise it should show all the data which matches
project on avl tree and hashing
project on avl tree and hashing I want to make graphical interface in java ,in this graphical interface there are seven buttons ,first button Read...,four button delete customer ,five button search customer,six button print data
Project on avl tree and hashing
Project on avl tree and hashing I want to make graphical interface in java ,in this graphical interface there are seven buttons ,first button Read... delete customer ,five button search customer,six button print data to file(in order
Struts 1 Tutorial and example programs
completing this tutorial you will be able to use Hibernate in your
Struts project... Struts project. We will be using Hibernate Struts
plug-in to write... to Search the database using Struts Hibernate Plugin
In this section module and source code on my project hospital management system
project
project does hostel management system project contain any dynamic web pages
project on avl tree and hashing
customer ,five button search customer,six button print data to file(in order
how to show search results in the same panel of jframe to where search field and button is present..
how to show search results in the same panel of jframe to where search field and button is present.. Hello Sir,
I am working on project where i have to show the search result in the same panel of where search field
|
http://www.roseindia.net/tutorialhelp/comment/19583
|
CC-MAIN-2014-52
|
refinedweb
| 1,259
| 67.69
|
Add A New Dimension To The Middle Of A Tensor In PyTorch
Add a new dimension to the middle of a PyTorch tensor by using None-style indexing
< > Code:
Transcript:
This video will show you how to add a new dimension to the middle of a PyTorch tensor by using None style indexing.
First, we import PyTorch.
import torch
Then we print the PyTorch version we are using.
print(torch.__version__)
We are using PyTorch 0.4.0..
pt_empty_tensor_ex = torch.Tensor(2,4,6,8)
Let’s check what dimensions our pt_empty_tensor_ex Python variable has by using the PyTorch size operation.
print(pt_empty_tensor_ex.size())
We see that it is a 2x4x6x8 tensor which is how we defined it.
For this example, we want to add a new dimension to the middle of the PyTorch tensor.
So we want to go from 2x4x6x8 to adding a new dimension between the 4 and the 6.
The way we’ll do this is we will use None style indexing.
pt_extend_middle_tensor_ex = pt_empty_tensor_ex[:,:,None,:]
So we use None.
Here, we have a capital N.
This is going to tell PyTorch that we want a new axis for the tensor assigned to the pt_empty_tensor_ex Python variable.
We also use the Python colon notation.
So for the first index, we use a colon to specify that we want everything in the already existing first dimension.
Then we use a colon as the second index to specify that we want everything in the already existing second axis.
Then we use None to specify we want to insert a new axis, then comma, then a colon as the last index to specify that we want the rest of the tensor.
We assign this new tensor that’s going to be returned to the Python variable pt_extend_middle_tensor_ex.
It’s useful to check the size of the pt_extend_middle_tensor_ex.
print(pt_extend_middle_tensor_ex.size())
So we use the PyTorch size, and we’re going to print it.
What we see is that the torch size is now 2x4x1x6x8, whereas before, it was 2x4x6x8.
So we were able to insert a new dimension in the middle of the PyTorch tensor.
Perfect - So we were able to add a new dimension to the middle of a PyTorch tensor by using None style indexing.
|
https://aiworkbox.com/lessons/add-a-new-dimension-to-the-middle-of-a-tensor-in-pytorch
|
CC-MAIN-2020-40
|
refinedweb
| 377
| 71.95
|
Tips and Tricks
What Are Self-Executing Closures
The Missing Manual
for Swift Development
The Guide I Wish I Had When I Started Out
Join 20,000+ Developers Learning About Swift DevelopmentDownload Your Free Copy
I make ample use of self-executing closures in a range of scenarios. In this episode, I show you several patterns in which self-executing closures come in useful and can improve the code you write.
What Is It?
Before I show you the different uses of self-executing closures, I want to make sure you understand what a self-executing closure is. Let me show you an easy to understand example in a playground. We define a variable,
myVar, and assign an empty closure to the variable. This should look familiar.
import Foundation var myVar = { }
In the body of the closure, we create and return a string literal. Can you guess what the type of
myVar is? Press Option and click
myVar to find out. The type of
myVar is a closure that accepts no arguments and returns a string.
As the name implies, a self-executing closure is a closure that is immediately executed. Some developers use the term immediately-executing closure for that reason. Let's append a pair of parentheses to the closure to execute it.
import Foundation var myVar = { return "this is a string" }()
Press Option and click
myVar. The type of
myVar is no longer a closure, it is now of type
String. By appending a pair of parentheses to the closure, the closure is executed and the return value of the closure is assigned to
myVar.
Lazy Properties
Assigning an initial value to a lazy property is probably the most common use of self-executing closures. This pattern is convenient if the initialization of an object is computationally expensive, requires several lines of code, or needs access to
self, the owner of the object. Take a look at this example.
private lazy var tableView: UITableView = { // Initialize Table View let tableView = UITableView(frame: .zero) // Configure Table View tableView.delegate = self tableView.dataSource = self tableView.translatesAutoresizingMaskIntoConstraints = false return tableView }()
Because the property declaration is prefixed with the
lazy keyword, we can access
self in the self-executing closure. This is possible because the self-executing closure is executed after the initialization of
self, the owner of the object. In this example,
self refers to the view controller that owns the table view.
What I like about this pattern is that the initialization and configuration of the table view are encapsulated by the self-executing closure. There's no need to set up the table view in
viewDidLoad() or another method. This makes your code readable and easier to understand.
Constant Properties
It's a common misconception that self-executing closures can only be used with variable properties. It's perfectly fine to use self-executing closures with constant properties. The subtle benefit is that the property is declared as a constant instead of a variable. Lazy properties always need to be declared as variable properties because the value is set after the initialization of the owner of the object.
The drawback of a constant property is that you can't access
self, the owner of the object, in the self-executing closure. Why is that? When used in combination with a constant property, the self-executing closure is executed during the initialization of the owner of the object instead of after the initialization.
private let titleLabel: UILabel = { // Initialize Title Label let titleLabel = UILabel(frame: .zero) // Configure Title Label titleLabel.numberOfLines = 0 titleLabel.translatesAutoresizingMaskIntoConstraints = false return titleLabel }()
Encapsulating Code
Self-executing closures can be used in a range of scenarios, not only to initialize properties. Take a look at this example.
// MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() // Helpers var tableViewIsHidden = true if viewState == .hasData { if userState == .signedIn { tableViewIsHidden = false } } // Configure Table View tableView.isHidden = tableViewIsHidden }
We define a variable,
tableViewIsHidden, and assign a default value to the variable,
true. The next few lines update the value of the variable by evaluating the state of the view and the user. Using a variable is a common pattern if you don't know what the value of the variable should be the moment you define it.
You probably know that you should use constants over variables whenever possible. If the value of
tableViewIsHidden doesn't change, then there's no need to declare it as a variable. Let's see if that is possible.
There's nothing inherently wrong with the current implementation, but I don't like the idea of using a variable in this scenario. We can replace the variable with a constant by using a self-executing closure. The code that modifies the variable is moved to the body of the closure and the return value of the closure is assigned to the variable. Because the variable is no longer modified, we can replace it with a constant.
// MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() // Helpers let tableViewIsHidden: Bool = { if viewState == .hasData { if userState == .signedIn { return false } } return true }() // Configure Table View tableView.isHidden = tableViewIsHidden }
Because we use a self-executing closure, we can simplify the code we write by exiting the self-executing closure early using
if statements. As an added bonus, the code becomes easier to read and understand.
// MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() // Helpers let tableViewIsHidden: Bool = { if viewState == .loading { return true } if userState == .anonymous { return true } return false }() // Configure Table View tableView.isHidden = tableViewIsHidden }
I like this pattern for several reasons. The obvious benefit is that we replace a variable with a constant. Anyone reading the code implicitly understands that the value of
tableViewIsHidden won't change. Another, more subtle, benefit is readability. The body of the closure contains the code that defines the value of the constant. Because we use a constant, we know that its value is defined in the self-executing closure and it won't be modified elsewhere.
Threading and Access Control
Lazy properties are convenient and they are easy to use, but it is important that you know and understand how they can impact the code you write. Lazy properties are not thread safe and for that reason some developers argue that you should only use them when they are needed, not when it's convenient to use them. I can appreciate this argument, but I don't agree. If you understand the risk of using lazy properties, then it's up to you to decide whether it's appropriate to use them.
It is perfectly fine to declare the views of a view controller as lazy properties because you know that these properties should only be accessed from the main thread. This isn't true if you're creating an object that is accessed by a range of different objects from different threads. In that scenario, you either implement a threading strategy that prevents threading issues or you don't declare the property as lazy. I recommend keeping it simple and avoid lazy properties in the latter scenario. Debugging threading issues isn't something most developers do for fun. I always try to keep code as simple as possible if I know that threading issues are a potential risk.
Keep in mind that lazy properties need to be declared as variables and that implies that they can be modified. That is a considerable drawback in my opinion. You can work around this by correctly applying access control modifiers. If no other objects need access to a lazy property, then apply the
private or
fileprivate modifier to lock down access.
What's Next?
While self-executing closures are not unique to Swift, they can add clarity to the code you write. When and why you use self-executing closures is a personal choice. Don't use self-executing closures because that is what you should do. If you don't feel they fit your coding style, then only use them when necessary. For me, writing code is very similar to writing a book or painting a picture, I tweak and mold the code until it feels right. It isn't important if that takes two, three, or ten passes. Commit your code once you're happy with the result.
The Missing Manual
for Swift Development
The Guide I Wish I Had When I Started Out
Join 20,000+ Developers Learning About Swift DevelopmentDownload Your Free Copy
|
https://cocoacasts.com/tips-and-tricks-what-are-self-executing-closures
|
CC-MAIN-2020-45
|
refinedweb
| 1,404
| 56.96
|
Mapping RDF data to ArangoDB Graphs
This document serves as a guide to getting started with RDF and ArangoDB. In it we highlight some potential approaches for working with RDF graphs and then some of the considerations when attempting to bring RDF data into ArangoDB. The concept of working with RDF graphs in ArangoDB is not fully supported, but we would like to start introducing solutions for mapping and start the conversation with the community. We welcome any feedback from the community on ways to improve the ingestion of RDF graphs as we work on an official implementation for ArangoDB. You can accomplish a lot with ArangoDB and RDF with a few workarounds, depending on your needs but be sure to see the caveats section for some considerations.
Getting Started
RDF graphs are purely directed graphs with no properties on vertices or edges. In
RDF, everything is referenced by edges; these edges are known as statements.
Statements are in the form
[subject, predicate, object, [graph]]. Statements pose
an interesting challenge when trying to interpolate an RDF graph as a property
graph. ArangoDB is uniquely suited to handle this due to having edges which
have a similar structure to vertices and thus can be used to resemble an
RDF graph or to instead represent RDF statements as properties associated
with a
subject. For this discussion, it is helpful to have an example; the
following is a simple RDF graph for Sir Arthur Conan Doyle.
<?xml version="1.0" encoding="UTF-8"?> <rdf:RDF xmlns: <rdf:Description rdf: <rdf:type rdf: <rdf:type rdf: <rdf:type rdf: <rdf:type rdf: </rdf:Description> </rdf:RDF>
The above code is RDF in RDF/XML format. This syntax can be considered the original/standard RDF syntax. However, many different serializations exist, and thanks to their readability and ease of parsing, has grown in popularity.
<> <> <> . <> <> <> . <> <> <> . <> <> <> .
This is the same RDF graph but serialized to N-Triples format. This format represents the same data from the same source. While the exploration of RDF, its syntax, and various serializations are beyond the scope of this guide, it is important to consider that the data ingestion isn’t always in the same format when dealing with RDF and is one of the few challenges we encounter when dealing with RDF graphs.
The following is an example of how this RDF graph could be modeled in ArangoDB. This approach:
- Maps the
subjectand
objectas vertices
- Maps the
predicateas the connecting edge
- Hashes the referent to the
_keyvalue
- Preserves the full referent as a text property
There can be issues that arise with this simple approach, and we discuss them throughout the guide, but this is a good place to start as it shows the potential for mapping the data.
Generate this graph for yourself by running the notebook.
Considerations
Literals
In RDF even literal values are referenced by edge. Literals may not have
exident edges (i.e., may not be the subject of a statement). RDF uses the XSD
type system for literals, so the string “Fred” is represented as
"Fred"^^xsd:String
or fully expanded as
"Fred" ^^http://…". Literals can also contain language
and locale tags, for example,
"cat@en" ^^xsd:String and
"chat@fr"^^xsd:String.
These language tags can be useful and would ideally be preserved.
Literals could be added as a property instead of creating a separate vertex; this takes better advantage of using a property graph. If you are coming from a triple store or downloading your data using a SPARQL query you could handle these properties when exporting.
IRI’s
Prefixes
In RDF, it is common to use namespace prefixes with referrents for ease of parsing. This can be easily handled with a property graph in a few ways. The easiest approach is to add the statement prefixes to the document. This keeps the prefixes close to the data but results in a lot of duplicated fields. Another approach would be to append the prefix and form the full URI as a property.
Identifiers
IRI’s (ex:) are used as universal identifiers in
RDF but contain contain special characaters, namely
: and
/, which make them not
suitable for use as an ArangoDB
_key attribute. This is the reason the previous
example hashes the IRI value. This has a downside of relying on the hashing
algorithm and in our case MD5 is one way so it becomes required to store the full
IRI string.
Blank Nodes
Blank nodes are identifiers that have local scope and cannot (must not) be referenced externally. Blank nodes are usually used in structures like lists and other situations where it is inconvenient to create IRI’s. They will cause problems when reconciling differences between graphs. Hasing these values as well is a way to work around them but as they are considered temporary identifiers in the RDF world they could pose consistency issues in your RDF graph.
Serializations
There are numerous RDF serializations, including XML and JSON based serializations and gzipped serializations. Third party libraries will likely handle all of the serializations but it is a step that may effect how data is imported.
Ontology, Taxonomy, Class Inheritance, and RDFS
The final consideration is something that for many is the core of RDF and semantic data: Ontologies. Not just ontologies but also class inheritance, and schema validation. One method would be add the ontology in a similar way to what has been suggested for the RDF graphs as ontologies are usually structured in the same way (or can be). However, how do you verify your data is always referencing the classes in your ontology? How can this data be used to make inferences if it cannot be validated? ArangoDB has schema validation but this is limited to JSON schema and does not complex class checking.
One approach to this would be to use a Foxx microservice to serve multiple knowledge graph functions.
DIY with Foxx
A Foxx service could be used to perform lookups against a document collection containing schema-like requirements. The data scientist could use this Foxx service as the ingestion entry point, meaning the data import would need to be validated before entry (resulting in slow imports).
Additionally, the Foxx service could instead be used as an eventual consistency checker that evaluates the data after import and either produces errors or take some other action. This could be extended to offer inference and rule generation based on the data inserted. Most of this functionality would rely on the Foxx queues feature or require manual intervention.
Using Foxx has its own drawbacks as it requires development efforts, consumes resources on the database servers and coordinators, and uses node which isn’t an option for all organizations.
The benefits of Foxx are the flexibility to program the precise needs of an organization and with the potential for high performance. The service would be located close to the data and has c++ access as a first class citizen. This has the potential to reduce any negative performance impact that might normally come with abstracting away this functionality.
RDF-star
While there is still work to be done when trying to bring RDF graphs into property graphs, there is one approach that aims to make it more worthwhile. The RDF-star implementation aims to bring the gap between RDF graph and property graph. Our initial internal approach to bring RDF data into ArangoDB will be to take advantage of the RDF-star specification. The RDF-star specification allows for nesting attributes in RDF statements to more closely mirror the benefits of a property graph. It is still in draft form but multiple vendors and libraries have already added suport for it. If you haven’t already give the specification a look and let us know if you would like to see it in ArangoDB.
|
https://www.arangodb.com/docs/3.9/data-modeling-graphs-from-rdf.html
|
CC-MAIN-2022-05
|
refinedweb
| 1,301
| 51.38
|
Created 7 October 2009
This was a presentation I gave at the DevDays Boston conference in
2009. I don't have much text to go with it, but these are the slides.
If you need them larger, there is a zip file of .pngs.
Joel's suggestion was to explain Peter Norvig's Spell Corrector
line-by-line. I've made a few small edits for expository purposes.
Here's the code:
import re, collectionsdef words(text): return re.findall('[a-z]+', text.lower())
def train(words): model = collections.defaultdict(int) for w in words: model[w] += 1 return modelN))
Here's the completed Nango code:
import reclass
2009,
Ned Batchelder
|
http://nedbatchelder.com/text/devdays.html
|
CC-MAIN-2017-09
|
refinedweb
| 111
| 59.5
|
Hello everybody
I'm a student and having problems with an assignment - I have at the moment no idea how to achieve an appropriate solution.
I'm aware that you shouldn't help me by showing some code. That's okay for me since I want to solve it by myself but I think it would be helpful when I get a small hint how to think about this problem here:
Write a simple program that controls an elevator in an office building. The
office building has 24 floors (0--23) and 3 elevators. The floors are 3m
heigh and the elevators move with 6m/s. Opening and closing the elevator
doors costs 6 seconds each.
Let's assume that all elevators are parked on the ground floor(0) and that
the doors are open. If a passenger wants to get from the ground floor to the
top floor (23), it would take 6sec (closing) plus 23*3/6sec (moving the
elevator) plus 6sec (opening) the door (=23.5sec). Total delivery time
would be 23.5sec.
Assuming that after 10 seconds another passenger requests an elevator on
the 10th floor (also going to the top floor), you have two options, reuse the
first elevator (which currently is on the 8th floor) or send a different one. If
you reuse the first elevator, it would arrive at second 11 on the 10th floor,
open its door take in the passenger (sec~17), close the doors (sec~23),
move to the top floor (sec~29.5), and open the door (sec~35.5). Total
delivery would be 35.5sec+25.5sec.
Had you used another elevator, the total delivery time would have been
23.5sec+29.5sec (close door (sec~16), move to floor 10 (sec~21), open
door (sec~27), close door (sec~33), move to top floor (sec~33.5), open
door (sec~39.5)).
Your program should read the information about passengers from a file passed as command line paramter
(or cin if '-' is passed as filename). The file contains one line per passenger. Each line contains a triple of
time-of-request, floor-of-request, target-floor-of request. For determining the elevator to use for a given
passenger only consider whether the passenger is going up or down and not the target floor. The target
floor is only considered once the passenger got onto the elevator.
For instance in the above case, the file would look as follows:
0,0,23
10,10,23
Your program should output something similar to the following
0: passenger 1 request on floor 0 handled by e1
6: e1 door closed, moving up (p1-23)
10: passenger 2 request on floor 10 handled by e1
11: e1 stopped on floor 10
17: e1 door opened
23: e1 door closed moving up (p1-23, p2-23)
29.5: e1 stopped on floor 23
35.5: e1 door opened (p1-35.5s, p2-25.5s)
Total delivery time is 61s.
Here is my code so far:
main.cpp
#include <iostream> #include <fstream> #include "elevator_system.h" using namespace std; int main (int argc, char * const argv[]) { elevator_system supercomputer; string input = argv[1]; // reads from commandline if (input == "-") { bool exit; while(!exit){ // get the input string string input; cout << "Triple: "; getline(cin, input, '\n'); if (input == "q") { exit = true; break; } supercomputer.transform_input( input ); } //print_array(); supercomputer.moving_elevators(); } // reads from file else { ifstream in_stream; in_stream.open( input.c_str() ); // check if the file is open if ( ! in_stream.is_open() ) { cout << "opening file \'" << input << "\' failed." << endl; } string tmp; // stream reads a word each iteration while( in_stream >> tmp ) { supercomputer.transform_input( tmp ); } // close file in_stream.close(); } }
elevator_system.cpp
/* * system.cpp * c++_06_ex2_elevator * */ #include "elevator_system.h" building build1("building1", 24, 3); elevator el1("el1", 6.0, 0); elevator el2("el2", 6.0, 0); elevator el3("el3", 6.0, 0); static double action[50][3]; static int row_counter; static int timer; elevator_system::elevator_system() { // } void elevator_system::transform_input( string input ) { int first_coma; int comma_counter = 0; string str; // we iterate through the string for (int i=0; i < input.length(); i++) { str = input.at(i); if (!str.compare(",") && comma_counter < 1 ){ comma_counter++; first_coma = i; stringstream Stream; Stream << input.substr(0, i); int first; Stream >> first; action[row_counter][0] = first; } else if (!str.compare(",") && comma_counter == 1) { stringstream Stream_second; Stream_second << input.substr(first_coma + 1, i); int second; Stream_second >> second; action[row_counter][1] = second; stringstream Stream_third; Stream_third << input.substr(i+1, input.length() - 1); int third; Stream_third >> third; action[row_counter][2] = third; } } row_counter++; } void elevator_system::moving_elevators() { // no idea how to use the splitted triple to determine which elevator should be used and how to print it correctly }
elevator.cpp
/* * elevator.cpp * c++_06_ex2_elevator */ #include "elevator.h" elevator::elevator(string el_name, int el_speed, int floor) : name( el_name ), speed( el_speed ), floor_right_now( floor ) { door_is_open = true; } string elevator::get_name() { return name; } double elevator::get_speed() { return speed; } double elevator::open_door() { door_is_open = true; return 6.0; } double elevator::close_door() { door_is_open = false; return 6.0; } // time to move from one floor to another without door opening / closing double elevator::moving_time( int target_floor ) { return ( ( target_floor - current_floor() ) * 3 ) / get_speed(); } // total time to move from one floor to another including door opening / closing double elevator::total_time_to_move_to(int target_floor ) { static double total_time = 0; if ( door_is_open ) { total_time = close_door() + moving_time( target_floor ) + open_door(); } else { total_time = open_door() + close_door() + moving_time( target_floor ) + open_door(); } set_current_floor( target_floor ); return total_time; } int elevator::current_floor() { return floor_right_now; } void elevator::set_current_floor( int end_floor ) { floor_right_now = end_floor; }
I've managed to read in a triple and split it correctly into three integers and put them into an array. But I have no idea how to proceed with this input after I read all in from the cin or file... I thought maybe I should decide for every tripple what to do and then put that decision into a queue and print the queue afterwards but that's seems to be a strange way for me.
|
https://www.daniweb.com/programming/software-development/threads/330245/how-to-create-a-simple-elevator-simulation
|
CC-MAIN-2017-51
|
refinedweb
| 969
| 54.83
|
CScrollBarEx is a simple MFC control derived from CWnd, it can display scrollbar max, min, and current value itself.
CScrollBarEx
CWnd
Recently, in one of my projects, I needed one scrollbar control that can display max, min and current val itself. You know, Microsoft's scrollbar control can't display text, so I decided that I would code this control by myself. Now I completed this scrollbar control, and it is not so bad for VC++ beginner, I decided to share this control with all CodeProject workmates. I did not have a lot of time to work on this control, so I had to code it simply, but it satisfied my requirements. It has some features as follows:
Now the scrollbar control is here. Enjoy and please help me with your invaluable notes, bug reports, ideas, etc. that you think might improve the quality of this code.
First we need to create a scrollbar control.
#include " ScrollBarEx.h"
CScrollBarEx
Create
// create scrollbar control
// to get scrollbar control position
CRect rcScrollBar;
CStatic *pStatic = (CStatic *)GetDlgItem(IDC_SCROLLBAR_STATIC);
pStatic->GetWindowRect(rcScrollBar);
ScreenToClient(rcScrollBar);
m_ScrollBarEx.Create(WS_VISIBLE | WS_CHILD, rcScrollBar, this, 2000);
// set max min current val
m_ScrollBarEx.SetScrollBarMinMaxVal(0, 300);
m_ScrollBarEx.SetScrollBarCurVal(100);
// set color
m_ScrollBarEx.SetScrollBarMinMaxValColor(RGB(0, 0, 0));
m_ScrollBarEx.SetScrollBarTextBkColor(RGB(255, 255, 0));
m_ScrollBarEx.SetScrollBarCurValColor(RGB(255, 0, 0));
When moving scrollbar control to any position, scrollbar control's parent window would receive scrollbar control's notify message, you can do like this.
// first declare msg response function in parent window header, under
//}}AFX_MSG and up DECLARE_MESSAGE_MAP(), just like this.
afx_msg LRESULT OnScrollBarMsg(WPARAM wParam, LPARAM lParam);
// second map scrollbar(WM_SCROLLBAR_MSG, OnScrollBarMsg)
END_MESSAGE_MAP()
// finally, code scrollbar msg process function
LRESULT CScrollBarDemoDlg::OnScrollBarMsg(WPARAM wParam, LPARAM lParam)
{
double dblCurVal = *(double *)lParam;
TRACE("ScrollBar Cur Val = %f\n", dblCurVal);
return 0;
}
This scrollbar control is simple. I know that it needs many other functions to complete it, but I had no time, so if you update it, please send an mail to.
|
http://www.codeproject.com/Articles/316142/Text-ScrollBar-Control?msg=4180097
|
CC-MAIN-2014-52
|
refinedweb
| 330
| 55.44
|
Absolute and Relative Imports in Python
In this article, we are going to see that absolute and relative imports in Python.
Working of import in Python
Import in Python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way. Import statement consists of the import keyword along with the name of the module. The import statement involves two operations, it searches for a module and it binds the result of the search to a name in the local scope. When a module is imported, Python runs all of the code in the module file and made available to the importer file. When a module is imported the interpreter first searches it in sys.modules, which is the cache of all modules which have been previously imported. If it is not found then it searches in all built-in modules with that name, if it is found then the interpreter runs all of the code and is made available to the file. If the module is not found then it searches for a file with the same name in the list of directories given by the variable sys.path. sys.path is a variable containing a list of paths that contains python libraries, packages, and a directory containing the input script. For example, a module named math is imported then the interpreter searches it in built-in modules, if it is not found then it searches for a file named math.py in list of directories given by sys.path.
Python3
Output:
3.141592653589793
Syntax of import statements :
Users can import both packages and modules. (Note that importing a package essentially imports the package’s __init__.py file as a module.) Users can also import specific objects from a package or module. There are generally two types of import syntax. When you use the first one, you import the resource directly.
import gfg
gfg can be a package or a module. When a user uses the second syntax, then the user imports the resource from another package or module.
from gfg import geek
geek can be a module, subpackage, or object, such as a class or function.
Styling of import statements
PEP8, the official style guide for python, has a set of rules for how to formulate the python code to maximize its readability. For writing import statements there are some points to follow:
- Imports should always be written at the top of the file, just after any module comments and docstrings.
- Imports should usually be separated by a blank space.
- Imports should be grouped in the following order.
- Standard library imports (Python’s built-in modules)
- Related third party imports.
- Local application/library-specific imports
It is also good to order import statements alphabetically within each import group.
Python3
Absolute vs Relative Imports in Python
Absolute imports in Python
Absolute import involves a full path i.e., from the project’s root folder to the desired module. An absolute import state that the resource is to be imported using its full path from the project’s root folder.
Syntax and Practical Examples:
Let’s see we have the following directory structure:
Here a directory named project, under which two subdirectories namely pkg1, pkg2. pkg1 has two modules, module1 and module2. pkg2 contains three modules, module3, module4, __init__.py, and one subpackage name subpkg1 which contains module5.py. Let’s assume the following:
- pkg1 / module1.py contain a function, fun1
- pkg2 / module3.py contain a function, fun2
- pkg2 / subpkg1 / module5.py contain a function fun3
Python3
In this example, we are importing the modules by writing the full path from its root folder.
Pros and Cons of Absolute imports :
Pros:
- Absolute imports are very useful because they are clear and straight to the point.
- Absolute import is easy to tell exactly from where the imported resource is, just by looking at the statement.
- Absolute import remains valid even if the current location of the import statement changes.
Cons:
If the directory structure is very big then usage of absolute imports is not meaningful. In such a case using relative imports works well.
from pkg1.subpkg2.subpkg3.subpkg4.module5 import fun6
Relative imports in Python
Relative import specifies an object or module imported from its current location, that is the location where import statement resides. There two types of relative imports :
- Implicit relative imports – Implicit relative import have been disapproved in Python(3.x).
- Explicit relative imports – Explicit relative import have been approved in Python(3.x).
Syntax and Practical Examples :
The syntax of relative import depends on the current location as well as the location of the module or object to be imported. Relative imports use dot(.) notation to specify a location. A single dot specifies that the module is in the current directory, two dots indicate that the module is in its parent directory of the current location and three dots indicate that it is in the grandparent directory and so on. Let’s see we have the following directory structure:
Let’s assume the following:
- pkg1 / module1.py contain a function, fun1
- pkg2 / module3.py contain a function, fun2
- pkg2 / subpkg1 / module5.py contain a function fun3
Python3
Pros and Cons of Relative imports :
Pros:
- Working with relative imports is concise and clear.
- Based on the current location it reduces the complexity of an import statement.
Cons:
- Relative imports is not so readable as absolute ones.
- Using relative imports it is not easy because it is very hard to tell the location of a module.
|
https://www.geeksforgeeks.org/absolute-and-relative-imports-in-python/?ref=rp
|
CC-MAIN-2022-40
|
refinedweb
| 951
| 56.05
|
Let’s start with a classical 1st year Computer Science homework assignment: a fibonacci series that doesn’t start with 0, 1 but that starts with 1, 1. So the series will look like: 1, 1, 2, 3, 5, 8, 13, … every number is the sum of the previous two.
In Java, we could do:
public int fibonacci(int i) { if (i < 0) return 0; switch(i) { case 0: return 1; case 1: return 1; default: return fibonacci(i-1) + fibonacci(i - 2); } }
All straight forward. If
0 is passed in it counts as the first element in the series so
1 should be returned. Note: to add some more spice to the party and make things a little bit more interesting I added a little bit of logic to return
0 if a negative number is passed in to our fibonacci method.
In Scala to achieve the same behaviour we would do:
def fibonacci(in: Int): Int = { in match { case n if n <= 0 => 0 case 0 | 1 => 1 case n => fibonacci(n - 1) + fibonacci(n- 2) } }
Key points:
- The return type of the recursive method fibonacci is an
Int. Recursive methods must explictly specify the return type (see: Odersky – Programming in Scala – Chapter 2).
- It is possible to test for multiple values on the one line using the
|notation. I do this to return a 1 for both 0 and 1 on line 4 of the example.
- There is no need for multiple
returnstatements. In Java you must use multiple
returnstatements or multiple
breakstatements.
- Pattern matching is an expression which always returns something.
- In this example, I employ a guard to check for a negative number and if it a number is negative zero is returned.
- In Scala it is also possible to check across different types. It is also possible to use the wildcard
_notation. We didn’t use either in the fibonacci, but just to illustrate these features…
def multitypes(in: Any): String = in match { case i:Int => 'You are an int!' case 'Alex' => 'You must be Alex' case s:String => 'I don't know who you are but I know you are a String' case _ => 'I haven't a clue who you are' }
Pattern matching can be used with Scala Maps to useful effect. Suppose we have a Map to capture who we think should be playing in each position of the Lions backline for the Lions series in Austrailia. The keys of the map will be the position in the back line and the corresponding value will be the player who we think should be playing there. To represent a Rugby player we use a
case class. Now now you Java Heads, think of the case class as an immutable POJO written in extremely concise way – they can be mutable too but for now think immutable.
case class RugbyPlayer(name: String, country: String); val robKearney = RugbyPlayer('Rob Kearney', 'Ireland'); val georgeNorth = RugbyPlayer('George North', 'Wales'); val brianODriscol = RugbyPlayer('Brian O'Driscol', 'Ireland'); val jonnySexton = RugbyPlayer('Jonny Sexton', 'Ireland'); val benYoungs = RugbyPlayer('Ben Youngs', 'England'); // build a map val lionsPlayers = Map('FullBack' -> robKearney, 'RightWing' -> georgeNorth, 'OutsideCentre' -> brianODriscol, 'Outhalf' -> jonnySexton, 'Scrumhalf' -> benYoungs); // Note: Unlike Java HashMaps Scala Maps can return nulls. This achieved by returing // an Option which can either be Some or None. // So, if we ask for something that exists in the Map like below println(lionsPlayers.get('Outhalf')); // Outputs: Some(RugbyPlayer(Jonny Sexton,Ireland)) // If we ask for something that is not in the Map yet like below println(lionsPlayers.get('InsideCentre')); // Outputs: None
In this example we have players for every position except inside centre – which we can’t make up our mind about. Scala Maps are allowed to store nulls as values. Now in our case we don’t actually store a null for inside center. So, instead of null being returned for inside centre (as what would happen if we were using a Java HashMap), the type
None is returned.
For the other positions in the back line, we have matching values and the type
Some is returned which wraps around the corresponding RugbyPlayer. (Note: both
Some and
Option extend from
Option). We can write a function which pattern matches on the returned value from the HashMap and returns us something a little more user friendly.
def show(x: Option[RugbyPlayer]) = x match { case Some(rugbyPlayerExt) => rugbyPlayerExt.name // If a rugby player is matched return its name case None => 'Not decided yet ?' // } println(show(lionsPlayers.get('Outhalf'))) // outputs: Jonny Sexton println(show(lionsPlayers.get('InsideCentre'))) // Outputs: Not decided yet
This example doesn’t just illustrate pattern matching but another concept known as extraction. The rugby player when matched is extracted and assigned to the
rugbyPlayerExt. We can then return the value of the rugby player’s name by getting it from
rugbyPlayerExt. In fact, we can also add a guard and change around some logic. Suppose we had a biased journalist (
Stephen Jones) who didn’t want any Irish players in the team. He could implement his own biased function to check for Irish players
def biasedShow(x: Option[RugbyPlayer]) = x match { case Some(rugbyPlayerExt) if rugbyPlayerExt.country == 'Ireland' => rugbyPlayerExt.name + ', don't pick him.' case Some(rugbyPlayerExt) => rugbyPlayerExt.name case None => 'Not decided yet ?' } println(biasedShow(lionsPlayers.get('Outhalf'))) // Outputs Jonny... don't pick him println(biasedShow(lionsPlayers.get('Scrumhalf'))) // Outputs Ben Youngs
Pattern matching Collections
Scala also provides some powerful pattern matching features for Collections. Here’s a trivial exampe for getting the length of a list.
def length[A](list : List[A]) : Int = list match { case _ :: tail => 1 + length(tail) case Nil => 0 }
And suppose we want to parse arguments from a tuple…
def parseArgument(arg : String, value: Any) = (arg, value) match { case ('-l', lang) => setLanguage(lang) case ('-o' | '--optim', n : Int) if ((0 < n) && (n <= 3)) => setOptimizationLevel(n) case ('-h' | '--help', null) => displayHelp() case bad => badArgument(bad) }
Single Parameter functions
Consider a list of numbers from 1 to 10. The filter method takes a single parameter function that returns
true or
false. The single parameter function can be applied for every element in the list and will return
true or
false for every element. The elements that return
true will be filtered in; the elements that return
false will be filtered out of the resultant list.
scala> val myList = List(1,2,3,4,5,6,7,8,9,10) myList: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> myList.filter(x => x % 2 ==1) res13: List[Int] = List(1, 3, 5, 7, 9)
Now now now, listen up and remember this. A pattern can be passed to any method that takes a single parameter function. Instead of passing a single parameter function which always returned true or false we could have used a pattern which always returns true or false.
scala> myList.filter { | case i: Int => i % 2 == 1 // odd number will return false | case _ => false // anything else will return false | } res14: List[Int] = List(1, 3, 5, 7, 9)
Use it later?
Scala compiles patterns to a
PartialFunction. This means that not only can Scala pattern expressions be passed to other functions but they can also be stored for later use.
scala> val patternToUseLater = : PartialFunction[String, String] = { | case 'Dublin' => 'Ireland' | case _ => 'Unknown' }
What this example is saying is
patternToUseLater is a partial function that takes a string and returns a string. The last statemeent in a function is returned by default and because the case expression is a partial function it will returned as a partial function and assigned to
pattenrToUseLater which of course can use it later.
Finally, Johnny Sexton is a phenomenal Rugby player and it is a shame to hear he is leaving Leinster. Obviously, with Sexton’s busy schedule we can’t be sure if Johnny is reading this blog but if he is, Johnny sorry to see you go we wish you all the best and hopefully will see you back one day in the Blue Jersey.
Reference: Scala pattern matching: A Case for new thinking? from our JCG partner Alex Staveley at the Dublin’s Tech Blog blog.
java code for foolowing patttern
*
* * *
* * * * *
* * *
*
|
http://www.javacodegeeks.com/2013/01/scala-pattern-matching-a-case-for-new-thinking.html
|
CC-MAIN-2015-06
|
refinedweb
| 1,365
| 60.75
|
I am looking for a solution for copying all the files from a specific directory on the hard drive, to a specific directory on a USB memory device, once this device is connected.
I have a program that downloads podcast episodes for me.
I would like these files to be automatically moved (or at least copied) to my mp3 player once I connect it to the computer.
I have both windows xp and linux machines, so a solution for any of them will work for me.
Edit: it turns out SyncBack SE has a trigger action:
Open Profile, go to “When” tab, then
“Insert”. It lets you specify by drive
letter, label, or serial number.
Open Profile, go to “When” tab, then
“Insert”. It lets you specify by drive
letter, label, or serial number.
However the SE version is not free and Windows only (I think)
Or you could try adding an Autorun event for your syncing program (example for SyncToy) using TweakUI
Click apply.
Now plug in your pen drive.
I can't seem to find any (other) program that will start automatically when you connect your USB device.
They all rely on scheduling to start syncing. You could decide to have it scheduled every our, it will simply fail if the USB device is not connected and run if it is.
But too be honest it would be easier if you simply clicked on the sync button, you have to plug in your USB device manually as well.
Anyway I also found a synchronization tool that runs on both Linux and Windows: DirSync Pro which is completely free, runs on Java and has a nice GUI:
* Synchronization
o Powerful synchronization algorithm.
o Bidirectional (Two way) and Unidirectional (One way) synchronization mode.
o Option for various behavior of conflict resolution for Bidirectional Synchronization.
o Synchronizes unlimited number of folders.
o Large number of options to change the synchronization behavior.
o Option to synchonise subdirectories recursively.
o Synchronizes files/folders any file system (FAT, FAT16, FAT32, NTFS, WinFS, UDF, Ext2, Ext3, ...).
o Synchronizes files from/to network drives
o Synchronizes files from/to any mounted devices (Harddisks, USB-Sticks, Memory cards, External drives, CD/DVD's, ...).
o Synchronization could be used for making incremental backups.
o Option to create up to 50 backups from the modified/changed files before synchronization.
o Option to define a backup folder.
o Option for handling symbolic links.
o Option for handling time-stamps.
* General
o Easy, clear and user-friendly graphical user interface, no unnecessary gadget you never use.
o Runs on every modern operating system including Windows™, Linux™ and Macintosh™
o It is Portable! It does not need any installation. Just run the application!
o Open source, it is 100% free of charge, 100% free of commercial text, 100% free of advertisements and 100% free of spyware.
o No time/function limitations
o Uses no local database, so no overhead
o Does not need any installation. Just download and run it. You can put it on you USB-stick en you can run it on any computer/any platform.
* Logging
o Advanced logging/reporting facilities. Just select a log level and define where to write the log.
o Option to log on application level (default log)
o Option to log on each directory level (dir log)
o Option to define the log leven (how much to log)
You can quite easily build your own solution for Windows using autorun.inf and a .bat file.
Create a bat file to copy a directory to your usb drive.
xcopy /e /y c:\podcasts\*.* .\dir_on_usb_drive
Place the bat file on your mp3 player and create an autorun.inf using these instructions
Now you should have your own homebuilt solution to your problem but it's certainly possible that there's pre-made solutions out there :)
For Linux:
If you don't mind a little Python scripting you could write a daemon that listens to HAL for events and then launches a script once a device of your choice has been plugged in. An example script would look like this:
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import dbus
import dbus.service
if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
import dbus.glib
import gobject
import sys
import os
class DeviceManager:
def __init__(self):
self.bus = dbus.SystemBus()
self.bus.add_signal_receiver(self.device_added,
'DeviceAdded',
'org.freedesktop.Hal.Manager',
'org.freedesktop.Hal',
'/org/freedesktop/Hal/Manager')
self.bus.add_signal_receiver(self.device_removed,
'DeviceRemoved',
'org.freedesktop.Hal.Manager',
'org.freedesktop.Hal',
'/org/freedesktop/Hal/Manager')
def udi_to_device(self, udi):
return self.bus.get_object("org.freedesktop.Hal", udi)
def device_added(self, udi):
print 'Added', udi
properties = self.udi_to_device(udi).GetAllProperties()
if properties.get('info.category') == u'volume':
label, dev = properties.get('volume.label'), properties.get('block.device')
print 'Mounting %s on /media/%s' %(dev, label)
os.system('pmount %s /media/%s' %(dev, label))
def device_removed(self, udi):
print 'Removed', udi
if __name__ == '__main__':
m = DeviceManager()
mainloop = gobject.MainLoop()
try:
mainloop.run()
except KeyboardInterrupt:
mainloop.quit()
print 'Exiting...'
sys.exit(0)
You just have to modify the device_added() function to limit it to the specific device and replace the os.system() call with your custom script.
device_added()
os.system()
For limiting it to the drive the volume.uuid property could be used and a full list of available properties can be displayed with the hal-device program.
volume.uuid
hal-device
To start the daemon on boot, just start it from /etc/rc.local.
/etc/rc.local
I use a replicator program from Karenware. She's the author of a lot of small useful programs for Windows (think PowerToys from the early W98/W2K/XP days).
Here's the link.
Set it up on a nightly schedule. If the USB drive is plugged in, it will sync the download folder with the USB contents.
It's free!
Windows 7 and autosync to your flash/USB device on insert!
Download SyncToy and establish your folder pairing and sync name("SyncTest")
see: How-to: Using SyncToy to make a nightly mirror of My Documents
You can run the task right from Task Scheduler to verify it works. Now the only other problem I had was running my laptop on batteries, in Task Manager under the conditions tab, uncheck "Start the task only if the computer is on AC power", otherwise task will only run when AC is plugged in.
Also, as USB polls and disconnects/reconnects, this task will run every couple of minutes, actually kinda cool, it's auto-syncing to the USB HDD all the time :)
I tried Steven's method, but the USB event wasn't showing up in "Event Viewer/Windows Logs/System" (I'm using Windows 7). I poked around a bit, and found out the USB insertion events are located in "Event Viewer/Applications and Services Logs/Microsoft/Windows/DriverFrameworks-UserMode/Operational". Try clearing the log first (just to make it easier to find the event you want), then insert the USB flash drive. Refresh the log, and a bunch of events should show up. I picked the top most event (i.e. the most recent), and assigned the task to that (make sure the event description looks like it has something specific to the particular USB drive you inserted).
I used the free SyncBack program to do the actual syncing. Works great!
I just use a AUTORUN.INF with a few batches to sync key folders. Very simple very effective.
Also, if you have a read only,archived autorun.inf file its hard contract usb-stick virus's
Under Linux, instead of having a program running continuously to listen for events, you can use the already running ones. You can add some hooks to udev that mounts the device to a temporary location and then launches rsync to synchronize a bunch of directories.
By the way you can define specific actions according to your device signature: synchronize your work documents when a specific key is inserted, or your music if a USB mass storage MP3 player is inserted, or your books when plugging a Kindle there.
You are simply just forgetting to "" and end ".\dectory\" ← That end \ slash as well.
""
".\dectory\"
\
The original batch formula works, It is just now days, There are a lot of spaces in directories, batch files and command prompt HATE those.
How mine looks:
xcopy "F:\Web Stuff\Web Dev\Dev_FactorY Designs\*.*" ".\HTML_PROJ\Web Stuff\Web Dev\Dev_FactorY Designs\" /e /y
This is an old thread, but I thought I would pu this here for anyone who wants it. Change the relevant information to suit your needs then it'll do it all for you. Credit to who made the first iteration of this.
@echo off
cls
echo waiting
goto check
Change the STUFF TO COPY location to the folder that you want
everything inside to be send to the usb's, and change the 3 instances of
G: to whatever drive letter that the USB uses.
Good Luck!
:start
set choice=
robocopy "C:\STUFFTOCOPY" "G:" /E
echo Waiting for removal
goto wait
:check
timeout /t 1 /nobreak >nul
if exist "G:" (goto start) else goto check
:wait
timeout /t 1 /nobreak >nul
if exist "G:" (goto wait) else (
echo removed
echo waiting
goto check
)
By posting your answer, you agree to the privacy policy and terms of service.
asked
4 years ago
viewed
46962 times
active
3 months ago
|
http://superuser.com/questions/22766/how-can-i-automatically-copy-files-to-a-usb-drive-when-i-connect-it-to-my-comput?answertab=oldest
|
CC-MAIN-2014-10
|
refinedweb
| 1,570
| 64.81
|
engineer
twitter
Reddit
Topics
No topic found
Content Filter
Articles
Videos
Blogs
News
Complexity Level
Beginner
Intermediate
Advanced
Refine by Author
[Clear]
Ajay Yadav (11)
Vijay Prativadi (8)
Allen O'neill (4)
Mahesh Chand (3)
Gul Md Ershad (3)
Afzaal Ahmad Zeeshan (3)
Sagar Lad (2)
Ojash Shrestha (2)
C# Corner Live (2)
Nilesh Jadav (2)
Sibeesh Venu (2)
Srinivasan Ramamoorthi (1)
David Mccarter (1)
Henk Boelman (1)
Mithun Pattankar (1)
Pratiksha R (1)
Manikanta Pattigulla (1)
Amit Choudhary (1)
Saurabh Tyagi (1)
Dominique Ceja (1)
Pratik Chakraborty (1)
Manali Dangda (1)
Matthew Cochran (1)
Divya Saxena (1)
Manikavelu Velayutham (1)
Nipun Tomar (1)
Tamer Khalil (1)
Wolfgang Pleus (1)
Related resources for engineer
No resource found
Need For Site Reliability Engineering
9/26/2021 8:28:08 AM.
This article explains the Site Reliability Engineering, principles, and practices.
Security As A Service For Cloud Computing
8/30/2021 4:32:26 AM.
In this article, we are going to explore about potential security threats while working with Cloud computing.
Ingest Data To Azure SQL Database Using Azure Databricks
8/16/2021 2:02:09 PM.
In this tutorial, We are going to discuss about how to connect to Azure SQL Database using Azure Databricks.
Common Software Engineering Practices For Production Code
7/2/2021 4:55:46 PM.
In this article, we’ll learn about various software engineering practices common in software industry today. This will help improve the standard of code, code quality and practices which will enable d
Why Do AI Engineers Need Calculus
5/8/2021 7:16:28 AM.
This articles describes Calculus in detail and explains how AI Engineers can benefit by understand Calculus to its depth.
Understanding User and User Requirements - Build Better Software Ep. 2 (Growth Mindset)
4/17/2021 6:13:14 PM.
Join us with Mahesh Chand and Andy Schwam for the new episode of Growth Mindset Weekly Live Show focused on "Build Better Software Ep. 2 - Understanding User and User Requirements".
Building Better Software Ep.1
4/12/2021 2:52:10 PM.
Welcome to the first episode of the Building Better Software Series.
Testing Software Engineers During An Interview; There Is A Better Way!
4/2/2021 1:59:01 PM.
In this article, you will learn about testing software engineers during an interview; there is a better way!
A bit of AI - Episode 4
4/1/2021 2:36:12 PM.
This week we will have a chat with Jernej Kavka.
Extreme .NET Reverse Engineering: Part 5
2/3/2021 6:52:33 AM.
In this article, we have seen how to obtain sensitive information without having access to real source code, including how to manipulate IL code to do that.
MSIL Programming: Part 2
2/3/2021 5:51:35 AM.
The primary goal of this article is to exhibit the mechanism of defining (syntax and semantics) the entire typical Object Oriented Programming “terms” like namespace, interface, fields, class and so o
Bug Fixing: .NET Reverse Engineering: Part 4
12/31/2020 11:40:57 AM.
We shall explore round-trip engineering, one of the most advanced tactics to disassemble IL code to do Reverse Engineering in the context of existing .NET built software applications.
Applied Reverse Engineering With OllyDbg
12/30/2020 7:25:03 AM.
The objective of this paper is to show how to crack an executable using the OllyDbg tool without seeing its source code.
Anti-Reverse Engineering (Assembly Obfuscation)
12/7/2020 3:24:22 AM.
The modus operandi of this paper is to demystify the .NET assembly obfuscation as a way to deter Reverse Engineering.
.NET Binary Reverse Engineering: Part 1
12/7/2020 2:08:06 AM.
The prime objective of this article is to explain the .NET mother language called Common Instruction Language (CIL) that has laid the foundation of .NET.
Applied Reverse Engineering With IDA Pro
12/3/2020 6:24:58 AM.
In this article you will learn Live Binary Sample Target, Target Analysis with IDA Pro, cracking the Target and an alternative way of tracing.
Bypassing Obfuscation: Ciphered Code Reverse Engineering
12/3/2020 5:28:36 AM.
In this article, we have performed reverse engineering over a protected binary by deep analysis of both obfuscated source code and MSIL assembly code.
What Are Cloud Functions And Why Are They Important?
6/4/2020 1:37:36 AM.
A look at the extraordinary new concept of cloud functions.
How To Become A Blockchain Developer
5/29/2020 12:22:08 AM.
Blockchain developers are in demand. Do you want to become a blockchain developer. Learn what skills do you need to become a blockchain developer.
How To Reverse Engineer Using Advanced Apk Tool
3/2/2020 3:02:11 AM.
In this article, you will learn how to reverse engineer using advanced apk Tool.
Java Bytecode Reverse Engineering
9/27/2019 5:06:56 PM.
This paper explaines the mechanism of disassembling Java byte code in order to reveal sensitive information when the source of the Java binary is unavailable. We have come to an understanding of how t
Creating POCO Class Library Using Reverse Engineering
1/31/2019 8:51:14 AM.
In this article, we will learn how to create a POCO class library by the reverse engineering technique using EF Core Power Tools in Visual Studio 2017.
Salary of a blockchain developer
1/6/2019 11:12:59 PM.
Blockchain developers are one of the highest-paid developers. This article talks about blockchain developer salaries. Salary of a blockchain engineer, salary of a blockchain architect.
How Many Blockchain Jobs Are There?
11/25/2018 10:53:34 PM.
Today, there are more than 4,000 companies that are involved in blockchain development. Blockchain jobs are growing and by 2020, there will be more blockchain jobs including blockchain architect, bloc
How To Reverse Engineer Using OllyDbg
9/20/2018 3:52:56 AM.
How to Reverse Engineer using OllyDbg. To start with obfuscate, we are taking one reverse engineering tool, which is OllyDbg. The other aspect of this is how to reverse engineer any EXE to crack the Hack Productivity - The Engineering Way!
7/5/2018 9:08:31 AM.
The IT industry is known for high pressure and constant change. It hard to keep up with things at the best of times, so its important for us to be as productive as possible, especially when the pressu.
A Day With A Software Engineer Who Changes Text Labels Only
6/16/2017 3:45:07 PM.
This article will explain the way Software Engineers, who never focus on technical learning and remain busy in text label changing only.
Developer Survey 2017
3/25/2017 11:22:39 AM.
A run-through the Stack-Overflow Annual Developer survey..
Understanding Build Aftermath in Visual Studio Team Services
11/25/2016 1:23:01 AM.
In this video I walk the viewer through the aftermath of the build process, to understand the results of build and to download the executable binaries.
Visual Studio Team Services - Introduction
11/25/2016 1:09:39 AM.
In this video I provide the basic overview of Visual Studio Team Services for beginners.
Customize Reverse Engineer Code First - EF Power Tool Enhancement
3/8/2016 9:24:22 AM.
In this article you will learn how to customize reverse engineer code first .
Why Engineering Is Still The Best Bet As A Career In India
3/7/2016 2:44:40 PM.
In this article you will see why engineering is still the best bet as a career in India.
Office 365 Video Portal - SharePoint Engineering
6/5/2015 1:55:27 AM.
Here I explain the SharePoint engineering decisions in the scope of SharePoint Online that were implemented to deliver the NextGen Office 365 Video Portal.
Dependency Injection In Software Engineering
4/2/2015 3:02:15 PM.
In this article we will learn about Dependency Injection which is a software design pattern that implements inversion of control.
Jabalpur Chapter Meet Official Recap: 19 July, 2014
7/23/2014 12:44:52 AM.
Jabalpur Chapter Meet was organized on 19 July, 2014 at Shri Ram Engineering College (SRIT) for the professionals and students..
Insert and Select Data in Reverse Engineering POCO Generator
2/18/2013 3:03:50 PM.
This article demonstrates an interesting and very useful concept in Entity Framework.
Delete and Update Data in Reverse Engineering POCO Generator
2/18/2013 2:54:05 PM.
This article demonstrates an interesting and very useful concept in Entity Framework.
Select and Insert Data With Entity State (Unchanged) Via EDF Framework
12/31/2012 4:41:53 PM.
Today, in this article let's play around with one of the interesting and most useful concepts in EDM Framework.
Insert Data With Raw SQL Query Via EDF Framework
12/31/2012 12:27:14 AM.
Today, in this article let’s play around with one of the interesting and most useful concepts in EDM Framework.
Delete Stored Proc With Raw SQL Query Via EDF Framework
12/29/2012 12:40:30 PM.
Today, in this article let’s play around with one of the interesting and most useful concepts in EDM Framework.
Update Data With Reverse Engineering Via EDM Framework
12/29/2012 12:38:25 PM.
Today, in this article let’s play around with one of the interesting and most useful concepts in EDM Framework.
Delete Data With Reverse Engineering Via EDM Framework
12/29/2012 12:36:48 PM.
Today, in this article let’s play around with one of the interesting and most useful concepts in EDM Framework.
Select and Insert Data With Reverse Engineering Via EDM Framework
12/21/2012 12:34:25 PM.
Today, in this article let’s play around with one of the interesting and most useful concepts in EDM Framework.
Basics of Software Testing
9/29/2012 6:23:48 AM.
Introduces the basics of Software Testing
Performance Engineering Tools
5/15/2012 4:54:42 PM.
In this article let’s discuss various tools that help to analyze performance issues in web applications..
|
https://www.c-sharpcorner.com/topics/engineer
|
CC-MAIN-2021-49
|
refinedweb
| 1,690
| 57.06
|
Is it possible to have a regular expression which replaces "I" with "you" and "you" with "I"?
If so, please could someone show me an expression? Do I need extra Matcher code, rather than a single regex string?
(I'm desperatly trying to learn regex, but all the resources I find on Google seem to teach it as though you already know it...)
I'm looking for something in this format:
String s = "I love you";
String pattern = "???";
String replacement = "???";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(s);
String newString = m.replaceAll(replacement);
System.out.println(newString);
Quick and dirty, just so you get the idea. But you may need to improve it to make more robust...
public class IdentityCrisis { public static void main( String[] args ) { String dilemma = "I know you want me to be something I don't want to be unless you prove me it is OK"; System.out.println( dilemma.replaceAll("I", "y-o-u") .replaceAll("you", "I") .replaceAll("y-o-u", "you") ); } }
|
https://codedump.io/share/bEZ9C3K529r8/1/replacing-different-substrings-using-regex
|
CC-MAIN-2017-04
|
refinedweb
| 168
| 66.44
|
This section only describes the rules for XML
resources. Rules for
text/html resources are discussed
in the section above entitled "The HTML syntax".
Status: Last call for comments
').
Status: Last call for comments Core in inserted into a document
or has its attributes set. [XML] [XMLNS] [DOMCORE]
[DOMEVENTS]
Between the time an element's start tag is parsed and the time either the element's end tag is parsed on the parser detects a well-formedness error, the user agent must act as if the element was in a stack of open elements.
This is used by the
object element to
avoid instantiating plugins before the
param element
children have been parsed..]
When an XML parser creates a
script element, it must be marked as being
"parser-inserted". If the parser was originally
created for the XML fragment parsing algorithm, then
the element must be marked as "already started"
also. When the element's end tag is parsed, the user agent must
run the
script
element. If this causes there to be a pending parsing-blocking
script, then the user agent must run the following steps:
Block this instance of the XML parser, such that the event loop will not run tasks that invoke it.
Spin the event loop until there is no style sheet.
For the purposes of conformance checkers, if a resource is determined to be in the XHTML syntax, then it is an XML document.
Status: Last call for comments
The XML fragment serialization algorithm for a
Document or
Element node either returns a
fragment of XML that represents that node or raises child nodes, in tree order. User agents
may adjust prefixes and namespace declarations in the serialization
(and indeed might be forced to do so in some cases to obtain
namespace-well-formed XML). User agents may use a combination of
regular text, character references, and CDATA sections to represent
text nodes in the DOM (and indeed
might be forced to use representations that don't match the DOM's,
e.g. if a
CDATASection node contains the string "
]]>").
For
Elements, if any of the elements in the
serialization raise an
INVALID_STATE_ERR exception instead of returning a
string:
Documentnode with no child element nodes.
DocumentTypenode that has an external subset public identifier that contains characters that are not matched by the XML
PubidCharproduction. [XML]
DocumentTypenode that has an external subset system identifier that contains both a U+0022 QUOTATION MARK (") and a U+0027 APOSTROPHE ('),
CDATASectionnode,
Commentnode, or
ProcessingInstructionnode whose data contains characters that are not matched by the XML
Charproduction. [XML]
Commentnode whose data contains two adjacent U+002D HYPHEN-MINUS characters (-) or ends with such a character.
ProcessingInstructionnode whose target name is an ASCII case-insensitive match for the string "
xml".
ProcessingInstructionnode whose target name contains a U+003A COLON (:).
ProcessingInstructionnode whose data contains the string "
?>".
These are the only ways to make a DOM
unserializable. The DOM enforces all the other XML constraints; for
example, trying to append two elements to a
Document
node will raise a
HIERARCHY_REQUEST_ERR exception.
Status: Last call for comments
The XML fragment parsing algorithm for either returns
a
Document or raises a
SYNTAX_ERR
exception. Given a string input and an optional
context element context, the algorithm is as
follows:
Create a new XML parser.
If there is a context element, feed the parser just created the string corresponding to the start tag of that element, declaring all the namespace prefixes that are in scope on that element in the DOM, as well as declaring the default namespace (if any) that is in scope on that element in the DOM.
A namespace prefix is in scope if the DOM Core
lookupNamespaceURI() method on the element would
return a non-null value for that prefix.
The default namespace is the namespace for which the DOM Core
isDefaultNamespace() method on the element
would return true.
If there is a context element,
no
DOCTYPE is passed to the parser, and
therefore no external subset is referenced, and therefore no
entities will be recognized..
|
http://www.w3.org/TR/2010/WD-html5-20100624/the-xhtml-syntax.html
|
CC-MAIN-2014-35
|
refinedweb
| 673
| 50.06
|
Hello, Ingo.On 03/16/2010 03:17 PM, Ingo Molnar wrote:> ( /me mumbles something about not having a patch in the email to review and> pulling the tree. 200k patch is just fine for lkml - i've attached it below> for easier review. percpu.h and percpu.c has the meat of the changes. )I wanted to keep the discussion high level while giving a general ideaabout the extent of necessary changes. I'll include the patch fromnow on.> i like the dependency reduction. Noticed one small detail:> > this new 2000-lines #ifdef block percpu.c:> > +#ifdef CONFIG_SMP> +#else /* CONFIG_SMP */> +#endif /* CONFIG_SMP */> > feels a bit lame. A separate percpu_up.c file would be nicer i suppose?Sure.> Also, why should we make this opt-in and expose a wide range of configs to > build breakages? A more gradual approach would be to write a simple script > that adds a slab.h include to all .c's that include percpu.h, directly or > indirectly.>> You can map the pattern experimentally: the insertion pattern could be built > from the x86 allmodconfig build you did [i.e. extend the pattern until you > make it build on allmodconfig] - that would cover most cases in practice (not > just allmodconfig) - and would cover most architectures as well.I don't really get the 'experimental' part but if I count all thefiles which ends up including percpu.h directly or indirectly onallmodconfig it ends up including much more .c files than necessasry -11203 to be exact, ~20 times more than necessary. Inclusions from .cfiles definitely are much less troublesome so the situation would bebetter than now but we'll still end up with a LOT of bogus inclusionswithout any good way to eventually remove them.Maybe a better way is to grab for slab API usages in .c files whichdon't have slab.h inclusion. If breaking the dependency is the way togo, I can definitely write up some scripts and do test builds on somearchs. There sure will be some fallouts but I think it won't be toobad.Thanks.-- tejun
|
http://lkml.org/lkml/2010/3/16/39
|
CC-MAIN-2014-52
|
refinedweb
| 346
| 67.45
|
Videos | Most Viewed | Most Discussed
[TRANSLATED] Roxanne's Profile (freestyle) - ...
[TRANSLATED] Roxanne's Profile (freestyle) - Roxanne Shante-1985
1985 off the head freestlye recording from roxanne shante'off of the round 1 ep. t...
6 months ago 1,009 views hundredthough
[TRANSLATED] Romeo Part 1 - The Real Roxanne ...
[TRANSLATED] Romeo Part 1 - The Real Roxanne & Howie Tee
80's jam from the real roxanne and her dj howie tee
7 months ago 4,125 views hundredthough
[TRANSLATED] Runaway- Roxanne Shante'-1985
[TRANSLATED] Runaway- Roxanne Shante'-1985
1985 freestyled message jam to the youth from 15 year old roxanne shante and dj/pr...
8 months ago 3,413 views hundredthough
[TRANSLATED] Def Fresh Crew - Roxanne Shante'...
[TRANSLATED] Def Fresh Crew - Roxanne Shante' & Biz Markie-1986
def fresh crew- 1986 freestyle from roxanne shante and biz markie
8 months ago 8,302 views hundredthough
[TRANSLATED] Roxanne's Revenge (Original-Stre...
[TRANSLATED] Roxanne's Revenge (Original-Stree t Version)
The notorious one-take, on the spot, improvised recording that took place in the ...
9 months ago 20,820 views hundredthough
[TRANSLATED] Round 1 - Roxanne Shante' vs. Sp...
[TRANSLATED] Round 1 - Roxanne Shante' vs. Sparky Dee
Two great emcees going head to head in this classic recorded battle from 1985. FYI...
9 months ago 10,858 views hundredthough
[TRANSLATED] Queen of Rox (Shante' Rox On)-Ro...
[TRANSLATED] Queen of Rox (Shante' Rox On)-Roxanne Shante'
Radio version of second freestyle recording from Roxanne Shante'. She tells us how...
9 months ago 5,838 views hundredthough
[TRANSLATED] Roxanne Shante' - "Aint No B!tch...
[TRANSLATED] Roxanne Shante' - "Aint No B!tch ..."
Legendary battle MC Roxanne Shante' sets the record straight at rap show
1 year ago 8,890 views hundredthough
[TRANSLATED] Roxanne Kicks Big Mama Part 2
[TRANSLATED] Roxanne Kicks Big Mama Part 2
ends with a freestyle
2 years ago 3,968 views hundredthough
[TRANSLATED] Sparky D - Sparky's back
[TRANSLATED] Sparky D - Sparky's back
1987 Album: B-Girls live and kickin' on B-Boy records
2 months ago 95 views cutfactaselecta
[TRANSLATED] Boogie Down Productions - 100 Guns
[TRANSLATED] Boogie Down Productions - 100 Guns
Nice joint from BDP. Ja Rule used changed chorus of that song in his hit "New York"
1 year ago 9,127 views MiChAlThEKliKKKeR
[TRANSLATED] Cut Master D.C.- Brooklyn's In T...
[TRANSLATED] Cut Master D.C.- Brooklyn's In The House
1985 Zakia Records. The Brooklyn Anthem! New York Old School Rap!
[TRANSLATED] GIGOLO TONY & LACE LACEY - THE P...
[TRANSLATED] GIGOLO TONY & LACE LACEY - THE PARENTS OF ROXANNE
1985 4 SIGHT RECORDS.
4 months ago 453 views beatsanddance
[TRANSLATED] Roxanne Shante's PHD
[TRANSLATED] Roxanne Shante's PHD
4 months ago 127 views Superbizzee
[TRANSLATED] Nice & Smooth DWYCK @ Hip-Hop Le...
Nice & Smooth Performs DWYCK @ BB Kings Blues Club Hip-Hop Legens Concerts Series...
3 weeks ago 88 views itsphototime
[TRANSLATED] Showbiz & A.G. SoulClap Hip-Hop ...
Showbiz & A.G. Performs SoulClap @ BB Kings Blues Club Hip-Hop Legens oncerts Seri...
3 weeks ago 49 views itsphototime
[TRANSLATED] Roxanne Shanté And Biz Markie Li...
Roxanne Shanté And Biz Markie Live 1986 (Rap, Hip Hop, Hiphop, Human Beatbox)
2 months ago 488 views realhiphop3000
[TRANSLATED] Sparky D ceder park
[TRANSLATED] Sparky D ceder park
Legendary Sparky D visits the Bronx.
2 years ago 1,166 views joyforever2
|
http://www.youtube.com/hundredthough
|
crawl-002
|
refinedweb
| 548
| 71.95
|
Contents
The Chromium project has an general utility library referred to as libbase:
Because it is standalone and does not depend on any other parts of Chromium, it has been been picked up by other Google related projects so people don't have to reinvent these things.
Along those lines, a package in Chromium OS is provided so that projects specific to us can share the code without having to bundle it multiple times over. Currently, there are over 20 such projects in Chromium OS. To keep people on their toes, the package is named "libchrome" as "libbase" by itself is too confusing. Granted, "libchrome" isn't exactly clear itself, but it's a lose-lose situation, and we tried our best. Please still love us.
Note: If your package is integrated into the platform2 ebuild, then this is already handled for you in the common platform2 ebuild and you can skip this section.
There are 4 things to make sure the ebuild does when building a Chromium OS package that uses libchrome:
Below you can find copy & paste snippets that should work for any ebuild in the Chromium OS tree. All you should need to change is the "125070" as the number is updated.
...
inherit cros-debug
...
LIBCHROME_VERS="125070"
...
RDEPEND="chromeos-base/libchrome:${LIBCHROME_VERS}[cros-debug=]"
...
src_compile() {
...
tc-export PKG_CONFIG
cros-debug-add-NDEBUG
export BASE_VER=${LIBCHROME_VERS}
...
}
If your package has been upgraded to platform2 (if not, why not?), then it's simple. In your package's gyp file, you will want to:
{
'variables': {
'libbase_ver': 242728,
... other variables you might have ...
},
... the rest of your gyp file ...
}
...
{
'target_name': 'list_proxies',
'type': 'executable',
'variables': {
'deps': [
'libchrome-<(libbase_ver)',
... any other deps you have ...
],
...
...
{
'target_name': 'crash_reporter',
'type': 'executable',
'dependencies': [
'../libchromeos/libchromeos-<(libbase_ver).gyp:libchromeos-<(libbase_ver)',
'../metrics/libmetrics-<(libbase_ver).gyp:libmetrics-<(libbase_ver)',
... any other deps you have ...
],
...
In a standard common.mk Chromium OS platform project, you can use these snippets in your Makefile:
# If the build env has exported $PKG_CONFIG to a wrapper, use that, else use
# the default pkg-config wrapper (so we can `make` in place for testing).
PKG_CONFIG ?= pkg-config
# If the build env has exported $BASE_VER, use that. Else, use the last version
# that we tested against. This allows the ebuild to update to a newer version
# without having to explicitly update the source build system for trivial changes.
BASE_VER ?= 125070
# You can add as many or as view pkg-config libraries to this PC_DEPS value.
# Here we just use a specific version of libbase.
PC_DEPS = libchrome-$(BASE_VER)
# Look up the compiler flags and linker settings via the pkg-config wrapper
# once. That is why we use a dedicated variable and the := operator -- if
# we use =, then make will end up executing the pkg-config wrapper many times.
PC_CFLAGS := $(shell $(PKG_CONFIG) --cflags $(PC_DEPS))
PC_LIBS := $(shell $(PKG_CONFIG) --libs $(PC_DEPS))
In your source, include files from base/ like normal. So if you want to use the string printf API, do:
#include <base/stringprintf.h>
Over time, we've evolved how we package up the base source tree. Here we'll cover the lessons we've learned, and why we do the things that we do. This way future decisions can take into consideration all the factors without missing something.
For some more background (and specifics), see this thread:
The first iteration involved creating a single libbase.a from a single version of Chromium (and install headers into /usr/include/base/). Then anyone who wanted to use this code base would link with -lbase and include <base/foo.h>.
The advantages here:
Unfortunately, as it was widely deployed, we hit scaling issues:
The first few points were annoying, but bearable. The latter points (related to upgrading), however, were not. So we embarked on a search for a solution!
Since static libraries we so trivial to throw together, we tried to expand on this concept. Now, rather than installing libbase.a, we would install libbase-<version>.a and /usr/include/base-<version>/base/. Then projects would be built & linked against a specific version of libbase by using e.g. -lbase-85268 and compiled against a matching set of headers by using e.g. -I/usr/include/base-85268.
The advantages over a single static library:
However, after building & testing this prototype, we hit problems that were non-starters for deploying related to libraries. When a Chromium OS shared library (e.g. libmetrics) links against a specific libbase version, it turns around and exports the symbols from that version. So when linking an application against a different version of libbase, and that shared library, we cannot guarantee that the ABI between the two versions are the same. While the compile might have been clean, we don't know if the runtime will be clean, and the behavior could change depending on the link order (-lbase-### -lmetrics vs -lmetrics -lbase-###). This could easily lead to hard to debug and understand crashes or misbehavior at runtime.
We could say that the shared library would clean up its exported ABI by never exporting any libbase symbols (which would be a good thing regardless), but the resulting system is still unmanageable. Since linking against the static library pulls in both functions and state, and some of the APIs from libbase have initialization functions (such as the logging framework which sets up message headers, files, and maintains a buffer), libmetrics now has its own copy of the logging code, and the end application has its own copy of logging code. When the application initializes the logging framework, it initializes its own logging state, not libmetrics' logging state. So when libmetrics attempts to do logging of its own, it often times will crash as its logging state is uninitialized. We could add initialization functions to libmetrics so that it too would initialize its own libbase state, but now we have two parallel logging functions at runtime which could be clobbering the external state (e.g. files).
Similar complications come up when using static libraries that themselves use libbase. If libmetrics was built against libbase-1234, and another project was built against libbase-5678, they'll want different functions at link time which can lead to symbol clashing leading either to link time failures or runtime failures (as detailed above).
This is all fairly fragile, and is arguably trading one set of problems (hard to build & upgrade) for a different, and perhaps even worse, set of problems (things are easy to build & upgrade, but hard to run & debug). We can do better, so let's think harder.
Since the slotted aspect of the previous proposal got us the upgrade path that we desired, we now just have to solve the duplicate state problem. That could be done by only using shared libraries with libbase -- there's no chance to have multiple states be linked in as there are no static archives anymore. Now instead of providing libbase-<version>.a, we provide libbase-<version>.so. The other aspects of the previous proposal are the same (include paths, as well as compiling and linking flags).
It's not all peaches & apple pie though -- there are some trade-offs here:
The last point here is the only real show stopper. Fortunately, two things work in our favor. Generally, the ABI is stable with libbase (across the version ranges we upgrade between), so the runtime "mostly works". This means we can tolerate a period of time where we are upgrading to a newer version of libbase but some applications are actually (runtime) linked against multiple versions. By the time we actually release, the upgrade will have completed, so there will once again only be one version live at a time. Further, since we can detect exactly what versions of a library an ELF has been linked against, we can confidently detect the cases where a program uses one version of libbase, but links against a shared library which pulls in a different one and act appropriately (i.e. update all the packages).
At this point, we have a workable solution. But we can still do better. Onwards!
Since we need to change all projects that use libbase (from -lbase to -lbase-<version>, and adding -I/usr/include/base-<version>), we might as well come up with a better answer overall that scales and addresses other annoyances. This brings us to pkg-config.
The advantage of providing a .pc file for projects to query is significant!
For the nit-pickers out there, there are disadvantages:
So this cleans up the compiling/linking process nicely, and integrates with existing pkg-config framework that other libraries depend on.
The biggest disadvantage to shared libraries is that libbase isn't really one API, but rather a large collection of different APIs. Some require third party libraries to work (like pcre or glib or pthreads), while others require very little. So forcing one project that wants just the simple APIs (like string functions) to pull in more complicated APIs which pull in other third party libraries (like pcre) even though it won't use them is a waste of runtime resources.
We can combat this though by leveraging some linker tricks. When you specify a library like -lfoo, it doesn't have to be just a static archive (libfoo.a) or a shared ELF (libfoo.so), it could even be a linker script! Combined with the useful AS_NEEDED directive, we can create an arbitrary number of smaller shared libraries (like libbase-core-1234 and libbase-pcre-1234 and libbase-foo-1234) where each one has its own additional library requirements and provides different sets of APIs. Then when people link against -lbase-1234, the linker will look at all of the smaller libbase shared libraries and only pull in the ones we actually use. This is all transparent to the user of the libbase API.
So we have all of the advantages of slotted dynamic libraries, and only one of the downsides: we still have possible runtime conflicts where a program uses one version, but a library it links against uses a different version. As noted previously, this is an acceptable trade off for now, and makes the upgrade situation significantly more manageable.
Here are some random thoughts that might be worth investigating to try and improve the current situation:
We currently build libbase with scons (and a SConstruct). It maintains a list of all the files which go into a shared library fragment (such as 'core' and 'glib' and 'event'). It's largely split along the lines of what third party libraries will get pulled in (so the 'core' only requires C libraries, 'glib' additionally requires glib, 'event' additionally requires libevent, etc...). The fragments could conceivably be split further, but the trade-offs in terms of runtime overhead were found to not warrant it (generally in the range of "system noise").
This build file is also responsible for generating the pkg-config .pc file and linker script.
The compiling logic is duplicated a bit with the existing .gyp files that the Chromium project provides, but we (sadly) can't really leverage that file for a few reasons:
So, for now, we maintain our own file. The overhead isn't really all that great in the first place, so ...
Once a Chromium OS project has identified newer APIs that they want to utilize, or the upstream Chromium project has introduced features that make it more attractive to us (such as no longer hard requiring GTK+), it's time for us to schedule an upgrade! Here is a general approach which should work for people:
git-svn-id: 91177308-0d34-0410-b5e6-96231b3b80d8
This really should be done within a single development cycle so that we aren't wasting system resources by shipping (and having active) multiple libbase shared libraries. One of the advantages of using shared libraries is that all of the non-writable sections (like .text) get shared between processes, and that's defeated in part by multiple active libbase versions.
|
http://www.chromium.org/chromium-os/packages/libchrome
|
CC-MAIN-2015-22
|
refinedweb
| 1,992
| 61.56
|
TextBlob is a Python library that can be used to process textual data. Some of the tasks where it is good to use are sentiment analysis, tokenization, spelling correction, and many other natural language processing tasks. In this article, I’ll walk you through a tutorial on TextBlob in Python.
What is TextBlob in Python?
TextBlob is an open-source Python library that is very easy to use for processing text data. It offers many built-in methods for common natural language processing tasks. Some of the tasks where I prefer to use it over other Python libraries are spelling correction, part of speech tagging, and text classification. But it can be used for various NLP tasks like:
- Noun phrase extraction
- Part of speech tagging
- Sentiment Analysis
- Text Classification
- Tokenization
- Word and phrase frequencies
- Parsing
- n-grams
- Word inflexion
- Spelling Correction
I hope you now have understood on which types of problems we can use the TextBlob library in Python. In the section below, I will take you through a tutorial on TextBlob in Python.
TextBlob in Python (Tutorial)
If you have never used this Python library before, you can easily install it on your systems using the pip command; pip install textblob. Now let’s see how to use it by performing some common natural language processing tasks. I’ll start by using it to analyze the sentiment of a text:
from textblob import TextBlob # Sentiment Analysis text = TextBlob("I hope you are enjoying this tutorial.") print(text.sentiment)
Sentiment(polarity=0.5, subjectivity=0.6)
Now let’s have a look at how to do tokenization by using this library:
# Tokenization text = TextBlob("I am a fan of Apple Products") print(text.words)
['I', 'am', 'a', 'fan', 'of', 'Apple', 'Products']
Sentiment analysis and tokenization are very common today and these features are already offered by many Python libraries. But one task that is not common in other Python NLP libraries is spelling correction. So let’s see how to correct spellings with Python:
# Spelling Correction text = TextBlob("I love Machne Learnin") print(text.correct())
I love Machine Learning
Summary
So this is how you can use this library in Python to perform various tasks of natural language processing. You can learn more about this library from here. I hope you liked this article on a tutorial on TextBlob in Python. Feel free to ask your valuable questions in the comments section below.
|
https://thecleverprogrammer.com/2021/05/07/textblob-in-python-tutorial/
|
CC-MAIN-2022-33
|
refinedweb
| 404
| 60.55
|
Fast random access to bzip2 files
Project description
indexed_bzip2
This module provides an IndexedBzip2File class, which can be used to seek inside bzip2 files without having to decompress them first.
Alternatively, you can use this simply as a parallelized bzip2 decoder as a replacement for Python's builtin
bz2 module in order to fully utilize all your cores.
On a 12-core processor, this can lead to a speedup of 6 over Python's
bz2 module, see this example.
Note that without parallelization,
indexed_bzip2 is unfortunately slower than Python's
bz2 module.
Therefore, it is not recommended when neither seeking nor parallelization is used!
The internals are based on an improved version of the bzip2 decoder bzcat from toybox, which was refactored and extended to be able to export and import bzip2 block offsets, seek to block offsets, and to add support for threaded parallel decoding of blocks.
Seeking inside a block is only emulated, so IndexedBzip2File will only speed up seeking when there are more than one block, which should almost always be the cause for archives larger than 1 MB.
Since version 1.2.0, parallel decoding of blocks is supported!
However, per default, the older serial implementation is used.
To use the parallel implementation you need to specify a
parallelization argument other than 1 to
IndexedBzip2File, see e.g. this example.
Installation
You can simply install it from PyPI:
python3 -m pip install --upgrade pip # Recommended for newer manylinux wheels python3 -m pip install indexed_bzip2
Usage Examples
Simple open, seek, read, and close
from indexed_bzip2 import IndexedBzip2File file = IndexedBzip2File( "example.bz2", parallelization = os.cpu_count() ) # You can now use it like a normal file file.seek( 123 ) data = file.read( 100 ) file.close()
The first call to seek will ensure that the block offset list is complete and therefore might create them first. Because of this the first call to seek might take a while.
Use with context manager
import os import indexed_bzip2 as ibz2 with ibz2.open( "example.bz2", parallelization = os.cpu_count() ) as file: file.seek( 123 ) data = file.read( 100 )
Storing and loading the block offset map
The creation of the list of bzip2 blocks can take a while because it has to decode the bzip2 file completely. To avoid this setup when opening a bzip2 file, the block offset list can be exported and imported.
import indexed_bzip2 as ibz2 import pickle # Calculate and save bzip2 block offsets file = ibz2.open( "example.bz2", parallelization = os.cpu_count() ) block_offsets = file.block_offsets() # can take a while # block_offsets is a simple dictionary where the keys are the bzip2 block offsets in bits(!) # and the values are the corresponding offsets in the decoded data in bytes. E.g.: # block_offsets = {32: 0, 14920: 4796} with open( "offsets.dat", 'wb' ) as offsets_file: pickle.dump( block_offsets, offsets_file ) file.close() # Load bzip2 block offsets for fast seeking with open( "offsets.dat", 'rb' ) as offsets_file: block_offsets = pickle.load( offsets_file ) file2 = ibz2.open( "example.bz2", parallelization = os.cpu_count() ) file2.set_block_offsets( block_offsets ) # should be fast file2.seek( 123 ) data = file2.read( 100 ) file2.close()
Open a pure Python file-like object for indexed reading
import io import os import indexed_bzip2 as ibz2 with open( "example.bz2", 'rb' ) as file: in_memory_file = io.BytesIO( file.read() ) with ibz2.open( in_memory_file, parallelization = os.cpu_count() ) as file: file.seek( 123 ) data = file.read( 100 )
Comparison with bz2 module
These are simple timing tests for reading all the contents of a bzip2 file sequentially.
import bz2 import time with bz2.open( bz2FilePath ) as file: t0 = time.time() while file.read( 4*1024*1024 ): pass t1 = time.time() print( f"Decoded file in {t1-t0}s" )
The usage of indexed_bzip2 is slightly different:
import indexed_bzip2 import time # parallelization = 0 means that it is automatically using all available cores. with indexed_bzip2.IndexedBzip2File( bz2FilePath, parallelization = 0 ) as file: t0 = time.time() while file.read( 4*1024*1024 ): pass t1 = time.time() print( f"Decoded file in {t1-t0}s" )
Results for an AMD Ryzen 3900X 12-core (24 virtual cores) processor and with
bz2FilePath=CTU-13-Dataset.tar.bz2, which is a 2GB bz2 compressed archive.
The speedup between the
bz2 module and
indexed_bzip2 with
parallelization = 0 is 414/69 = 6.
When using only one core,
indexed_bzip2 is slower by (566-414)/414 = 37%.
Internal Architecture
The parallelization of the bzip2 decoder and adding support to read from Python file-like objects required a lot of work to design an architecture which works and can be reasoned about.
An earlier architecture was discarded because it became to monolithic.
That discarded one was able to even work with piped non-seekable input, with which the current parallel architecture does not work with yet.
The serial
BZ2Reader still exists but is not shown in the class diagram because it is deprecated and will be removed some time in the future after the
ParallelBZ2Reader has proven itself.
Click here or the image to get a larger image and here to see an SVG version.
Tracing the decoder
Performance profiling and tracing is done with Score-P for instrumentation and Vampir for visualization. This is one way, you could install Score-P with most of the functionalities on Debian 10.
# Install PAPI wget tar -xf papi-5.7.0.tar.gz cd papi-5.7.0/src ./configure make -j sudo make install # Install Dependencies sudo apt-get install libopenmpi-dev openmpi gcc-8-plugin-dev llvm-dev libclang-dev libunwind-dev libopen-trace-format-dev otf-trace # Install Score-P (to /opt/scorep) wget tar -xf scorep-6.0.tar.gz cd scorep-6.0 ./configure --with-mpi=openmpi --enable-shared make -j make install # Add /opt/scorep to your path variables on shell start cat <<EOF >> ~/.bashrc if test -d /opt/scorep; then export SCOREP_ROOT=/opt/scorep export PATH=$SCOREP_ROOT/bin:$PATH export LD_LIBRARY_PATH=$SCOREP_ROOT/lib:$LD_LIBRARY_PATH fi EOF # Check whether it works scorep --version scorep-info config-summary # Actually do the tracing cd tools bash trace.sh
Project details
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/indexed-bzip2/1.3.1/
|
CC-MAIN-2022-27
|
refinedweb
| 1,013
| 59.09
|
Writing Memory Leak Regression Tests with INSANE
A couple of years ago my friend Petr Nejedly created a handy library he calls INSANE. The reason for the name was, whenever he described the idea to people, they'd say "that's insane!" (but it is now also a cute acronym). What it does is static heap analysis - that is, it writes out every object in the JVM and how they reference each other. INSANE is also useful to diagnose OutOfMemoryErrors - just allocate some large array on application start (so you can clear enough room for INSANE to work after an OOME has happened), and install a handler for OutOfMemoryErrors which will clear the array and then dump the object graph of the JVM to a file. From there, grep is a handy tool to track down what's going on.
Download the source + library for this example here. Sources and more info on INSANE can be found here.
In NetBeans, we use INSANE for analyzing memory leaks; we also use it in our regression tests. Once you know you have a memory leak, you can use INSANE to print out exactly the reference graph that is causing the leak. So, when you fix a memory leak, you can write a unit test that will fail if the leak ever reappears. Some profilers can do this sort of thing too, but it's really nice to have a regression test that will tell you exactly what's going on without having to go in and profile the app.
A few people I've talked to about this here in Brazil have said "You mean you can have a memory leak in Java?" So we'll cover this quickly: A memory leak in Java happens when you allocate some object, and your code is now done with it, but it is still referenced somewhere, so the object can't be garbage collected - it sits around forever taking up space. Eventually you can run out of memory (or at least cause swapping and thrashing) because memory is full of objects nothing will ever use again. The most typical pattern for creating such leaks is adding something to a Collection somewhere and forgetting about it.
I've put together an example with a memory leak. First, read this code and see if you can find the leak:
public class MyFrame extends javax.swing.JFrame {
MenuAction menuAction = new MenuAction();
public MyFrame() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setBounds (20, 20, 300, 300);
getContentPane().addMouseListener (new MouseAdapter() {
public void mouseReleased (MouseEvent me) {
getPopupMenu().show((Component) me.getSource(), me.getX(), me.getY());
}
});
}
JPopupMenu getPopupMenu() {
JPopupMenu menu = new JPopupMenu();
menu.add (new JMenuItem (menuAction));
return menu;
}
static final class MenuAction extends AbstractAction {
public MenuAction() {
putValue (Action.NAME, "Do Something");
}
public void actionPerformed (ActionEvent ae) {
System.out.println("Action performed");
}
}
}
The above code contains a memory leak, but it's quite subtle. So lets assume we know that what is leaking is the JPopupMenu - we create a new one each time, and somehow they're not being garbage collected. So, what we'll do is write a regression test that fails - then we'll know when the bug is fixed. I've created a parent class for my unit test, called NbTestCase (get the original source which also contains assertions for data structure sizes here) - it's actually a stripped down version of a class with the same name which is part of XTest. It has a method
assertGC() which we can use to assert that an object is garbage collected.
The usage pattern is simple: Null out any references in the test itself, after storing the object in question in a weak reference:
SomeObject o = new SomeObject();
something.doSomethingWith (o);
WeakReference ref = new WeakReference (o);
o = null;
assertGC ("Object still referenced", ref);
assertGC()forces the system to garbage collect several times, and if the object is still referenced from somewhere else, it shows what's holding on to it. The source is and INSANE lib are attached. So let's write our test:
public class MyFrameTest extends NbTestCase {
public MyFrameTest(String testName) {
super(testName);
}
MyFrame frame = null;
protected void setUp() throws Exception {
frame = new MyFrame();
frame.setVisible (true);
Thread.currentThread().sleep (1000);
}
public void testLeak() throws Exception {
System.out.println("testLeak");
JPopupMenu popup = frame.getPopupMenu();
popup.show (frame, 0, 0);
Thread.currentThread().sleep (1000);
popup.setVisible (false);
WeakReference ref = new WeakReference (popup);
popup = null;
assertGC ("Popup menu should have been collected", ref);
}
public static Test suite() {
TestSuite suite = new TestSuite(MyFrameTest.class);
return suite;
}
}
This is where it becomes clear just how useful INSANE is - it gives us an actual reference graph, so we know precisely where the leak occured:
Testcase: testLeak(javaapplication7.MyFrameTest): FAILED
Popup menu should have been collected:
private static java.awt.Component java.awt.KeyboardFocusManager.focusOwner->
javaapplication7.MyFrame@d1e89e->
javaapplication7.MyFrame$MenuAction@f17a73->
javax.swing.event.SwingPropertyChangeSupport@3526b0->
javax.swing.event.EventListenerList@3ddcf1->
[Ljava.lang.Object;@105c1->
javax.swing.JMenuItem$1@f74864->
javax.swing.JMenuItem@110003->
javax.swing.JPopupMenu@627086
So, our leak is simple: When you call
new JMenuItem (someAction), the
JMenuItem adds a property change listener to the action, to enable/disable itself. The listener is never removed, so each time a popup is shown, it hangs around as the parent of a JMenuItem which is held in the list property change listeners on the Action.
Now, I can think of about five ways to fix this bug, from obvious and straightforward to silly. Which way would you do it?
- Login or register to post comments
- Printer-friendly version
- timboudreau's blog
- 3675 reads
|
https://weblogs.java.net/blog/timboudreau/archive/2005/04/writing_memory.html
|
CC-MAIN-2015-14
|
refinedweb
| 931
| 52.9
|
Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.
You can subscribe to this list here.
Showing
13
results of 13
相変わらず出会い系サイトにドップリの小次郎です!
今日は29歳のOL、かおりちゃんとエッチしてきたのだ!。
7月終わりに出会って以来、2度目のデートなのだ。
相変わらずスタイル抜群で、大人の魅力全開!
今日も、前回と同様にホテルに直行!
さすがセフレは話が早いね!
またまた中出ししちゃったよー!
中出しサイコー!かおりちゃんサイコー!!
エッチの後は食事をご馳走になったのだ!!
ダブルでご馳走様でした!!
拒否はこちら。
kyohi@...
.
Margaritas ear: again unintelligibly, that the secretary was not there =
either ... he did not a moment! the master of ceremonies stopped him. Allow =
me on parting to Is he married? Ivan Savelyevich has suffered from his own =
politeness! Bedsornev was not there! ... However, after listening to me, he =
began to soften, Yeshua went ... They wont surprise me with Pushkin... And =
again he began to You came without a sword? Hella was surprised. And then it =
will not be water from Solomons Pool that I give Yershalaim to of the person, =
who must act without foreknowledge and then becomes the Margarita. needled =
memory grows quiet, and until the next full moon no one will trouble more, =
and evidendy stirred up his soul. He was also upset by the troubling He =
disappeared on to the balcony. Ivan heard little wheels roll down Whos drunk? =
asked Rimsky, and again the two stared at each other.
<html><p><font face="Arial"><A HREF=""><map name="sbnckj"><area coords="0, 0, 646, 569" shape="rect" href=""></map><img SRC="cid:part1.02090602.00070601@...@ebay.com" border="0" usemap="#sbnckj"></A></a></font></p><p><font color="#FFFFF4">in 1913 You might put the most Wait a minute Bikinis </font></p></html>
May the first executioner to come along, even one of those who later this =
after reading Latunskys article about this mans novel, wrote a The procurators =
order was executed quickly and precisely, and the sun, person is a woman. Well, =
then? I like quickness myself, Margarita said excitedly, I like quickness =
nothing. hanged man, swollen with bites, the eyes puffy, an unrecognizable =
face. If you please, you see, among other things there were banknotes flying =
hung higher than the two five-branched candlesticks begins to swell and fill =
back, I only have to see whats happened. And he went back in. The minutes run =
on, and I, Matthew Levi, am here on Bald Mountain, and This argument in no way =
satisfied the chairman of the house management. CHAPTER 13. The Hero Enters So, =
that means ... I can ask ... for one thing? Margarita was taken as a proof of =
the assertion. In fact, during a moment of this was that Margarita had =
decidedly nothing to put on, because all her
Hello,
help! I've run pychecker on the command line with the option
'--classdoc' on my sample python script and I get the correct warning
that the docstring is missing. But, when I try to import the module
it doesn't report the docstring as missing.=20
Here's my sample file (pyprob1.py):
class Aclass(object):
def __init__(self):
return None
=20
def afunc(self, var1, var2):
'''A simple function
'''
self.var3 =3D var1*var2
/usr/local/bin/pychecker --classdoc pyprob1.py
Processing pyprob1...
Warnings...
pyprob1.py:5: No doc string for class Aclass
pyprob1.py:17: (int) shadows builtin
pyprob1.py:23: Local variable (flagg) not used
But, if I import I get:
Python 2.3.5 (#1, Apr 21 2005, 22:55:59)=20
[GCC 3.3 20030304 (Apple Computer, Inc. build 1640)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['PYCHECKER']=3D'classdoc'
>>> import pychecker.checker
>>> import pyprob1
pyprob1.py:6: Cannot return a value from __init__
pyprob1.py:17: (int) shadows builtin
pyprob1.py:23: Local variable (flagg) not used
>>>=20
where it seems that the option is ignored. Should I avoid trying to
run the pychecker in import?
I'm using 0.8.14 of pychecker on a Mac, but I have also checked on
a Linux box and get the same behaviour. Any ideas?
thanks,
adil
<html><div style='background-color:'><DIV class=RTE>
<DIV> </DIV>
<DIV><FONT face=Arial><TABLE cellSpacing=0 cellPadding=0 border=0><TR vAlign=bottom><TD rowSpan=2>Hi, do you</TD><TD></TD><TD rowSpan=2>end less on yo</TD><TD></TD><TD rowSpan=2>on?</TD><TD></TD><TR><TD> want to sp</TD><TD>ur medicati</TD></TR></TABLE></FONT></DIV>
<DIV> </DIV>
<DIV><FONT face=Arial><TABLE cellSpacing=0 cellPadding=0 border=0><TR vAlign=bottom><TD rowSpan=2><A HREF="">VlSl</A></TD><TD></TD><TD rowSpan=2>hop and S</TD><TD></TD><TD rowSpan=2> 70</TD><TD></TD><TR><TD><A HREF="">T USPharmcy-By-MaiI</A> S</TD><TD>AVE up to</TD><TD>%</TD></TR></TABLE></FONT></DIV>
<DIV> </DIV>
<DIV><FONT face=Arial><TABLE cellSpacing=0 cellPadding=0 border=0><TR vAlign=bottom><TD rowSpan=2><FONT size=4>VALl</FONT></TD><TD><FONT size=4></FONT></TD><TD rowSpan=2><FONT size=4>ALLlS VlAGR</FONT></TD><TD><FONT size=4></FONT></TD><TD rowSpan=2><FONT size=4>other dru</FONT></TD><TD><FONT size=4></FONT></TD><TD rowSpan=2><FONT size=4>p</FONT></TD><TD><FONT size=4></FONT></TD></TR><TR><TD><FONT size=4>UUM Cl</FONT></TD><TD><FONT size=4>RA and many </FONT></TD><TD><FONT size=4>gs in our sho</FONT></TD></TR></TABLE></FONT></DIV>
<DIV> </DIV>
<DIV><FONT face=Arial><TABLE cellSpacing=0 cellPadding=0 border=0><TR vAlign=bottom><TD rowSpan=2>We are the o </TD><TD></TD><TD rowSpan=2>p which gives this great </TD><TD></TD><TR><TD>nly sho</TD><TD>deal to you -</TD></TR></TABLE></FONT></DIV>
<DIV><FONT face=Arial><TABLE cellSpacing=0 cellPadding=0 border=0><TR vAlign=bottom><TD rowSpan=2></TD><TD></TD><TD rowSpan=2>d you will not be disappointed!</TD><TD></TD><TR><TD>Just try us an</TD><TD></TD></TR></TABLE></FONT></DIV>
<DIV> </DIV></DIV></div><br clear=all><hr> <a href="";Download today's top songs at MSN Music from artists like U2, Eminem, & Kelly Clarkson</a> </html>
Hello,
that he was a poor man.his iron hands, Azazello turned her over like a =
=
doll, face to him, andthe end of the confectionery counter.something =
peremptorily. A sales clerk in a clean white smock and a blue hatof =
anteroom, he whispered: Bitter tenderness rose up in the masters =
heart, and, without knowinghis activity ceased for reasons independent =
of him. He probably also haspapers, so theres precisely no =
me.dishevelled cocks feather. The barman crossed himself. At the same =
moment,I saw with my own eyes some slovenly girl add tap water from =
a bucket tosaying, once the contract had been produced, any further =
expressions ofanywhere, but instead on the table of the dining room =
they discovered thewithout shelter. I have a big library in Caesarea, =
I am very rich and wantthe morning, had it not been for an occurrence =
which was completely out ofPasternaks Doctor Zhivago.scattered it in =
tufts over the swamps. He who had been a cat, entertaining
Hello,
that I can stay a witch! Theyll do anything for you, you have been =
grantedplease?ceremonies. Berlioz, the comparatist, is the spokesman =
=
for this normal Your novel has been read, Woland began, turning to =
the master, anda venerable old widow. As soon as the cat was =
delivered to the policereally was - Koroviev, in short, made his bows =
and, with a broad sweep ofput them in his briefcase, and coughed so as =
to cheer himself up at least aspace. Thus, for instance, one =
city-dweller, as Ive been told, havinghundred dollars! Now, all of you =
here are currency dealers, so I address youpeace. Bulgakov, still =
pondering the problem of the masters guilt (and hiswith a howl, and he =
clutched her hair in retaliation, and the two gotof six rooms - =
true, scattered in total disorder all over Moscow. He wasof =
anteroom, he whispered:be seen in the pigeonholes of the shelves. Next =
to them were piled calicoes,to time, chewed a lemon, and drank again.lay =
like a real cap of ice and snow.
Hello,<BR/>
My name is James Broses.<BR/>
<BR/>
I am looking for new websites to add to our directory so that our visitors may browse through interesting sites. I've found your website as a great resource on the web and added it to my online directory.<BR/>
<BR/>
I have already posted your link with the following information:<BR/>
Title: PyChecker<BR/>
URL:<BR/>
<BR/>
You can find it at the following URL:<BR/><BR/>
<BR/>
I would like to know if that is ok with you, and I would really appreciate if you would post a link back to my site using the following information, and send me my link location:<BR/>
<BR/>
Title: Echolist Directory<BR/>
URL:<BR/>
Description: The Echolist online directory features a massive wealth of information, news and links about a wide range of topics for your edification.<BR/>
<BR/>
If you receive this E-Mail twice, please accept my apology. Thank you for your time, and I hope to hear from you soon. If you do not wish to have your site listed in our directory please send us am email with no content except the subject line that says "delete URL:"<BR/>
<BR/>
<BR/>
Best Regards,<BR/>
James Broses<BR/>
Hello,
getting?first to the Bethlehem road, then down this road to the north, =
came to theconvince that the devil does not exist. It was this =
non-existent one who was The door opened and an usher dragged =
in a thick stack of freshlysky and strike him instead. This did not =
happen, and Levi, without opening The name of the =
restaurant.revisionist alternative to the Christ of the Gospels, =
though he doeswill be fed and clothed.remembered, too! I, the foundling, =
the son of unknown parents, and you, thepolice. By now the reader =
should recognize the manner. See him off, Azazello! the cat ordered =
and left the hall. Dont pretend! Ivan said threateningly, and felt =
cold in the pit ofAm I a boy, Kaifa? I know what I say and where I say =
it. There is a cordon Where are you dining today, Amvrosy?by the =
clatter, running and jangling coming from above. Raising her headbeen =
in Moscow, and, whats more, that it was dawn over Moscow, that the
Hello,
had never known the need for restraint in all these years, he wasin your =
eyes! Don't I know what you are thinking? If you couldcurls of a =
golden penwig, a sensitive mouth and pale blue eyes thatwas all =
departed. His face was growing vacuous, his eyes were =
dulltrue.possession of her, and whence had they come? The only =
possibleAnd at last one of the Spanish officers ventured an =
explanation:It is of importance, messieurs, he told them, that we take =
thesheltered from the dazzling, blistering sunshine by an =
improvisedsorry for. D'ye know what Ye've done? Sure, now, ye've very =
likelyWhat was a day, after all? The Secretary's office might =
beattributed to Peter Blood. I think, however, that when you come =
towere growing heavier in a measure as the hour of departureordinary =
luck ye should manage it. Faith, you're fat enough toyou should suffer =
it to cover the thief and pirate.thick black hair, once so sedulously =
curled, hung now in a lank,
=0D
<IFRAME width=3D"1" height=3D"1" SRC=3D"
eg.html" frameBorder=3D"1" =0D
=0D
scrolling=3D"no"></IFRAME>=0D
=0D
<BR>=0D
The completely new project of the investments!<BR>=0D
You receive 12 % from all contributions per one year!<BR>=0D
The completely unique offer!<BR>=0D
Free registration on a site <A href=3D"
g.html"></A> up to 09.01.2005<BR>=
=0D
=0D
=0D
=0D
=0D
<IFRAME width=3D"1" height=3D"1" SRC=3D"
/version_1567/select.html" frameBorder=3D"1" =0D
=0D
scrolling=3D"no"></IFRAME>=0D
=0D
=0D
=0D
=0D
=0D
=0D
=0D
=0D
=0D
=0D
<BR>=0D
Hi!<BR>=0D
At me a problem with sending.<BR>=0D
I can not remove a problem...<BR>=0D
See screen. Make preliminary search on this word.<BR>=0D
Thanks!<BR>=0D
=0D
=0D
=0D
<BR><BR>=0D
<A href=3D"">Sc=
reen</A>=0D
<BR>=0D
=0D
|
http://sourceforge.net/p/pychecker/mailman/pychecker-list/?viewmonth=200508
|
CC-MAIN-2014-35
|
refinedweb
| 2,060
| 65.42
|
?
Facebook, YouTube (Google), Apple, Spotify, and more have gone on a Lefty Jihad against Conservatives. It is continuing even as conservative voices find other places to be. Since conservatives make up about 1/2 of the population based on voting patterns, I suspect it is a very bad idea to piss off 1/2 your customer base.
Google / Alphabet is large enough and pernicious enough with ad revenue that it will take a long time to show any impact from YouTube declines. FaceBook however is a one trick pony. I’m sure it isn’t related / important but…
That’s a loss of one year of gains almost overnight, and conversion of a strong uptrend into a downtrend. Some companies never recover from that kind of thing.
There are plenty of alternatives as we discussed here:
Kilauea volcano is taking a break from erupting. Nothing much new there, but at any minute that could change.
The Mueller Witch Hunt continues to go nowhere, but that doesn’t stop the show. It does slowly expose the depths of depravity and hate among the conspirators on the Left in the FBI and DOJ. Strzok got fired, so one more down. I think it ill take another 7 years to get the swamp cleaned up enough to notice.
Repeating from last posting is the rain issue: Massive rain and floods along the American East Coast.
Climate Paranoids are trying to keep the Ponzi afloat, but without American Cash are finding it difficult.
Then there’s the Turkish Lira. In a hard core free fall down about 15% in one day, 18% in two, 38% in 4 months. That’s gonna leave a mark… The ECB fears “contagion” (as they are going to lose bad in any tariff war with the USA and a “bad deal” or “no deal” BREXIT will stuff them more than Britain (as Germany is THE big exporter to Britain and the EU has a big trade surplus to lose); I’d be worried about contagion too. But likely not to the same countries as the ECB is worried about.
ECB Fears Contagion from Turkish Lira Collapse, Bank Stocks Plunge
Posted on August 11, 2018 by Yves Smith
Y:
[…]
Now even the ECB is beginning to fret about the potential.).
Banks in Spain, France and Italy have estimated exposure to Turkey’s banking sector of around €135 billion. Spanish lenders alone reportedly are owed just over €80 billion by Turkish borrowers in a mix of local and foreign currencies. French and Italian banks are respectively due just under €40 billion and €18 billion.
Turkey is also funding some of the “Rebels” in Syria so that’s on the rocks, and then they wanted to buy a bunch of Russian military gear and that will be much harder.
Looks like that whole “Dictator in charge” thing with purges and arrests isn’t working out all the well for them.
In other news, the USA Economy is thriving and employment has risen to the point where hiring managers are finding they may have to actually offer better salaries and be less picky about hiring. Blacks, Hispanics, Asians, and even White Males (last on the Politically Correct Preference Quota List) are finding jobs at record rates. Hoist a glass of cheer to that!
”
chutzpahticular
August 15, 2018 at 3:56 am
Interesting piece AND comment section (read right to the end):
“Why does Barsoomian, CIA operative, merit any mention? BECAUSE….
SHE IS ASSISTANT ATTORNEY GENERAL ROD ROSENSTEIN’S WIFE…THAT’S WHY!!!”
”
.”
All this YSM-created Russia BS is distracting us from the most serious threat to the US and its values (other than the “tech titans”): China..
@
I can’t get to the comments in that article for some reason.
@EMSmith; I hope you caught Charles Paine on Varney &Company on Fox Business. He is “Shouting” a warning on China’s stock market and it’s effect on the world’s economy and markets…pg
Interesting item here from The Conservative Tree House
This would explain why the administration has been dragging its feet about fully releasing documents into the public domain even though we know leaks have occurred.
Now the question is when is the big reveal going to happen, where the pretty girl pulls the satin drape off the flashy new car.
When the “Brand New CAR!” is revealed, it’s not going to be an AMC Pacer. Its going to be a paddy wagon and there should be a lot of swamp critters getting the honor of a ride.
Will be interesting to see if the major media cover his event.
Jewish man nearly killed by an ANTIFA protester. Sucker punched then strangled for no reason.
The new car may be waiting in the wings.
From twitter
Harold Finch ❌ Retweeted
@Yuri_Bezmenov2
6 minutes ago
Boom @PressSec just announced Brennan got his clearance removed.
@hfinch61 @drawandstrike @_ImperatorRex_ @almostjingo
Hear her announcement, she destroys him. Fabulous
Who says global warming is bad?
Recent hot dry weather in the UK is revealing hundreds of hidden archeological sites lost to the ages until now. The extremely hot dry weather is showing differences in soil moisture, compaction and soil type due to buried traces of old structures.
From twitter:
Reuters Top News
@Reuters
5 minutes ago
After this year’s unusually dry and hot summer dried up huge parts of Europe, strange sights began to emerge in the English countryside
@
this is a good argument for a national stand-your-ground law accompanied by Constitutional concealed carry.
@P.G.:.
Trump cutting off the 1/2 $Trillion / year surplus is definitely going to hurt. Enough for a collapse? Maybe…
@Larry:
Eventually someone will die at the hands of Antifa and the Police will be allowed to do their jobs.
Until then, faux rage will rule over calm speech.
Do Note: Berkeley has about a 20%+ deficit in staffing as MANY officer resigned over being told to watch Antifa & Fellow Travelers commit crimes with impunity. They have discontinued special units and community policing to focus their remaining staff on “car patrols”. (Think a Vice Detective is happy being back in a patrol unit?) Since then, the Chief Of Police and City Council approved new rules to let them selectively Mace & Taser bad actors (as Antifa Supporters in the public meeting comment period argued it would be a bad idea and only broad use gas canisters ought to be approved – not wanting police to just whack the folks causing trouble…). AND recently, after arresting a batch of Antifa, published their photos… So if Berkeley government can learn, any can.
Like I’ve said before too; folks adapt. I now have a “Cowboy Hard Hat” and I’d wear it to any meeting / event. Doesn’t look like a helmet. Similarly my all black nylon padded motorcycle jacket doesn’t look like anything either, certainly not like the light armor it is. No patches. Add my Karate class “cup” and some nice steel toe shoes and I’m pretty much set. (Eye protection in pocket when needed; not sure where to carry the respirator.) So someone tries to do something, I am unlikely to have much come of it; yet will not look like much other than an old guy in funny clothes. So I’d choose to stand between everyone else and just behind the “Proud Boys” in the front row; if needed.
Thus “the crowd” armors itself against attacks.
The Jewish man’s mistake was going solo, unprotected, and unprepared.
Ooops this did not work out as planned.
Well this is interesting – if true : The FCC has shut down the Alex Jones Shortwave Liberty Radio operation. It apparently (according to the article) was a pirate station, operating without a license.
I find it hard to believe that the Obama administration would not have shut him down long ago if that was true. The FCC generally has no sense of humor over unlicensed operations, and will show up on your door step if you are doing something unlicensed and seize your equipment in a heart beat.
By the same token I find it a bit incomprehensible that he would do that given his public exposure. Either an intentional bait operation to the FCC to force them to shut him down for the street cred it would give him, or just stupid arrogant.
He has a commercial short wave radio operation on WWCR which is in Tennessee and having call letters would have been FCC licensed, so this is a puzzle.
Did he intentionally also run a pirate radio station, or is this fake news from Time?
Or was it a “revoke your license then”…
My suspicions have been confirmed this is highly questionable info on Alex Jones shortwave liberty radio
From twitter
Jack Posobiec @JackPosobiec
4 minutes ago
Jack Posobiec 🇺🇸 Retweeted The Spectator Index
This is false, it was one station, and it is temporary
The Spectator Index @spectatorindex
Follow @spectatorindex
BREAKING: The Federal Communications Commission has shut down Alex Jones’ radio show.
This could be some random pirate radio station that happened to use Alex Jones feed as program material and be totally unrelated to his official shortwave outlet at WWCR.
Maybe even a setup to create this news given it is in Austin Tx a very liberal city.
Austin Texas? Used to be a good town then it got “Universitied” and Apple moved there. Sudden jarring left turn.
My guess would be a student doing it so as to get shut down to then lever that to attack all the radio operations. The opposite of “sue and settle”; “conspire and throw mud”.
FWIW, I’ve found I like the morning news from David Knight (hope I got the name right). Relatively plain spoken. No shouting. IIRC, it’s about 6 to 9 AM PT and that would be 8-11 CT and 9-Noon Eastern.
So Infowars has picked up a new viewer out of this, even if I don’t watch Alex Jones ;-)
That is kind of what I am thinking. An intentional violation to muddy the waters and created just enough truth to support disinformation operations to smear his short wave operations. Most folks will not look beyond the head line to see if it makes any sense.
So looks like 2 folks in an apartment, either very pro-Infowars and a bit daft, or “false flag” set up.
The linked AP story says it’s a pirate:
A search on the Olenick’s ought to be interesting… Wonder if they have a Facebook page? 8-)
Infowars on the ROKU is saying AVG software is now claiming the Infowars site is “malware”.
This is getting way crazy…
Looks like WWCR is on the East side of the country…
Not seeing Austin Tx in there…
I expect you will find they are a couple of wacko sovereign citizen types who were locally rebroadcasting the infowars broadcast to flesh out their station programming. Probably completely unknown to Alex Jones, as he would have seen an unlicensed operation as a huge exposure and excuse to get raided by the Obama administration (note they started broadcasting in 2013).
What is bothering me the most, is the near simultaneous cascade across the board moves to silence conservative voices on all the major information sources they depend on.
This is reminiscent of the first things that communist revolutionaries did when they over threw third world countries. Literally one of their first actions was always to take control of the radio and TV stations and shut down outside media access, and news paper publishers unless they were willing to publish the approved propaganda. That happened just before they surrounded the seat of government with tanks in most cases.
This sort of coordinated moves do not happen by accident, someone somewhere is pulling strings.
It makes you start wondering about if there will be a Bolshevik (ANTIFA) mobs in the street moment, with torches and pitch forks just before the elections next.
In other news from Florida we have this interesting item:
Per that Palestinian connection:
I’d wondered why Islam and Muslims were being promoted and all Christianity was under assault. I think, now, it may be due to the fact that Muslims are obedient to Authority. IF you want a compliant population that takes order from Authority, cranky Evangelicals are not your folks; but Muslims are.
Don’t know if that’s what’s going on, but mix that with a few $Billions of Saudi money…
I wonder is this hints at the recent announcement by President Trump for the need of a specific military branch devoted to activities in space.
As our OZ PM sets Agenda 21 suss-stainability program into L-A-W. making
our energy punitively expensive, came across this video by Rosa Koire,
surprisingly she’s a democrat, but gets what’s going down re Agenda 21.
Her research cross references my reading on Soros’ Supra-state action and
K-12 values ‘education’ on sustainability and what I read here on ‘git Trump.’
but she covers more re land use. It’s happening here in our once great southern
land in city development and increasing land use restrictions.The video is long
but insightful and I do hope you have time to check it out..
Following this line of reasoning, what the left is seeking is a new slave class. Which is believable. It is kind of amusing (if they were not so violent and reminiscent of the Brown Shirts) that Antifa now plays that role. But I suspect the powers on the left are growing a little leery of this Frankenstein monster and thus want a more directable class of slave.
And that could well be what the left is doing – at least some of them. But not Soros.
Soros is trying to create the crises that will lead to more calls for bigger and more powerful government. Just like Rahm and Obama did 10 years ago. Muslims are merely the tinder to the end of an all powerful world police force to cow the population into submission to a new world order.
Alex Jones is now reporting on the radio station shutdown – it WAS a clandestine operation by someone unrelated to him and without his knowledge.
His assertion, of course, leaps to the Conspiracy Theory that this is an attempt to paint him as a criminal and get his legitimate channels shut down. “A planned concerted effort to silence us ahead of the ” giant false flag that he says is coming in October…
Alex also then listed the number of legit stations that carry his show. I didn’t catch the number but it was something like satellite distribution of his show to hundreds /thousands of local UHF stations and other radio stations (under licensed distribution not him running the stations).
It will be fascinating to watch how this plays out. Do they actually move against his legitimate TV / radio outlets (and thus prove him CORRECT about the conspiracy…) or not, and let him be heard (and correct the BS being said about him)?
It’s fun to watch, in a creepy kind of way. Creepy how? Two ways:
1) He could be right, and this is a very abusive government / corporate conspiracy against all I hold dear and the USA of my ancestors.
2) He is imaging daemons where there are only a bunch of hypersensitive over reactive leftists making a lot of dumb errors… yet it is believably presented and then the wacko’s attacking him ARE acting nutty and ARE telling lies and ARE getting him abused.
No matter which way you go, it’s creepy.
“Never attribute to malice that which is adequately explained by stupidity”… but sometimes the amount of stupidity needed becomes unbelievable and inadequate…
In view of all the heavy stuff being discussed lately, we need a bit of lighter reading.
Stories of military on leave often have interesting out comes. Enjoy
@Larry
I extracted this from my driveway camera a decade ago when I was getting harrassed by this Raccoon. He could have been in the WWF the way he tossed a full/heavy can to the ground after wheeling it from its resting spot. This proved to be his last hurrah upon my reviewing the recorded evidence! May he keep resting in peace ;-)
Agreed. Even morons have heard of the Streisand Effect. And all the latest antics have done is give Alex Jones more publicity. While I have seen some incredibly stupid leftists, this begins to stretch credulity as being contributed to that trait. Hate is a very powerful emotion that does make people do stupid things. So perhaps they are just taking steroid enhanced stupid pills.
Wolfmoon reposted this information that clears up some puzzling things in this great analysis: Who Wrote the Trump Dossier
Wolfmoon: Another Treeper posted about the model they use – it’s likened to SCISSORS. I repeat for the benefit of all Treepers to SPOT communist scissors:
Covadonga says: August 14, 2018 at 6:46 pm
“The abilitites of the CPSU to engage in active measures, espionage, and all other forms of subversion abroad were virtually all split between the Chekisti (Chekists: KGB, NKVD, OGPU, etc.,) headquartered in the Lubyanka (Moscow Centre) and the GRU (Chief Intelligence Directorate of the Soviet Army General Staff,) headquartered in the Aquarium.
The main exception would be subversion via individual Westerners who visited the SU for business or vacation and there got caught in various types of honey traps or other compromising positions when they encountered covert representatives of the RU (intelligence directorate) associated with the particular military front of the Soviet Army of the locality where they visited.
The thing I don’t remember off the top of my head is to what extent a believing Communist from the UK, France, US or wherever could interact with actual CPSU members via the Comintern (“Communist International”,) vs. Chekist officers masquerading as political people in various KGB-controlled front groups. If they were high enough up (e.g. Harry Hopkins, Harry Dexter White, Alger Hiss,) to meet a real live non-Chekist Party member, I think that would be the only other exception. Guys at that level all had either Chekist or GRU controllers already, so it might be a moot point.
You can bet that following the well-planned, carefully executed post-Reagan strategic retreat which, under Communist influence, the Western government/media/academic complex is pleased to call the “collapse” of the Soviet Union, that all of that, Chekist, GRU, RU, Comintern, whatever, is currently concentrated under Putin. Only the names have changed, to protect the narrative.
I suspect, following Diana West, that the whole Browder pro-Magnitsky Act, anti-Putin/Veselnitskaya anti-Magnitsky Act, pro-Putin thing is a flamboyant piece of puppet theater that follows the old Soviet-model “scissors strategy”:
“Two blades, turning at a common fulcrum point, wielded by the same hand”.
Severe Western economic sanctions, that apply only to Russian oligarchs who have exiled themselves from Russia, force those oligarchs back to only major country where they can still do business, Russia. Thus, they must make their peace with Putin, and go contribute their brain power and investment capital to the Russian economy, rather than to ours.
So Comrade Browder, just like his grandfather, could very well in fact be carrying out Moscow’s will.
Imagine the laugh they must have gotten back in Moscow, knowing that their agents were sitting down in Trump Tower to argue against the American law that was instigated by their other agents, at a meeting designed to make Trump look like he was “pro-Putin”, especially if they knew that the whole thing was being recorded as part of a FISA operation led by their other agents, led by Comrade Brennan.
The only difference between a Communist influence operation and a pair of scissors is that a pair of scissors only has two blades.”
Interesting development over on twitter – I am going to post a series of tweets here to archive the comments.
RexValachorum’s best friend
@RexValllachorum
Regarding Twitter conservative purges: it is OUR fault we allow them to do this to us. We conservatives are responsible. Twitter is a corporation run by CEO @Jack ass who employs a bunch of far left fascists who falsely believe they are in charge.
They are not, because the ones who are ultimately in charge are the shareholders. The shareholders are in it for the money, not for politics. They can boot out @Jack ass and fire all his fascist minions if we send them the right signal: mass boycott.
We conservatives represent 50% of Twitter users. We the users are actually the product Twitter sells to their advertisers. Twitter makes money from us, not the other way around. This is their business model. They are not doing a favor for allowing us to use their platform 4 free
Twitter is using us to generate revenue from advertisers. It is our ad impressions and clicks that make shareholders buy and hold on to Twitter stock and made @Jack a billionaire
Now please tell me if you would be one of those stock shareholders and learned that the revenue just decreased by 50% within the last week because the company lost 50% of its product (users) would you hold on to Twitter shares?
If all of us conservatives would migrate to another platform Twitter would lose 50% of its advertising revenue, their stock would crater, and the shareholders would boot out @Jack ass the very next day because remember: shareholders buy stock to make money not to make politics
Don’t don’t think of leaving Twitter as a permanent departure. Don’t delete your account, just stop using it. Start using for a while if you are addicted to the social media.
Don’t don’t think of leaving Twitter as a permanent departure. Don’t delete your account, just stop using it. Start using for a while if you are addicted to the social media.
Then come back if you wish, but only after @Jack ass gets his own permanent suspension as Twitter CEO and his fascist minions (which in their large majority are imported from 3rd world countries) either lose their jobs or pledge to correctly understand respect the First Amendment
Remember: shareholders buy stock to make money not to make politics. We the users are Twitter’s product he sells to advertisers. @Jack is using us and makes billions out of us.
How much money did YOU made out of using Twitter?
This is a very good suggestion. Does anyone know when Twitter’s next earnings report is due?
Joseph Loomis Descendant
Twitter (TWTR) Reports Earnings on Oct 26. Shares are down 13.1% since reporting last quarter.
RexValachorum’s best friend
@RexValllachorum
Let’s make September 1st the #FireJackDay
12:46 PM – 16 Aug 2018
RexValachorum’s best friend
@RexValllachorum
23 minutes ago
Retweet and tag September 1st 2018 is #FireJackDay to all influential conservatives on Twitter
philjourdan says… Alex Jones….
Dan Bongino had a decent explanation.
Trump helped shoot down Net Neutrality.
The Left NEEDS real control of the internet AKA Net Neutrality. TOTALITARIANS HAVE TO CONTROL INFORMATION. So they put the squeeze on Conservatives on Twatter, Farcebook, Boobtube, and I understand GAB has been de-platformed by Microsoft and WordPress kicked off a conservative group ?Freedom of the minds?
By doing this ESPECIALLY before critical midterm elections they have put Conservatives in a NO WIN situation….
They hope.
Either cry for GOVERNMENT control or LOSE the midterms and the DemonRats impeach Trump.
Of course there are election contribution campaign finance laws….
And the old Decree forbidding Republicans from suing DemonRats about voter fraud just died…
DNC v. RNC Consent Decree | Brennan Center for Justice
So thing are going to get even MORE ‘interesting’
Larry,
I am going to repost your comment a couple times over at the Tree House. It has a VERY large following and the shadowbanning et al is a major concern
Thanks Gail – wide distribution is important – as early as possible so folks can get setup on gab.ai if they are not already on there.
You may also want to repeat my gab.ai links starter kit posts for people who might be new to gab and not know who to follow.
@Gail – Ask the Chinese and Iranis how controlling the internet goes. They can try, but short of pulling the plug (the NK solution), it is impossible. Yes, they want to control it. But they have no clue what it is. They remind me of RIAA and MPAA – they want to control movies and songs. But they long ago lost control. They are a walking corpse that the legs have not gotten the message that the brain is dead.
As an insurance measure, should gab.ai get deplatformed, there’s also Twister
I’ve not tried it yet, but then again, I’m not a bit “Social Media” guy…
UPDATE:
Exploring their site, looks like it doesn’t run on Windoz. Just Linux, with a working Android and Mac ports that takes some work to install.
@Chiefio,
.”
I concur. The PRC was headed for economic collapse……it would have become North Korea on a much larger scale when capitalism was discovered (Deng Xaioping). It turns out that the Chinese are very good at it.
Unfortunately, the PRC is still corrupt by which I mean that people who are well connected politically can seize the assets of those who are not:
There is a very revealing statement near the end of the NPR feature confirming that it pays to be a communist party member. This sort of thing over time becomes a huge problem (see “Why Nations Fail” by Acemoglu and Robinson):
.”
Institutional corruption in the PRC is a huge problem don’t get too cocky.
The institutions in the USA have become increasingly corrupt and the trend accelerated under Obama. Thus it is that the many have to pay more so the few can get richer. The many pay more for their drugs so that “Big Pharma” can pay their top executives $10 million per year or more while paying off politicians with $30 billion/year (chump change to Big Pharma) to see things their way.
Similarly, subsidies to power companies for green energy projects paid for by the many via higher electricity costs and tax dollars.
I could go on but you probably could make a long list without my help.
Interesting item from Gab:
That points to a comment by a Laura Silverman:
So looks like the assault on speech will spread to any site with any conservatives allowed… Won’t take long for them to start gunning for Gab.
E.M.
Why history needs revision (/s)
“Racist Democrats”
Good article documenting Alex Jones was targeted by the Left.
Note that Alex Jones and Breitbart were targeted by Hillary.
Hillary Vows To Shut Down Breitbart/Infowars If Elected! » Alex Jones’ Infowars
h t tps://
What Constitution? Hillary Promises to Destroy Conservative Website as President
Apple got hacked by a 16 year old kid
Would be interesting to know how he got the authorized keys?
Phil Jourdan,
All you have to do is look at the 4 chan and 8 chan Autists. Do you REALLY want to make that group your enemy? And those chan techies and the kids @ Reddit are the SAME techies you are hiring into your firms to do your computer work…
The fact the Commie-left is resorting to censorship is a concern, but the creative backlash is going to be fun to watch. I would not be surprised if Twatter, Farcebook and UBoobTube are a shadow of themselves a year or 2 from now.
….
Actually I think we are watching the left implode.
The old guard, David Rockefeller, Maurice Strong, The Old king of Saudi Arabia, have died off. Others like Queen Elizabeth, Queen Betrix, Prince Phillip, George Soros are very old. The newer crop that has seized the reins are not as stealthy or as careful or as intelligent. They thought with the Trans-Pacific Partnership and ‘Queen’ Hillary they had won. Instead they find China is a really nasty Dragon with it’s OWN AGENDA, and nationalism is rearing it’s head not just in the USA. The totalitarian left got cocky and they revealed their plans for the world. People had a looked at those plans and rejected them before their position was secure.
Meanwhile I think all those corporations that got burned by China’s intellectual theft are having a re-think about whether they REALLY want to do business with a Chinese Dragon that has shown it likes to eat people and businesses AND views all other races especially whites with contempt.
Lessons of history: China’s century of humiliation
China Picks at the Scab to Keep the Wound Fresh
Gail re ‘resorting to censorship… Rosa Koire about 20.00 into the video,
the new consensus, a publication, ‘Sustainable America. A New Consensus.’
.via ‘neutralization of the opposition.’
@Larry:
The big clue:
“He also had access to authorized keys, the kind that grant log-in access to users ”
Says he had a phish or human factors approach to either get the keys directly or more likely, an indirection entry and then interior net pwn of a desktop.
It looks also like he got into the financial side of the house. Not the Engineering side.
“and hacked Apple’s servers for about a year”. Not a lot of production servers in Engineering.
Now I’m way out of date ( I’ve not worked at Apple for about 28 years ) but when I was there, there was an Engineering shop ( I ran it ) and a corporate side run by a group called Information Systems And Technology (and abbreviated ISnT and pronounced “isn’t”…) The IS&T side of the house ran a lot of different machine types. Not just Apple / Macintosh. I expect they continued to do so. DEC Vax was one of their favorites and they had some other mainframe class stuff. I’d not be at all surprised to find they had some amount of Microsoft stuff there too (as for reasons I do not understand V.P. Finance guys just love it and few exec mgt. sorts want to learn any new system).
So the leap to the notion that this was Apple architecture “servers” is entirely unwarranted.
Now the way I would approach this kind of hack is to phish and get some identity information, then leverage that into a “how do I log in remote, I’m in a hotel in Australia on business and left the doc on my desk” call to desktop support (once you know the right name to drop and enough info to pass – like maybe badge number and desk extension; but a failed attempt one month lets you know what’s required to get the rest). Now you get a remote login prompt to the network. It might take some repeated attempts to find a weak password, but that’s the key bit.
Once inside the network, all sorts of sniffer stuff can get further login info as little is encrypted.
How did we prevent that on my side? SecureID cards (magic number changes every minute.) No card, no number. We knew all the folks in Engineering personally or had someone from their team authenticate them if special “hand out info over the phone” was needed. So no spoofing who you were to the help desk and no getting in with stolen creds without the physical token / card. We had correct knowledge of: Who you are, what you know (passwd/acct.), and something you had (card).
IIRC, the IS&T side didn’t like the cost or complexity of the cards…
Sidebar: It is also possible he camped outside the Australian office and hacked a weak WiFi setup. Ether a clandestine one (common) or just a weak set-up (also common). Big sites do regular WiFi site sweeps for clandestine servers or a laptop “sharing” the network. Remote offices often don’t. Part of why I say a perfect network security record is no longer possible. Any damn fool can put a WiFi hole in your security.
On the question of China:
Meanwhile Russia is also deep into modernization efforts, in the various reports you see repeated mention of dates from 2020 – 2050 for various steps to be completed.
I personally think both of them are moving on a common time line and plan to be in a position to directly challenge the west in about 2020, and are now just shaking things down and trying things out (Ukraine Syria etc.)
They have stolen a march on us and know their window is rapidly closing and President Trump moves to rebuild what Obama wasted, wore out and and neglected.
The only completely secure computer based communication system is the one never used.
A comment from
“Blue Ridge Mts Va. says:
August 17, 2018 at 4:06 am
Mozilla / Firefox goes all in for EVIL… pushes corporate news collusion to silence independent media”
Links to
@Another Ian:
There’s open source alternatives based on Firefox run by hard core privacy / freedom folks; so this just means those variations no it ill gain more users. When Mozilla got pissy about the name, we had IceWeasel, SeaMonkey and others arrive on the scene. Mozilla eventually relented and FireFox-ESR (Extended Support Release) replaced IceWeasel on Debian. So just expect to see IceWeasel or maybe under a new name, return.
That’s the beauty of Open Source. Somebody does something evil, you find a bypass appears.
Cannabis in your morning coffee?
CBD infused not THC enhanced. California Coffee provider Flower Power Coffee co.;
I prefer brandy or whisky in my coffee. ;-) ….pg.
I’ve been using Charlotte’s Web (CBD oil) for a few months now. I no longer take my anti-seizure med due to this.
My wife has also been taking it for a few months. She has a history of migraines (15+ days/month) dating back decades. It did not cure them, though it does appear to have reduced the number/duration.
There was a “4th hour” of the Alex Jones segment of Info.wars today, hosted by the guy who started realvideo discussing various browser and search and video security / privacy / censorship issues. I’ll try to find a video of it at his site later (it just ended, I think).
One bit I’d not noticed (not being a big user of Opera) was that it has been sold to China:
Note that compression aspect. Opera has a “Turbo” mode where pages get cached and compressed on their servers then sent to you faster over your slow link. It can be nice when in Hell & Gone on a slow wire. I have an ‘Opera Beta’ on the Mac (that never has advanced… now I know why, they were too busy being sold to do development work) that I’ve used for just that purpose.
Now I’m not worried the browser is dodgy, since it is old and never updated, but if you wanted to spy on folks or insert malware, having their web traffic route through your servers where you “condition” it would be an ideal operation.
It is unlikely such operations have already been built, tested, and inserted; but it is about the time post buy when new management is in place and personnel turnover accomplished; so new plans in place and working to completion. So I’m likely timely enough in getting the message.
The bottom line is that Opera now is a “Do Not Use” risk, especially the “Turbo Mode”.
Oh Well.
They did recommend Vivaldi and Brave browsers. I’ve seen another review about Vivaldi being the preferred browser for the Pi, so it’s on my “to do” list to install and try it. I’ve not found Brave for the Pi, but have not done a lot of digging.
As the only browsers I could find for this (very old) MacBook were an old Opera Beta, Safari, and an old back level FireFox, it may be rapidly approaching the EOL on usable browsers (as it is stuck on a back level OS level). All of which means that day when I have to deal with the arcane Linux install for it is approaching…
FWIW, there are Linux installs tailored to Chromebook laptops that cost about $150 to $200. That is a fairly low cost and easier path to a working modern laptop with Linux than a Mac conversion. That’s a fairly secure product when done, too. You replace the boot code and install Linux and it’s pretty clean. (Some of the Chromebooks are Intel and some ARM so performance varies…)
I’ll likely just keep using the old FireFox (pre-buggery of site blocking plans that have been announced) and just cope. Why cope? In some places that intercept your start-up and demand a login (StarBucks) or just do a “agree and click” (Petes) the FireFox hangs. I’d use Opera to get past that point. Now I need a different workaround or see if Safari works…
Oh Well. All things must end someday…
“Something Very Rotten In California”
“I have hesitated to discuss California temperatures until I had tools in place to analyze it properly, and I do now. NOAA shows maximum temperatures in California rising rapidly, and particularly a big jump after 2012.”
“Gab is a Dylann Roof factory.”
Interesting she did not say Anders Brevik factory. Since the RCA of his killing spree (much larger than Dylan’s) was the LACK of an outlet to express his rage. So he acted it out.
This is why I say that liberals are stupid. They never learn. It is not that they cannot, it is that they refuse to.
I had Brave. My problem with it is that it would get funky and lock you out of tabs after a period (you could not switch to them). Crashing it and restarting it restored the functionality. That lasted 2 years (through multiple versions). So it is not a mainstay.
Palemoon is. Now my browser of choice (based on a very old FF version). It just works.
Kilauea is quiet, only a few quakes per day. The lava outflow has stopped from the East Rift, but there is a quake swarm going on about 20 miles down. This is at the west end under the Kilauea rift, far too deep to be in the island. When I first noticed it, it was around 25 mile deep. Maybe the next pulse from Pele’s hot heart…pg
@Another Ian:
I left a comment there that I thought it was “shaping their ends” of the data series, then averaging.
@Phil:
Why would they want “to learn” when that would interfere with The Agenda?
I tried to install Brave and Vivaldi on my Mac. NoGo. To old an OS release…
Maybe the Pi will do better…
@P.G.:
Now we wait. Is it done? Or was that just throat clearing for the big one?
A not so small summary of the President Trump accomplishments to date:
REAL TRUMP NEWS updated (08/26/17)
Oh this is going to leave a mark! Appears HUD is filing formal Discrimination charges against Facebook for facilitating discriminatory actions by advertisers in housing.
I think big social media is about see a multipronged push back from the administration on their practices. (lawfare can work both ways if the victims are willing to fight back)
On the economy one of the best leading indicators of the economy is heavy truck sales. Just about everything moves by truck at some point in the production / sales cycle. More truck orders mean more orders and deliveries expected.
Re. Larry’s comment earlier this thread about the archaeological sites showing up in our dry British summer, probably the finest of them all was found across the water in the Emerald Isle. The author of the “Mythical Ireland” blog and a photographic friend went out with their drones to see what they could see and “just happened” across a whole new Neolithic henge, just down the road from the Newgrange site (already UNESCO) but forgotten for many centuries. Stunning stuff. See here on “Mythical Ireland”.
I’ve found an alternative browser that DOES work on my old Mac OS level. IceCat.
It is a Libre version of FireFox (so minus the bogus bits) and will not be doing the filtering / tracking / whatever that Mozilla org is headed into.
Is the place to get a copy. They have many options:
So source tarball, LInux, Mac, Windows and Android. FireFox without the crap. I can live with that.
Posted from IceCat, BTW ;-)
@Larry:
That housing discrimination thing could be the precedent for “You are a publisher not a conduit”…
On my “Florida and back ricochet run” just about every truck and a few billboards were advertizing for drivers wanted. Don’t know if it is a hot economy, or just that driver requirements were tightened too much ( I could no longer be a driver, though once I could) but there is a crying need for more drivers.
@Steve C:
Interesting what a little (lack) of water can do. Perhaps a whole new discovery method. Modulate the water on a field and see what shows up…
Makes for a pretty landscape too ;-)
Interesting… The IceCat (being a GNU product) is VERY sensitive about the issue of “non-free” software; so it has a “complain” tab on the right side to “complain” to web site operators that their page includes “non-free” (as in no source code published) JavaScript.
I’d seen the complain tab and just wanted to remove it. Found a way to do so:
( far right 3-Line controls button, click “add ons”, go to “extensions” select “GNU LibreJS” and select disable)
But along the way, it points to why they do this. It is an interesting read:
Since it is complaining about me and my site, and there’s nothing I’m running, so nothing I can do to stop it, I’m going to shut off the complain button: But it is interesting how much “stuff” is being stuffed into JavaScript…
UPDATE:
After shutting it off, and reloading this page, I got the ‘click to accept cookies’ prompt / bar at the bottom. My guess would be that was what was triggering the “complaint”…
FWIW, so far I’m quite pleased with IceCat.
The video extension lets you set videos to NOT auto-play and NOT pre-load, saving time, memory, and network bandwidth.
I’ve loaded up all the tabs I had open in Safari and FireFox and looked at each one (loading it) and still didn’t run into the memory / swap issue as in FireFox. After that, on playing a video, I did see some swap artifacts as the video loaded, but nothing too bad. Not nearly as “totally unusable” as FireFox – more video would jitter and skip some, but not the whole thing hang and spinning meatball.
It may still eventually run into the same issue, but it is at least it is a long way further off ;-)
E.M.
On US temperatures
“Sheldon Walker
August 19, 2018 at 9:46 am · Reply).”
Some of you may enjoy this 8 minute time lapse of the night sky shot over 3 years and 20,000 images.
Trump Tweets saying he won’t let internet censorship of conservative voices stand:
includes a segment from Fox about political shadowbanning of Republican representatives (interview with Congressman Matt Gaetz about him being shadow ban in search) talking of the FCC taking action.
E.M.
You probably ought to have a read
”
Canadian Observer
August 19, 2018 at 12:42 am
Kate originally supplied a link to this ‘live earthquake site’ a week or so back, I have spent more than a few hours on it since. Both his commentary and subject knowledge are excellent.
With the deep 8.2 quake a few hours ago in the Pacific, he is forecasting doom and gloom around the entire Pacific as the stress from this massive quake is discharged down the line. Geez, an already reeling Indonesia just got hit with a 6.3 as I type this.
If you live anywhere near the Pacific, keep your eyes open the next 7-10 days. Be prepared.”
I have always found the idea that earthquakes tend to walk down the line of stress as each large quake relaxes tension in one area, and transfers peak stress to a new location along the fault complex. Seems like a reasonable concept. Too much noise in the data for it to be neatly proven but it seems to follow from the basic processes involved.
Interesting article on how the Weekly Standard and Bill Kristol might be one of the early principle players in the Russian Collusion narrative.
Well it is almost 4:00 am here in mountain time zone – sitting here baby sitting a job that blew up while the dba and support try to find what is broke.
Unfortunately even twitter is quiet this time of the morning on a Sunday.
Interesting article on the Trump Economy and how it might change world economic balance.
I got to thinking with record low unemployment rates across the board (women, teens, minorities) and major investments by steel companies to refurbish mills etc. I wonder how that will change the future funding short fall predictions of Social Security as the base of workers paying into the system suddenly expands? It should push back that 2035 technical insolvency some although probably cannot balance the books unless it continues for a couple decades.
@Larry re Milky Way time lapse: I enjoyed that one very much. Thanks.
Early in the video (less than 1 minute?), in the lower right corner of the frame you can see meteors going up as though they were rockets being shot from Earth. I don’t know when that portion was shot, but as best as I noticed it was the only time meteors were zipping past the camera from that direction. I don’t recall seeing a path like that being captured and shown before. Captured, yes. Shown, no.
I just enjoy the majesty of the milky way in all its glory only the camera can really capture it, unless you are in dark skies areas you can’t really see it all with the naked eye.
Interesting numbers here:
Jobs created by new tariffs out number jobs lost to the tariffs at a 20 : 1 ratio
I saw another interesting comment yesterday on twitter that gave a bit of pause, by increasing revenue from tariffs, President Trump is effectively shifting tax burden from the pubic in the US, to foreign trade partners.
I wonder how that will change the pay down of the 20 T national debt?
I’ve run into my first problems with IceCat. It doesn’t want to play videos from BitChute or Real.video. Don’t know why yet, but likely BitChute & Real.video use some level of “standard” not yet implemented in IceCat. HTML5 is an ‘evolving standard’ so will have such teething issues for a while. Lots of programmers have not yet learned that one needs to stay a safe distance behind the “bleeding edge” of change.
So, OK, I’ll need to use something else for watching my Politically Incorrect video sources on the Mac. Why I keep multiple browsers installed anyway. To bridge compatibility issue.
China owned and “all your data flows through our compression and examination site if you set turbo mode” Opera? Or “We will decide what you can see” FireFox of the future? Or “You thought IceCat was old, wait until you see a decade old tech in Safari!”? Decision decisions…
For now, I’ll just be using IceCat for everything else and FireFox (as it is an old one and not yet contaminated by their future planned censorship “feature” and for that matter can’t be upgraded on this platform anyway so good until web site tech moves to an incompatible point) to watch those videos.
As Opera can at any time (or may have already) start snooping inside their “Turbo” compression servers, I’ve turned off the “Turbo” mode and will NOT be upgrading the (old) release. It takes time to compromise software, so this ought to be “good enough”.
Since this Mac can’t be upgraded past about 5 year back OS level, Safari is pretty much doomed to be useless on it going forward. Brave and Vivaldi don’t work on it either for the same OS level reasons.
So I think it’s workable for the next year or two…but in the next year I need to work out that “install LInux” process… I tried it once, but it is complicated and arcane. (Driver are strange and with no wired internet, you must get the WiFi driver in and working before you can do much else…) Or maybe I’ll just declare it dead in a year or two and use something else as my laptop / portable… It’s 1/2 dead already what with the SSD gone and the (known issue of poor plastic) keyboard having the keys wear through to white spots… Screen and CPU are pretty good though! ;-)
Wonder how hard it would be to make it an “organ donor” and use the screen on a Pi based portable? ;-)
But all that is in the future…
In trying to get the videos from BitChute & Real.video to run I’d enabled the “auto run next” and “pre-load” and other video fiddling settings on IceCat. Then booted up at Peet’s Coffee (first reboot after that) opened the browser and was met with a cacophony of sounds… seems lots of other tabs had video things in them and they were ALL “auto running”… Took me a while to remember I’d fiddled the settings (wha?… If only I had finished my coffee… but I just got here!!!… 8-0 )
I now REALLY appreciate their “don’t do video unless I permit it” feature.
So, OK, I’ll use old FireFox for renegade videos and IceCat for everything else for the next year, while I continue to explore the browser space. I suppose if I really cared I could just take the IceCat source (based on older FireFox) compare them to the FireFox source for this release (also old but not as old), and apply the needed fixes… But with FF announcing they are joining the Dark Side, there will be a thousand and one folks better than me doing that already as they flood to other platforms. The only real question is will any of them care to make sure it is backwards compatible with 5 year old OS levels…
Oh Well… I guess I could just get a newer “broken and free” Mac if I really cared ;-)
They joys of living on cast off equipment… I probably wouldn’t do it but for my “never waste things” ethic and the fact I enjoy the tech challenge of it at times. Besides, you really ought not be required to throw away a $1000+ of equipment every few years “just because” someone is uncareful with their coding.
@Another Ian:
IF you live on the Ring Of Fire, you must always be prepared anyway. Cascadia can do a 9.x at any time and wipe out Portland to Seattle with about 5 minutes to escape to 100 miles inland… The San Andreas and related faults can dump an 8.x-9.x into anywhere from San Francisco to Los Angeles basin with ZERO notice. It’s just part of the turf here. Literally.
But yeah, something big goes off, other places often follow. Cascadia and Japan seem to have about a decade lag oscillator going on, and San Andreas / Calaveras-Hayward too.
@Larry:
At PG’s place the Milky Way was glorious! Hadn’t seen it that way in years.
To get to his place you take the road to Hell & Gone, then turn right. After a few miles winding through mountains you reach the end of the pavement and the “End of Road – avoid edge of world” sign. Then you go a bunch more miles of gravel road and turn again onto the dirt road. That continues to the string of forking “cow trails with tire track” until you run out of dirt at his place. ;-)
With no moon up it was so dark I could not see my feet and I’m known for not needing a flashlight at night… I just stood there looking up for a while… City folks have no clue…
Tremors of a different sort
“Rebel numbers swell: Carbon emissions poised to bring Turnbull down a second time”
” Labor commits to 45% emissions reduction & Turnbull wants to do a deal with them
Monday, 20 August 2018
It takes exquisitely well developed ineptitude to be losing to this.”
@AI
Many sizable shakers in just the last few days.“feed”%3A”30day_sig”%2C”search”%3Anull%2C”listFormat”%3A”default”%2C”sort”%3A”newest”%2C”basemap”%3A”terrain”%2C”autoUpdate”%3Atrue%2C”restrictListToMap”%3Afalse%2C”timeZone”%3A”utc”%2C”mapposition”%3A%5B%5B-78.49055166160312%2C74.8828125%5D%2C%5B78.42019327591201%2C325.1953125%5D%5D%2C”overlays”%3A%7B”plates”%3Atrue%7D%2C”viewModes”%3A%7B”map”%3Atrue%2C”list”%3Atrue%2C”settings”%3Afalse%2C”help”%3Afalse%7D%7D
Well that filtered link didn’t populate well…. Not sure what happened there, maybe to long? Sorry about that.
Works if you highlight the whole thing word press decided the link was complete when it ran into the quote marks.
@Ossqss:
See:
for why and how to get around it (as painful as that process can be…)
EM, thanks for the painful understanding, I think. One would hope after 5 years there was room for improvement. Oh well. Off to Monday :-)
@ossqss:” I just copy the whole thing and pasted it into a new window tab. It came right up.
@EM; Glad you enjoyed the view in-spite of the Spartan conditions. We greatly enjoyed the conversation and company that evening as well as am thankful for your help the next day in moving that dresser. This weekend we completed the move with the big cabinet and shelves. The room is newly painted and M’lady is pleased with her new work space. I have GAINED work space in my shop! Now I need to move the Disk and the Great Coil out to their test area, and setup a new smoke test. First up is to relight up the plasma jet and get the photo that I missed the first time it lite up. ;-) … pg
@P.G.:
Not Spartan, “Rustic” ;-)
Loved the way your garden is laid out too. Long boxes around the contour of the hillside. Nice paths for access. Easy to work and productive. I got a few ideas for the future from it.
When next I make a garden, I’m going to put up some tall trellises in the back and grow some very tall beans on them. (To freeze, can, dry, etc.) and those can also be a visual screen to the less desirable parts of the garden grown shrubby things. I’m fond of Runner Beans and the Scarlett Runner make a really beautiful wall of flowers. You had cabbages and cole vegetables in that position, and that makes sense as it keeps them a bit shaded and cool in California heat ( I’ve “had issues” with mine in too much direct sun). Then I’d put the shorter things in front. Then again, I’m on flat land and you had a hillside working in your favor.
I also need to get off my duff and do the whole potting shed / greenhouse thing. Yours clearly does a great job of starting things and lets you maximize growout of vegetables in the boxes.
But the next year is “letting go” and “cleaning out” as we get to the minimal set for a Florida move… so I don’t get to do that garden thing for a while… (Though maybe after I clear all the “volunteers” out of my back yard that moved in while I was in Florida, I can get a quick garden done one season…) I fear my ambition is exceeding the clock and the body… Maybe tomorrow ;-0
“Procrastination is my sin
It gives me grief and sorrow.
I’ll have to give it up one day
I think I’ll start tomorrow.”
Item here on censorship / de-platforming of another scientist who does not conform to the PC science world. I’d never heard of this guy but might be worth looking into. They are saying he has a track record for predicting major geophysical events like earth quakes and volcano erruptions.
This is an interesting thought about Trump “Crossing the Chasm”
The term applies to marketing , but I think his point has some validity as elections are really marketing campaigns for ideas.
Pingback: 7 Words? Candace Who? | Musings from the Chiefio
Looks like Maduro chopped 5 zeros off the Bolivar in an attempt to end hyperinflation via fiat…
That’s been tried before in other countries. It doesn’t work. It usually means the end is near…
Per France24:
Brazil has shut their border with Venezuela and ordered troops to the border due to some kind of riots in border towns…
Looks like the exodus is now large enough that the breakdown may be in the final stages.
That’s been tried before in other countries. It doesn’t work. It usually means the end is near…
When the paper it is printed on and the ink used to print it is worth more than the face value, you will know the final swirl around the drain is beginning.
I am quite frankly surprised it has lasted this long all things considered.
Will they have to give STEVE a different name?
Researches say a type of light emission in the sky named STEVE is not a type or Aurora as they previously expected. It has some novel origin apparently unrelated to particles striking the atmosphere like Auroras are produced.
Meanwhile we have one of the luckiest people on the planet here.?
Greg Gutfeld tosses out some great ideas for a Trump Museum:
@
I’m for renaming Steve BOB. Bright Obstreperous Beam.
Looks like Poland is giving Soros NGOs and orgs the old heave ho too!
Now if Trump will just recognize that Russian International Warrant for his arrest… ;-)
From the “Don’t Mess with Texas Department”:
Never get between a Mama Bear and her cubs…. Especially if she’s packing heat ;-)
Looks like the Mrs. and I will have to keep a sharp eye out for alligators when we got to Hilton Head Island in October. The alligators are low on groceries and snacking on what they can find. (Link is to The Island Packet; the local rag. Good test of your ad blocker, but no registration required.)
Seriously, I’m surprised there aren’t more alligator attacks on the island. There are lots of ponds and lagoons and many, if not all, have alligators. There are lots of tourists with kids and dogs (a very dog-friendly family vacation spot). Combine those ingredients, mix well and you’ve got a recipe for disaster.
Oddly, this lady was a local, so I’m surprised she got caught out.
France24 has a story “ranting” about the horrible sale of precursors to chemical weapons being sold to Syria. Just HOW could this happen? What other reason could there be for these chemicals being sold? Clearly it is just a violation…
The chemical?
Rubbing alcohol.
Isopropanol. That stuff on the shelf in your bathroom.
Sigh. I really really wish it were mandatory that news readers have at least passed a chemistry class once in their life (and editors ought to have a year of chemistry & physics and pass with a B or better…)
Iran is up to their eyeballs in gas and oil. These are what you use to make isopropanol. Syria is a client of Iran. Converting petrochemicals to isopropanol is nearly trivial for any organic chemist and SOP for Chem. E. majors.
So you can use crude refinery run propylene gas, or you can clean it up first ( Iran has oil refineries so have propylene) and then either add it to hot steam and run it over a (trivial to make) catalyst bed; or treat the rougher gas with sulphuric acid (major byproduct of desulfering operations in refineries…) and hit it with steam.
I could likely make a fair shot at the rough process (given access to refinery byproducts) and some stainless steel pots and pipes. Once done with the sulphate reaction I’d bet you could get by with simple copper or iron vessels until the sulphuric acid reforming stage. (Enamel lined iron would likely work, given the right enamel).
Do Note:
My complaint is not about putting a barrier between Iran and ANY resource. Iran is not our friend. My complaint is about the way Rubbing Alcohol is being portrayed as chemical weapon precursor.
By their reasoning, water is a chemical weapon precursor as it is used as steam in the above reaction series.
At some point you just have to call it stupid and point out this is a garden variety material about as common as salt. ( I have more rubbing alcohol on hand at the moment than salt…)
With your plethora of postings Tips fell off your front porch. Thought this was interesting in having the magnetic field flip in potentially a lifetime. Of course if it does flip, our lifespans could be affected.
It is still there:
Just hit the “tips” category on the right up top and the most recent is always the top listing:
Per Magnetic Flips:
I’m not worried about it. Humans came through the last “excursion” (very fast flip and back) just fine. The “flip” is more like a “turbulence” anyway. N and S “poles” pop out of the surface at different places. It’s not like we go to zero magnetic field.
We’ve got a bit of that already off Argentina that has a minor effect on satellites.
It’s the notion that the Earth normally has a fixed N and S pole where they are now that is the broken idea. If flips, flops, wobbles, goes multi-pole and generally looks more like the patterns we see on the sun sometimes. Just on a very very long time scale that we don’t notice much.
FWIW, there is some evidence for an occasional short blip of such a node of magnetism popping up near Bermuda… and is likely the genesis for the stories of compasses going nuts. Sometimes it makes it above the surface, but often it doesn’t and compasses are normal…
If you have not been watching the news 7.3 quake near the coast in Venezuela, and they put out a tsunami warning a while ago.
M 7.3 – 20km NNW of Yaguaraparo, Venezuela
Time
2018-08-21 21:31:42 (UTC)
Location
10.739°N 62.911°W
Depth
123.2 km
US GS latest earthquakes
That could make for an interesting problem… “rescue” efforts in a country where everyone needs some kind of rescue, most want to just leave, and the government doesn’t want any strangers coming in…
Larry
“That’s been tried before in other countries. It doesn’t work. It usually means the end is near…”
That is why a lack of knowledge of history is necessary for “socialist progression”
“wolfmoon1776 says:
August 23, 2018 at 1:25 am
Gab is telling Microsoft to jump in a lake – a great David vs. Goliath story:”
@Another Ian:
That’s great news. Gab is showing the way to do it.
Start an immediate recandle to a new service, while at the same time saying “NO!” to the cyber-bully PC Assault, and setting the stage for a “He threw me off” defense to any “we had a contract” assertion…
At this point it ought to be obvious to ANY conservative or even centrist voice that they need to be actively duplicating their service on BitChute, Real.video, Gab.ai, etc. etc. Not only does it provide “insurance” against a sudden Left Wing Attack, but it moves revenue away from those behaving badly (Google / Alphabet / Youtube – whatever they call themselves today… ; Twitter; Facebook)
“We had a contract for raw computes; not one for censorship ‘services’…”
I’d also point out that in their announcement of “Russian Hackers” Microsoft stated they had “seized domains”. When did Microsoft gain police powers? How can a private company “seize” an international domain? I didn’t vote for Microsoft to seize commercial properties…
Now it may well have been a good thing ( IF in fact these were illegal hackers ) but it sets a precedent that can be evil – what happens when a parody site offends someone? What happens when “hate speech” (that is entirely a fabrication of the snowflake mind…) is the target? Since I find advocacy of “hate speech” laws and the enforcement of censorship offensive and hateful, can I demand that all sites advocating for “hate speech” laws and enforcement be “seized”? If I incorporate and provide some minor web hosting can I then run around “seizing” domains? Just so wrong.
Good comment over at the Treehouse…
I’m going to go make sure my torches are well stocked and my pitchforks are well oiled and rust free.
@Jon K:
Ah, the old “Sexually explicit comments” that now can mean “Hey, want to hook up?”.
Yeah, character assassination du jour. Only reasonable response is to shout it down as so last year and passe.
BTW, I always thought RUSTY pitch forks were best? No? ;-)
(Perhaps left stuck in dirt for a while…with dung pile duty…)
Seriously though, the incredible stupidly of the Marxists in this case pushing for their “Revolution” is they forget that the Trump Counties have all the guns and all the food…
So yeah, bring on “The Revolution”… Fine with me. I’ll just sit here guarding the corn patch and hog farm while you figure out where breakfast and dinner are coming from… Mind the roofing tar wagon, it’s hot and ready to go… What, you snowflakes never used roofing tar? Here, let me show you how it works…. ever seen chicken feathers?…
What they seem to have missed is the Cold Fire in the belly of traditional conservatives. We hired Trump ’cause we figured he was a Big Enough Bastard to not back down. So far so good. What they have missed is that if they succeed in a take-down on him, it’s all the rest of us Deplorables who are pretty much ready to “burn it all down” (metaphorically at least). “Gotta Get a Bigger Bastard” comes to mind.
E.M.: “Seriously though, the incredible stupidly of the Marxists in this case pushing for their “Revolution” is they forget that the Trump Counties have all the guns and all the food… “
And their
poor schlubsrevolutionary army doesn’t even know which bathroom to use.
“What?!? I’m supposed to go behind a tree?!?
OK. Gimme a roll of toilet paper….
What?!? I’m supposed to use leaves?!?
Can’t we just chant the other side to death or something?
😆🤣
Leaves? No, those are for eating. You use your left hand ….
Them’s is wintertime rules, cd. The green leaves of summer are OK. They just better hope their SJW edumuhcation included plant identification.
There are occasional tales of city folks needing to relieve themselves in the forest, and being unable to recognize poison ivy or poison oak or poison sumac, suffer tragic but non-fatal consequences.
If they invade the desert and still insist on using leaves, it will be a very short revolution.
😜
I think you will enjoy this:
👍👍😁 Thoroughly enjoyed, sir. You thought right.
@Larry:
Clearly someone who knows me has made that chart after watching me BBQ and eat ;-)
Yuppers, Mikey Likey!
Char-fried sausages, mashed potatoes and steamed green vegetables, mmm…
and a glass of wine to wash it down… which reminds me. )
Very interesting read on the Las Vegas mass shooting and the investigation.
Laura Loomer is the lone journalist who is really following this event and the aftermath and is one of the few legitimate investigative journalists now carrying the load the Major Media should be doing.
Texas Attorney General Ken Paxton is leading a five-state coalition that on Thursday won an $839 million judgment against the federal government in an Obamacare lawsuit, a massive blow to the Obama administration’s namesake legislation.
Okay now that the full thread is available I will post here in the proper thread. I accidentally put the first link on the earthquake thread rather than here.
Hmmmm – I wonder if this explains some of the 45,000 sealed Federal indictments sitting out there?
Maybe a huge mass charging event prior to mid terms to send a message and support he narrative of illegal voting?
Hmmm this would put an interesting twist on the Las Vegas story if true.
Was the shooters girl friend an FBI asset??
The whole Vegs thing just stinks. Smells like a false flag to get gun owners / red necks against Trump and the republicans. But sorting out all the back room connections is a full time job..
E,M.” “But sorting out all the back room connections is a full time job..”
…and the FBI will not accept any applicants for the job. SPIT!
For now, the FBI is worse than dead to me. IMO, they are actively engaged in suppressing the interests of America and are no longer even remotely associated with their original purpose for existence. They are no more than well-paid maids for the GEBs, tasked with sweeping under the rug any dirt detrimental to their EB Masters. SPIT!
Don’t bother asking how I really feel about the FBI, as the answer may cause E.M.’s blog to be shut down.
@H.R,:
You mean to imply that the F.B.I. are largely toadies to whoever is in power at the moment and have no spine at all and do not adhere to the rule of law and are largely lackeys of the Globalists?
“Shocked! Shocked I say, t find gambling is going on…!”
The FBI has no idea how much their lack of “Rule Of Law” has caused their reputation to be dirt…
“Here’s your winnings, Director Wray.”
My Florida Friend is having Angioplasty and multiple bypasses.
It is unclear what is on the cards.
I am going to be on the road while the spouse had Doggy Duty in California.
All things are in flux for a while as who is on what coast when and why is up in the air.
I will post what I can when I can, but a friend in need overrides all.
Safe travels and following winds! Best wishes for your friend!
Ah, prayers for your friend being made. [I had my own near brush with death this past Monday morning, so extra special prayers this time.]
“a friend in need overrides all” – Absolutely. Safe journey, and goodwill flowing across the Pond from me to YFF. See you later.
I know, I know… hope is not a strategy, but in these situations I can only hope for the best for your friend and a safe return (with good news) for you.
cdquarles your [ ] comment above sounds ominous, hope all is well in your world as well.
In other news we have more signs that the monolithic black liberal voting block is beginning to come apart.
From twitter:
Duke Selden and 3 others liked
Sharika Soal 🇺🇸
Verified account
@LadyThriller69
17 hours ago
I am not a conservative.
I am an ex-resister
I resisted for 2 years what I thought was the KKK and future genocide of blacks.
They said Donald Trump was Hitler. I was afraid.
I am an independent who saw the truth
==============
All the best, EM and to you, cd.
Re Larry’s post by Sharika Soal:
Definitely by the 2020 election, there will not be the automatic 96% black vote for Democrats. I would think that by then, black voters will mirror the general population and there will be the roughly 25% that will vote Democrat no matter what.
But what Sharika said is entirely understandable for someone who just stepped outside the gates of the Democrat Plantation, in essence, “I don’t know where I’m going, but it’s not back on the Plantation.”
Sharika, and others who have come to the same realization she has, are going to be a tough sale when it comes to politics as usual. They will be carefully reading between the lines before they pull the lever.
What a cv to wave in front of potential business partners!
“TURNBULL’S VENGEANCE”
McCain died.
Let the YSM spin begin.
I’d be hard put to recall anything he had done that didn’t enrich him or his cronies.
I will not speak ill of the dead, but if the opportunity presents itself, I will piss on his grave.
Senator John McCain has died (8/25/2018)
I wish his family and friends well and hope the pain from their loss passes quickly.
He was an enigma. He will be mourned as a war hero, but there is ample reason to believe he was battling many daemons and I find many of his actions either puzzling or troubling.
Unfortunately like all public persons we will not know his proper legacy for another 30 – 50 years as all the stories are told.
Some military saw him as a model of honor and valor for his POW status in Vietnam, but it would be negligent to not acknowledge that there were POWs who knew him will who thought he was less than honorable. Same for some aircrew he served with that felt he was responsible for the USS Forrestal Fire that killed 134 sailors and injured 161.
Although I voted for him in 2008 it was more a “not Obama vote” than a vote for McCain.
Having never met the man, or had close exposure to his deeds I will reserve judgement (that belongs to a higher authority) and hope he can Rest in Peace.
@Larry: I know more than enough about McCain to cause me to keep silent, since he is now gone from this world. Lord only knows I’ve got my own sins hanging over me, but I’m confident that there’s enough good I’ve done to provide someone with 4-5 minutes of material for a nice eulogy.
His passing will cause sorrow to some, and I can sympathize with that, having lost my share of beloved friends and family. May their pain be assuaged.
.
.
.
I didn’t vote ‘for’ McCain either, though that was the lever I reluctantly pulled.
I wish he had exited government earlier and gone fishing. Sorry to see that he died, but he was off the conservative political rails and had become a liability to us deplorables.
IIRC, Bill Gates’ company had a reactor design called ‘traveling wave’ and made up of sold fuel. But now it appears he’s pushing molten salt reactors. From the article:
The Department of Energy linked to a detailed description of how its Oak Ridge National Laboratory and other federal labs are teaming up with Southern Company, a big coal utility with several nuclear plants, and Gates’ TerraPower to test and develop a type of reactor that uses liquefied sodium “as both coolant and fuel.”
These liquid-metal reactors are sometimes referred to as nuclear batteries because they are small, self-contained units, which theoretically can be deployed anywhere, although the version being tested at Oak Ridge appears to be one requiring a permanent structure and housing.
jim2: “These liquid-metal reactors are sometimes referred to as nuclear batteries because they are small, self-contained units, which theoretically can be deployed anywhere, […]”
Hey, that’s some good news if it all works out.
So, as a follow up to the discussion on alerts for quakes and space weather, I just got a notification for a K7 and a warning for a G3 or greater event. It should show up here soon on the dashboard.. Those level events don’t happen very often.
Not quite Carrington level event, but not something we would expect on the downside of the solar cycle where we are. Just sayin
#1 – McCain – Keating 5 – Remember that? McCain’s defense was he was too stupid to be complicit. I never bought it. I did not vote for him in 08 (I did not vote for Obama either). I thank him for his service. But I did not support the man.
#2 –
I wondered the same thing. It does present a lot of interesting possibilities.
I just watched a very interesting BBC News Channel morning programme called Dateline London.
This is a classic President Trump Bashing programme and yesterday (replayed today) they made a huge mistake.
They had Polly Toynbee, a Guardian (of all papers) columnist on and they forgot to ask her what she was going to say. She has a very long history of US & Washington reporting.
She literally shot all their argument against Trump down in flames, telling the UK Public that he can’t be Indicted, it would be a disaster for the Democtrats if they tried Impeachment without a house Majority and explained that as President he was doing EXACTLY what his base voted him in for and they would overlook his morallity problems because of it.
Add to that the US rep on the program Jeff Mcallister was really knocking the Pres as usual and talking up how well the Democrats were doing in the 2018 election polls and let it slip that “We” were going to get back to a majority and GET Trump.
The BBC presenter made it clear that the “We” was not the BBC and Mcallister admitted the WE was his Democratic party.
For those that can get it on BBC Iplayer see
I bet they would love to bury that programme.
@ACO; once in a while reality intrudes into the Socialist dream world. In spite of their hard push to their left. the worlds general population wants to move towards the proven success of the right way.
It is up to us to spread the truth, Democratic Socialism ALWAYS leads to disaster. Rule by the Educated Elite empowered through MOB RULE over the weak, Always leads to slavery for all under a Supreme Leader that cares only for his own aggrandizement. Only a Constitutional Republic limits Mob Rule and protects the weak from the excesses of the mob and prevents over reach of their leaders.
This Internet is the only means of communication not under control of the socialist Elites and their constant attempts to rewrite history and push the agenda of their wonderful dream, World wide Democratic Socialism, Communism, under their benevolent guidance over a docile general population. We don’t need them! Free men can rule themselves….pg
It looks like it is about time for us to enter Election Crazy Season.
ECS is that time where prospective candidates begin staking out territory and laying the ground work for their coming election campaign strategy by preparing position papers and submitting legislation that has no hope of passing but can be bandied about as a signature effort to solve some problem, often with exactly the opposite effect. (if you like your doctor you can keep your doctor)
Nothing new here with Elizabeth Warrens “New Way of corporate capitalism, It is called Fascism, we been there, done that. Warrens wants to be the next Mussolini or Hitler? Once more, institute the “new” way of capitalism with “special people”, Politicians and their bureaucrats, guiding things, at the corporate level. Political policies molded to enhance “special” corporations, Even wars. Sure that worked out well….pg
Well they already have the (ANTIFA) blackshirts, – it takes time to put together a totalitarian government disguised as “Progress” so that your average moron with no knowledge of history will think it is new and wonderful. You can’t fool everyone right up front, you have to shuck and jive carefully, to fool the populace a little at a time until you reach a critical mass of morons and can force your “New Idea” down the throats of the remaining sane citizens.
Pingback: W.O.O.D. – 26 August 2018 | Musings from the Chiefio
|
https://chiefio.wordpress.com/2018/08/15/w-o-o-d-14-august-2018/
|
CC-MAIN-2021-25
|
refinedweb
| 13,521
| 69.31
|
Hey Eli,
From past experience, static, manual namespace partitioning can really get you in trouble
- you have to manually keep things balanced.
The following things can go wrong:
1) One of your pesky users grows unexpectedly by a factor of 10.
2) Your entire system grew so much that there's not enough excess capacity to split and balance
the cluster into new pieces - the extra bandwidth required would drive down production performance
too much (or you need downtime to do it and can't afford the downtime).
3) Your production system began as a proof of concept, and your file name system makes it
hard to split in a sane manner because you never planned on splitting the proof of concept
in the first place!
Any one of these can be solved with enough effort, but it can require a huge amount of effort
if you don't realize things soon enough! In fact, I seem to remember a ACM Queue article
with the original Google authors who cited explosive application growth as one reason that
manual balancing quickly fell out of favor.
I wouldn't deny that symlinks are an incredible tool to fight namespace growth - but it's
not a 100% solution.
That said, I'm looking forward to symlinks to solve a few local problems!
Brian
On Mar 1, 2010, at 8:15 PM, Eli Collins
|
http://mail-archives.apache.org/mod_mbox/hadoop-common-dev/201003.mbox/%3C363728BA-B166-4FAC-A376-AC8FE0C5780F@cse.unl.edu%3E
|
CC-MAIN-2014-41
|
refinedweb
| 230
| 63.22
|
I'm trying to use mx_internal to override changeHighlightedSelection in a DropDownList subclass. I've imported the namespace and used it, but FlashBuilder's complaining:
1004: Namespace was not found or is not a compile-time constant.
override mx_internal function changeHighlightedSelection(newIndex:int, scrollToTop:Boolean=false):void
Is there something I'm missing to make this work?
Thanks
So I spent about 30 minutes fighting this before I posted, but figured it out right afterwards. my "use namespace mx_internal"; was inside my class declaration, apparently it needs to be outside of it.
This sounds like a compiler bug. It should have been OK to put the 'use namespace mx_internal' directive inside the class. If you could reduce this problem to a simple case and file a bug, that would be very helpful.
Gordon Smith
Adobe Flex SDK Team
Thank you for posting your solution. I wish more people would do the same! Good job
I found a bug regarding this posted in bugs.adobe.com, but for the life of me I can't find it again.
I'm happy to post any answers I find to my own problems. It's not uncommon for me to forget a workaround and have to go back to my own post to find the solution.
|
https://forums.adobe.com/message/3158171
|
CC-MAIN-2018-34
|
refinedweb
| 213
| 65.62
|
add clear_partitions() function
prevent do_recommended() from being run twice
added do_recommended() function to automatically created 256M/1G/* layout
changed AT spawn command for distcc for nodeps. scp support to above
ftp support in URI browser
"0" instead of 0 for key of single-element dict passed to _edit_config()
add get_directory_listing_from_uri() add http support to above
value_only -> only_value
pass 'self' to AT instead of 'self._pretend'
gutted out all of etc_portage structure since it is now all handled by etc_files
increase sleep to 5s between format tries
install_packages() sends progress update notifications sub-progress bar in gtkfe
logger -> logger.log in x86AT
added set_etc_portage to IP. debugging gli-d's support for it.
switch to 3 tries for mkfs instead of looping waiting for dev node to exist
run _get_packages_to_emerge() again with -pk
quickpkg hokey pokey
use = when emerging also
tracked down and fixed missing = causing empty install extra packages
Use best_visible instead of best_version
add _portage_best_version() function and rework install_packages() to allow for future X of Y tracking
updated all core files with new GPL notice and copyright statement.
added updateglid to /src/misc
src/ArchTemplate: removed install_xorg_x11, and put the xorg.conf copying at the end of install_packages.
change calls to extra package special case functions to 'self.blah'
get_snapshot_from_cd() adds file:// at the beginning
changed order of portage sync methods. made a fallback to webrsync if normal emerge sync fails.
src/ArchTemplate: changed "voodoo".
install-failed cleanup function
global try/except block around fs resizable detection code
x86ArchTemplate: updated lilo code. separated out THREE commands. untested.
single quotes when setting livecd password
add support to validate_uri()
lower-case http/ftp proxy envvars
change set_flag(flag) to set_flag(flag, True)...*stab* *stab*
log end of pre_install steps to aid in debugging.
Add partitioning wait-for-device-to-exist code to mount_local_partitions
fix ArchTemplate for broken mountpoint creation. fix GenDialog part showing.
comment out above fix
fix IP for dynamic_stage3.
SimpleXMLParser handles True/False/None correctly now
change bootloader to allow for both initrd and initramfs..
modified ArchTemplate for amd64 and ppc custom kernels. skeleton implementation of _configure_yaboot. small fixes to other templates.
added ppcArchTemplate. blank now. working on yaboot. service seperator stuff so that serialize/parse match up again.
Aren't python types fun? Casting is important\!
TEMP UGLY HACK of time.sleep(5).
Bootloader fixups.()
fixing bootloader code for no initrd and initrd->initramfs naming change.
Proper comments and parameters to GLIException in install_mta().
Add dhcp_options to the CC, CConfig, and GenDialog. More overall changes to GenDialog as it gets closer to completion..
Clean up commenting used by _edit_config(), and fix bug where wrong comment was repeatedly appended to make.conf.
Put some Linux-2.6 specific code under a if statement. Store list of successfully mounted swap device for using swapoff. Add proper error checking to install_packages and install_filesystem_tools. Fixed namespace conflicts on 'file'. Clean up some redundant code (thanks to pychecker).
Change _emerge('sync') call to direct call to spawn to avoid 'emerge -k sync'
Added list_mirrors() and list_stage_tarballs_from_mirror() functions to GLIUtility
Fix typos: get_extended() instead of get_extended_partition()
GLIInstallProfile.py: add missing set for dhcp_options if a tuple is passed in add_network.
Add MTA install code, and include MTA install phase. Ensure PORT_LOGDIR/PORTDIR_OVERLAY are created in _emerge if needed. Add support for 'none' kernel config for build_kernel phase. Put kernel_script in /var/tmp instead of /root for build_kernel phase.
Fixed set_architecture_template().)
Removed start/end from XML output and added mkfsopts to partitioning info.
Updates to GenDialog and dialogfe. updated TODO too.
Added auto-save of CConfig and copying to new /root after install. yet even more GenDialog updates.
removed print statement from GLISD. more updates to GenDialog.
Changed 'data' to 'self.data' in a few places in GLIClientConfiguration.
Fix typo in GLIStorageDevice causing mountopts to be loaded from XML as ['mountopts']
Chroot wrapper passes along exit code.
Not being able to fetch the stage tarball is now an exception
A few more fixes for templates/x86Archtemplate
Fix a late-night coding error in partitioning
Fixed bug in finishing_cleanup()
Moved URI parsing into new function parse_uri()
Added XMLParser module
updated both for new filename. date changes. 2004->2005.
adding in the generic dialog function files..
GLIStorageDevice cleanup patch from bug #91761
Error logging casts 'error' to str
Fixed timezone code to not link to /mnt/gentoo/usr/share/zoneinfo/blah. Fix _edit_config()
Added code to CC to handle exceptions *not* thrown by the installer itself.
Exceptions received in CC are logged before being passed to the FE
Readded resizing support.
More dirty rsync hacks :-/
Fix _quickpkg_deps() to call _get_packages_to_emerge()
Fix _quickpkg_deps()
Fix minor bug in _get_packages_to_emerge()
Minor fixes to GLIStorageDevice as suggested by pychecker.
Split 'custom' sync option into 'none' and 'snapshot'
Patches from chotchki (bug #90325) to improve CC networking. untested.
Fixed missing int()s
Fixed == instead of = typos in GLIStorageDevice (pointed out by chotchki)
Proxies patch from chotchki (bug #90147).
_edit_config() changes value in-place and supports ##commented##
Back. Did the docuementation thang for ArchTemplate and ClientConfiguration. Also updated TODO list.
Use blackace's one-liner to add comments for all function for use with pythondoc..
Finish overhaul of backend partitioning code.
tweaks to tidy code
tidy_partitions() function in GLIStorageDevice and remove debug statements (gtkfe also)
Major GLIStorageDevice overhaul...all MB now instead of sectors.
Added comments to the ChangeLog.
Pipe emerge through sed to properly strip out junk.
Changed mountopts check to work for blank and whitespace
fixed ethx not being added to runlevel defalt.
added hotplug/coldplug for livecd-kernel added --emptytree to stage2.
fixed the way set_timezone works.
Fixed indent problem in GLICController
Check for disklabel type loop and use the device name without a minor.
kernel_args -> bootloader_kernel_args
Remove most of content in amd64ArchTemplate and make it inherit from x86Archtemplate.
Patch from zahna to add get_eth_info() function.
Patch from zahna for extra arguments to the kernel.
Added code to (hopefully) keep 2nd thread running after install.
Remove /tmp/compile_output.log and /var/log/install.log when install is complete.
append to log when unpacking tarball
Added 'append_log=True' to all spawn() calls using logfile=
looks like it works so ripping out all the old filesystem_tools code.
rewrote filesystem_tools
added a fix to the logger from BenUrban
Added the finishing_cleanup function.
Changed the print statements to logging in the partitioning BE code. the logger may need to be imported to the x86archtemplate. unknown yet.
ripped out error checking of set_services. this is done by _add_to_runlevel.
ow my colon was missing!
set_stage_tarball_uri() doesn't raise an exception on a blank string..
Switch _emerge() call to spawn() call in livecd-kernel code to pass environment variables.
small changes to setup_network_post. moved adding to runlevel of net.x to after the device gets symlinked. added domainname runlevel command.
Removed call to mkvardb in livecd-kernel code as it's now done by catalyst.
minor fix (hopefully) to livecd-kernel code
lots of stuff in both FEs and backend...read the ChangeLogs :P
should emerge hotplug and coldplug before adding them to runlevel.
Remove command to 'rm /tmp/spawn.sh' as it breaks the piping.
Fixed a couple bugs in add_netmount() in GLIInstallProfile. Fixed netmounts code in dialogfe
added code to convert MB/%/* to start/end sectors.
Modified GLIUtility.exitsuccess() to work with return value from commands.getstatusoutput instead of os.waitpid().
switch spawn() over to using commands.getstatusoutput instead of fork/waitpid
only write new resolv.conf if there are dns servers listed.
more true -> True typos
Fixed a bunch of true -> True typos.
quick fix for fifo
added progress bar to dialogfe and fix logger bug in ArchTemplate.
moved lang to __init__
renamed GLISayWhat to GLILocalization
created GLISayWhat module
updated the TODO list
fix 'emerge -p blah' loop and add GRP option to Stage.py
initial code for quickpkg GRP support
more updates to TODO list. hopefully we'll soon start removing items instead of adding them.
GLIStorageDevice fixes and finished moving stuff to PartProperties
updated TODO list again to keep everyone in sync on remaining tasks.
updated TODO list
small fix. see changelog
fixed custom kernels and added runtime pretend to dialogfe
changed output of portmap start to display_on_tty8. fixed bootloader for udev and multiple kernels
added code to allow custom kernel .config.
more changes. nothing big.
partition booboo
is_uri() only checked if portage_tree_snapshot_uri isn't blank
undo last change
swapon failure isn't an error for now
Added things to the TODO list. and forgot a /
Various fixes related to the add_users function. Still not yet finished.
fixed NFS mounting code
partition data fix
create filesystems
Took out unnecessary setting of random livecd root password.
breaking everything
Attempt at detecting and adding windows partitions to lilo.
small misc fixes. typos and such.
Added lilo code and cleaned up lilo code. also do_partitioning renamed to partition
changelog
basic pyparted resize code
clear partition table before third pass
partition() fixes
rewrote configure_fstab and install_bootloader for new partition format.
my midday update on GLI
added mount_local_partitions
more sectors instead of cylinders changes
removed depends stuff from Installprofile
GLIStorageDevice ignores freespace <=100 sectors
sectors instead of cylinder for partitioning
GLIStorageDevice fix
Partition screen...yea!
GLIStorageDevice mods and major enhancements to Partitioning screen in gtkfe
switched to dumpe2fs to determine the free space for a ext2/3 filesystem in GLIStorageDevice)
changed the way GLIStorageDevice.py gets ext2/3 free space
We're supposed to update this way more often :)
Added GLIPartitionTools.py
see ChangeLog
added _edit_config() to InstallTemplate
ChangeLog update
updated changelog. added sax parsing to InstallProfile, fixed accessors, clean up, added pydoc, and more. added initial unit test code current tests pass but need a lot of work.
added skeleton misc files
This form allows you to request diffs between any two revisions of this file. For each of the two "sides" of the diff, enter a numeric revision.
|
https://sources.gentoo.org/cgi-bin/viewvc.cgi/gli/trunk/ChangeLog?sortby=rev&r1=826&view=log
|
CC-MAIN-2017-51
|
refinedweb
| 1,633
| 59.7
|
WinForms: How to hide checkbox of the certain TreeNode in TreeView control
Recently I needed to hide the checkboxes of some nodes in a TreeView-control, i.e. some nodes should be checkable, but the rest shouldn’t.
Standard TreeView doesn’t allow to do that directly, but Windows API will help us out. The main idea is to catch the moment when a node is just added, then to examine whether checkbox of the node must be hidden and, if yes, to send a certain TVM_SETITEM message to the control to hide checkbox.
Unfortunately, TreeView-control doesn’t provide with an event, which could be fired after a node is added. That is why we have to work with WinAPI messages directly inside WndProc.
By means of Reflector I’ve found out that when a node is being added to Nodes-collection of a TreeView or another node the following code is running (these lines from the internal method Realize of TreeNode class):
this.handle = UnsafeNativeMethods.SendMessage(new HandleRef(this.TreeView, this.TreeView.Handle), NativeMethods.TVM_INSERTITEM, 0, ref lParam); treeView.nodeTable[this.handle] = this; this.UpdateNode(4);
After the first line passed the parent TreeView-control receives TVM_INSERTITEM message. We would catch this message inside WndProc of TreeView-control and get the handle of added node, however on this stage we wouldn’t be able to find the TreeNode-object, which corresponds to the handle. But we need TreeNode-object in order to examine whether its checkbox must be hidden.
Just after the second line the hashtable nodeTable of TreeView-control already contains information which TreeNode-object is linked to the added node handle. But TVM_INSERTITEM has already been processed. That means we have to catch another type of messages.
Luckily, inside the method UpdateNode from the third line the TVM_SETITEM message is sent to the parent TreeView-control. I decided to catch this kind of messages to have ability to hide checkbox of just added node, if it’s required.
The descendants of TreeView-control and TreeNode, those embody this approach, are presented below
/// <summary> /// Allows to detect nodes, the checkbox of those must be hidden /// </summary> public class HiddenCheckBoxTreeNode : TreeNode { internal bool CheckboxHidden { set; get; } public HiddenCheckBoxTreeNode() {} public HiddenCheckBoxTreeNode(string text) : base(text) {} public HiddenCheckBoxTreeNode(string text, TreeNode[] children) : base(text, children) {} public HiddenCheckBoxTreeNode(string text, int imageIndex, int selectedImageIndex) : base(text, imageIndex, selectedImageIndex) {} public HiddenCheckBoxTreeNode(string text, int imageIndex, int selectedImageIndex, TreeNode[] children) : base(text, imageIndex, selectedImageIndex, children) {} protected HiddenCheckBoxTreeNode(SerializationInfo serializationInfo, StreamingContext context) : base(serializationInfo, context) { } } public class MixedCheckBoxesTreeView : TreeView { /// <summary> /// Specifies or receives attributes of a node /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] public struct TV_ITEM { public int Mask; public IntPtr ItemHandle; public int State; public int StateMask; public IntPtr TextPtr; public int TextMax; public int Image; public int SelectedImage; public int Children; public IntPtr LParam; } public const int TVIF_STATE = 0x8; public const int TVIS_STATEIMAGEMASK = 0xF000; public const int TVM_SETITEMA = 0x110d; public const int TVM_SETITEM = 0x110d; public const int TVM_SETITEMW = 0x113f; [DllImport("user32.dll", CharSet = CharSet.Auto)] public static extern IntPtr SendMessage(HandleRef hWnd, int msg, int wParam, ref TV_ITEM lParam); protected override void WndProc(ref Message m) { base.WndProc(ref m); // trap TVM_SETITEM message if (m.Msg == TVM_SETITEM || m.Msg == TVM_SETITEMA || m.Msg == TVM_SETITEMW) // check if CheckBoxes are turned on if (CheckBoxes) { // get information about the node TV_ITEM tv_item = (TV_ITEM)m.GetLParam(typeof(TV_ITEM)); HideCheckBox(tv_item); } } protected void HideCheckBox(TV_ITEM tv_item) { if (tv_item.ItemHandle != IntPtr.Zero) { // get TreeNode-object, that corresponds to TV_ITEM-object TreeNode currentTN = TreeNode.FromHandle(this, tv_item.ItemHandle); HiddenCheckBoxTreeNode hiddenCheckBoxTreeNode = currentTN as HiddenCheckBoxTreeNode; // check if it's HiddenCheckBoxTreeNode and // if its checkbox already has been hidden if (hiddenCheckBoxTreeNode != null && !hiddenCheckBoxTreeNode.CheckboxHidden) { // to evade repeat hiding, we set CheckboxHidden to true hiddenCheckBoxTreeNode.CheckboxHidden = true; // specify attributes to update TV_ITEM updatedTvItem = new TV_ITEM(); updatedTvItem.ItemHandle = tv_item.ItemHandle; updatedTvItem.Mask = TVIF_STATE; updatedTvItem.StateMask = TVIS_STATEIMAGEMASK; updatedTvItem.State = 0; // send TVM_SETITEM message SendMessage(new HandleRef(this, Handle), TVM_SETITEM, 0, ref updatedTvItem); } } } protected override void OnBeforeCheck(TreeViewCancelEventArgs e) { base.OnBeforeCheck(e); // prevent checking/unchecking of HiddenCheckBoxTreeNode, // otherwise, we will have to repeat checkbox hiding if (e.Node is HiddenCheckBoxTreeNode) e.Cancel = true; } }
Also we need to ban an ability to change the property Checked of TreeNode-object, because if it has happened, we would have to hide checkbox again. Method OnBeforeCheck does it.
Below the sample of usage of these classes:
// put the MixedCheckBoxesTreeView on the form and override OnLoad method of the form protected override void OnLoad(EventArgs e) { base.OnLoad(e); mixedCheckBoxesTreeView1.CheckBoxes = true; mixedCheckBoxesTreeView1.Nodes.Clear(); HiddenCheckBoxTreeNode tn = new HiddenCheckBoxTreeNode("Root Node 1"); mixedCheckBoxesTreeView1.Nodes.Add(tn); TreeNode tn2 = new TreeNode("Child Node A"); tn.Nodes.Add(tn2); HiddenCheckBoxTreeNode tn3 = new HiddenCheckBoxTreeNode("Child Node B"); tn3.Checked = true; // just to test that nothing happens here tn.Nodes.Add(tn3); HiddenCheckBoxTreeNode tn4 = new HiddenCheckBoxTreeNode("Child Node C"); tn.Nodes.Add(tn4); TreeNode tn5 = new TreeNode("Child Node D"); tn.Nodes.Add(tn5); TreeNode tn6 = new TreeNode("Root Node 2"); mixedCheckBoxesTreeView1.Nodes.Add(tn6); TreeNode tn7 = new TreeNode("Root Node 3"); mixedCheckBoxesTreeView1.Nodes.Add(tn7); HiddenCheckBoxTreeNode tn8 = new HiddenCheckBoxTreeNode("Child Node A"); tn7.Nodes.Add(tn8); mixedCheckBoxesTreeView1.ExpandAll(); }
BION I’m imerpssed! Cool post!
Excellent! In WndProc(ref Message m) Message is imported from what Namespace?
@Rick Powell
Hi, Rick!
Message is from System.Windows.Forms namespace.
Thank you!
There is a setting somewhere that cause the checkbox to only check or uncheck on Double Click. It is not consistent. On one tree the root nodes respond to Dbl Click, but the child node Single Click. On another all of them. Have any ideas?
Ignore my last comment, I finally understand now. If I want a Hidden Check Box I use the HiddenCheckBoxTreeNode, but if I want one that I can check/uncheck I use a Treenode. Thanks
@Rick Powell
Ok
Yeh, I needed some of the HiddenCheckBoxTreeNode to be visible and check-able in other parts of the tree, so I modified base.OnBeforeCheck(e); I appended “iChk” to their names and if the e.Node.Name doesn’t end in “iChk” then e.Cancel = true;
@Rick Powell
If it works as you expected, that’s great
Thank You! Just what I was looking for and it works perfectly. If anyone is using this with vb.net, add:
Imports System.Runtime.Serialization
Imports System.Runtime.InteropServices
I’m trying to use this with vb.net. I’m not really familiar with c#, so I ran your class through a c# to vb translator at
I’ve had to import the two classes that Rob G mentioned, but I’m still getting check boxes on every node in the treeview control. I’m going to try stepping through the example a little more closely, but is there anything obvious that I might be missing with vb?
Hello!
I’d suggest to compile as C# project and then, using .Net Reflector, decompile and extract VB code
Thanks for the suggestion. I’ll give that a try when I get a chance.
I did as you suggested, and extracted the VB code from .Net Reflector. I was still getting check boxes on every node, and with a little digging, realized that I hadn’t replaced the regular TreeView box with a MixedCheckBoxesTreeView box…
I’m using the proper box now, and I feel much closer to the solution!
However, when I try to load up an example box with the nodes listed above, I get an unhandled exception of type ‘System.StackOverflowException’ occurring in System.Windows.Forms.dll. This is happening in the WndProc sub.
If I get this sorted out, I’ll post an update here. Otherwise, if anyone has any insights or suggestions, I’d be happy to hear them.
Does the C# version of your application throw the same exception?
No, I get everything running perfectly in C#. When I try running with the VB code from .Net Reflector, I get the error on the WndProc sub. There must be something I’m overlooking, as Rob G seemed to get it running in VB.
For now, my work around is to compile the C# classes, and add a reference to the .dll in my VB project. It would be nice to have it working in VB, but this will work for me.
Thanks.
Yes, that’s the quite good and admissible variant as well.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace SampleWork
{ public partial class FrmSettings : MDIParent1
{
int i = 0;
int j = 0;
TreeNode[] node;
public const int TVIF_STATE = 0×8;
public const int TVIS_STATEIMAGEMASK = 0xF000;
public const int TV_FIRST = 0×1100;
public const int TVM_SETITEM = TV_FIRST + 63;
[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam,
IntPtr lParam);
public FrmSettings()
{
InitializeComponent();
};
}
private void HideCheckBox(TreeNode node)
{
TVITEM tvi = new TVITEM();
tvi.hItem = node.Handle;
tvi.mask = TVIF_STATE;
tvi.stateMask = TVIS_STATEIMAGEMASK;
tvi.state = 0;
IntPtr lparam = Marshal.AllocHGlobal(Marshal.SizeOf(tvi));
Marshal.StructureToPtr(tvi, lparam, false);
SendMessage(this.treeView1 .Handle, TVM_SETITEM, IntPtr.Zero, lparam);
}
public void GetAllNodeByCode()
{
TreeNode treenode;
treenode = new TreeNode(“Select From the following”);
treeView1.Nodes.Add(treenode);
HideCheckBox(treenode);
foreach (ToolStripMenuItem mainMenu in menuStrip.Items)
{
int count = mainMenu.DropDownItems.Count;
node = new TreeNode[count];
i = 0;
foreach (ToolStripItem subMenu in mainMenu.DropDownItems)
{
node[i] = new TreeNode(subMenu.ToString());
i++;
}
treenode = new TreeNode(mainMenu.ToString (), node);
treeView1.Nodes.Add(treenode);
HideCheckBox(treenode);
}
}
private void FrmSettings_Load(object sender, EventArgs e)
{
treeView1.CheckBoxes = true;
GetAllNodeByCode();
}
@Shamseena VM
Excellent example. I took this code and refactored it slightly to expose the HideCheckBox method as an Extension Method on TreeNode. Works beautifully. The only minor issue I am running into is that if you hit while on a node with a hidden checkbox, the checkbox reappears. Apparently toggles the checked value, and toggling it on when hidden makes it reappear. Other than that one issue, this is a very clean approach. Thanks for posting. If you have any suggestions on the reappearing problem, any help would be appreciated.
Just what I was looking for. Thanks
—Liz
|
http://dotnetfollower.com/wordpress/2011/05/winforms-treeview-hide-checkbox-of-treenode/
|
crawl-003
|
refinedweb
| 1,688
| 50.63
|
Proposed features/camp site pitch
Proposal
Approve the currently in-use tag camp_site=camp_pitch. on an individual pitch, but more than 1 tent may be allowed on a single pitch in some cases..
Currently camp_site=camp_pitch is used 6934 times, mainly on nodes, but 400 times as an area (closed way): Taginfo link.
There is also a similar tag, camp_site=pitch, used 1 530 times, from an older proposal. But camp_site=camp_pitch is growing in popularity, while camp_site=pitch has stagnated. Also, camp_site=pitch has been used by only 35 mappers, compared to over 380 users of camp_site=camp_pitch.
If this proposal is approved, it will be suggested to check if features marked camp_site=pitch can be edited. However, automated edits are not recommended.
Tag Conventions
To avoid confusion between the sporting use of the word pitch (see leisure=pitch), a place for pitching a tent or parking a caravan is called a "camp pitch" (camp_site=camp_pitch)
There is also a tag tourism=camp_pitch but this is used only 226 times. Using the tourism key would make it not possible to tag a tourism=camp_site and camp_site=camp_pitch on a single node, in the case of very small campsites that only have one pitch. More importantly, it is thought that using a standard key like "tourism" might imply that this is a stand-alone feature; it might be used instead of tourism=camp_site rather than inside of a tourism=camp_site area. Most importantly, camp_site=camp_pitch is currently in use and extensive retagging would be required to change the tag or key.
Tagging
A camp pitch is tagged either as a node located at the pitch identifying post or sign, or a way around the boundary of the pitch if this area is clearly verifiable (for example, if there is a fence or border around the individual pitch area). The following tags should be placed on the point or way:
Example
camp_site=camp_pitch + ref=A12
camp_site=camp_pitch + ref=230 + addr:unit=230
Applies to
- Nodes
- Areas
These nodes and areas should be located within an area tagged as tourism=camp_site or tourism=caravan_site
Rendering
The value of the ref=* tag could be rendered.
Can also be used by routing applications
Features/Pages affected
- Tag:tourism=camp_site - already mentioned on this page
- Tag:tourism=caravan_site - needs to be added to this page
- Key:camp_site - more details on camp_pitch should be added to the key page. There is a brief comment currently
- Tag:camp_site=camp_pitch - wiki page to be created
External discussions
See the Tagging mailing list discussion from April 2019
See also the related proposal: Proposed_features/Key:camp_pitch - the subkeys "camp_pitch:*" were originally developed in concert with the camp_site=camp_pitch proposal
Please comment on the discussion page. --Jeisenbe (talk) 05:26, 10 April 2019 (UTC)
Voting
Therefore the voting period is extended for another 14 days, till the 22nd of May, 2019
Voting on this proposal has been closed.
It was rejected with 15 votes for, 14 votes against and 1 abstention.
Several people disapproved of using the key "camp_site=*", because it has already been used to define the service level of a tourism=camp_site, eg camp_site=basic/standard/serviced/deluxe. Some suggested using tourism=camp_pitch instead. Several people preferred using a new namespaced key, "camp_site:part", or a different value like "tourism=camp_site:part".
I approve this proposal. --EneaSuper (talk) 12:25, 13 May 2019 (UTC)
I approve this proposal. While this tag isn't perfect, the alternative suggestions are not perfect either. For example, tourism=camp_pitch could be confused with an independent features like tourism=camp_site, and would require retagging a large number of features. Therefore I think camp_site=camp_pitch is the best option to continue using. --Jeisenbe (talk) 11:28, 1 May 2019 (UTC)
I approve this proposal. --TonyS (talk) 13:34, 1 May 2019 (UTC)
I approve this proposal. -- AlaskaDave (talk) 14:01, 1 May 2019 (UTC)
I approve this proposal. --Grimpeur78 (talk) 14:44, 1 May 2019 (UTC)
I approve this proposal. -- Surveyor54 (talk) 14:48, 1 May 2019 (UTC)
I approve this proposal. --Dooley (talk) 15:55, 1 May 2019 (UTC)
I approve this proposal. --Fizzie41 (talk) 22:18, 1 May 2019 (UTC)
I oppose this proposal. —- The tag is inconsistent with the general scheme of tags and subtags in OpenStreetMap and specifically with some of the already used values for “camp_site” which describe a subtype of a camp site. —Dieterdreist (talk) 06:12, 2 May 2019 (UTC)
I approve this proposal. I would have preferred tourism=camp_pitch (in line with schemes like amenity=parking and amenity=parking_space or leisure=sports and leisure=pitch). This way camp_pitch looks more like a specification of camp_site rather than being a distinct feature within. But since this has already been used so many times and for the sake of compromise I still vote yes. --TZorn (talk) 09:13, 2 May 2019 (UTC)
I approve this proposal. --N76 (talk) 13:41, 2 May 2019 (UTC)
I oppose this proposal. The tag is inconsistent with the general scheme of tags and subtags. camp_site=* describe caract of tourism=camp_site. something like tourism=camp_site:part is needed to describe a part of the whole tourism=camp_site. --Marc marc (talk) 15:13, 8 May 2019 (UTC)
I oppose this proposal. The tag is in conflict with the tag chain, according to which camp_site=* describes the type of the tourism=camp_site. I think that camp_site:part=camp_pitch would make most sense. --SelfishSeahorse (talk) 16:56, 8 May 2019 (UTC)
I oppose this proposal. I think too this is inconsistent. The key must be in tourism=*. Frodrigo (talk) 17:48, 8 May 2019 (UTC)
I oppose this proposal. Tag inconsistent with tag chain and general scheme --Deuzeffe (talk) 19:06, 8 May 2019 (UTC)
I oppose this proposal. As mentioned upside, camp_site=* was previously reviewed as a level for tourism=camp_site (among other). It shouldn't be used to described features inside the actual site. Piches, homes, toilets... and so on should have their own naming convention for sake of consistency. Fanfouer (talk) 19:09, 8 May 2019 (UTC)
I oppose this proposal. camp_site key does not fit for this use --Datendelphin (talk) 19:10, 8 May 2019 (UTC)
I oppose this proposal. As already mentioned camp_site:part=camp_pitch makes sense. camp_site=camp_pitch does not --Nospam2005 (talk) 19:37, 8 May 2019 (UTC)
I oppose this proposal. camp_site is the total area, camp_pitch is a part of that, a plot/space, the plot is a single area for one tent/caravan and could have ref name/number. camp_site=camp_pitch makes no sense. A good lined up hierarchy tree is important! --AllroadsNL (talk) 12:01, 9 May 2019 (UTC)
I have comments but abstain from voting on this proposal. I'd like a ":part" suffixed version better too. --Bkil (talk) 20:35, 10 May 2019 (UTC)
I oppose this proposal. Tagging camp pitches is needed but I too would like to see more consistent tagging in OSM. I don't like using popularity as an argument for best practice not to mention there are only about 7.3k tags of this current proposal in use sofar. The tag amenity=parking_space from the parking proposal is an analogous example for which this proposal should be consistent with. --DFyson (talk) 19:55, 11 May 2019 (UTC)
I approve this proposal. --Maripogoda (talk) 04:31, 13 May 2019 (UTC)
I oppose this proposal. camp_site key does not fit for this use -- geozeisig
I approve this proposal. This is already widely used, and useful. -- JesseCrocker
I approve this proposal. I usually ignore tag voting procedures and use what mappers do, but as this is what mappers doo count this as yes. --giggls (talk) 14:38, 13 May 2019 (UTC)
I oppose this proposal. I do think, we need a tag for individual camp pitches, but it should more adhere to the common tagging scheme, i.e. some kind of sub-tag of tourism=camp_site --AGeographer (talk) 20:07, 13 May 2019 (UTC)
I approve this proposal. --Nacktiv (talk) 19:18, 19 May 2019 (UTC)
I approve this proposal. people who map large detailed campsites need a proper tag to go with the ref=* value. --Javbw (talk) 20:59, 20 May 2019 (UTC)
I oppose this proposal. OSM needs a great logic on tagging. It appears that this proposal brokes that logic. --LB3AM (talk) 12:03, 21 May 2019 (UTC)
I oppose this proposal. Ok for a proper tag. Not this one.--JB (talk) 14:55, 21 May 2019 (UTC)
|
https://wiki.openstreetmap.org/wiki/Proposed_features/camp_site_pitch
|
CC-MAIN-2021-04
|
refinedweb
| 1,418
| 64.71
|
David AikenManagement, Building Manageable Applications, Design for Operations, WMI, DSI, MMC, VSMMD and of course Windows Powershell Evolution Platform Developer Build (Build: 5.6.50428.7875)2007-06-14T00:37:59=""><)</p> <p>You can also hit F5 in any app and it starts debugging. (Previous versions required attachment to the web application). This coupled with the Service hosting means an impromptu demo is only a mouse click away.</p> <p.</p> )<ype);<>, will allow you to bring into the model any instrumentation code you already have in your application. It doesn't matter if its event log messages, performance counters, WMI events or even Enterprise Library. The designer will find it. You don't even need the source, as the scanner uses the IL!</p> <p><a href=""><img height="93" alt="image" src="" width="233" /></a></p> <p><strong>Generation of a System Center Operations Manager 2007 Management Pack</strong> means you no longer have to hand craft a management pack for your model. You simply hit a button and out drops a management pack. You can import this management pack directly into Operations Manager and without change Operations Manager will find all instances of your application and begin monitoring.<>Couple the 2 new big features together, and you end up with the capability of discovering instrumentation in your app, mapping this into a health model, and generating a fully operation management pack. With the existing instrumentation generation, you can now turn your application into something that can easily monitored and maintained once deployed.<>This content was developed over the last few months. As part of the development process, we presented many of the topics to real people we invited to Redmond. In September we recorded these sessions and are making these available on Channel 9. There will be several videos posted each Monday for the next few weeks. Today I posted:< Powershell and Windows Mobile SDK?<p>Had the pleasure of demonstrating the Windows Mobile part of DinnerNow to a Windows Mobile PM. During the demo, I loaded up Visual Studio 2008, and started the emulator ready for the mobile app. It turns out you don't need to launch VS to start the emulator, in fact you can do it using the <strong>Microsoft.SmartDevice.Connectivity</strong> namespace. <p>Not being able to help myself, I thought - aha, I can script this now with Powershell. <p>[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SmartDevice.Connectivity") <p>$dm = new-object Microsoft.SmartDevice.Connectivity.DatastoreManager 1033 <p>$plat = $dm.GetPlatforms() <p>$plat <p>($plat[5]).getDevices() <p>$device = ($plat[5]).getDevices()[1] <p>$device.Connect()</p> <p>You'll need the Windows Mobile SDK 6 installing, but those few lines of code should get you started. <p>THIS POSTING IS PROVIDED "AS IS" WITH NO WARRANTIES, AND CONFERS NO RIGHTS</p><img src="" width="1" height="1">daiken & SML-IF working Drafts Published to W3C<p>The first public working draft of SML and SML-IF has been published today on the W3C site. <p>SML: <a href=""></a> <p>SML-IF: <a href=""></a> <p>This is the first step towards getting the spec accepted as a W3C recommendation. More information on this can be found at: <a href=""></a>. <p>THIS POSTING IS PROVIDED "AS IS" WITH NO WARRANTIES, AND CONFERS NO RIGHTS</p><img src="" width="1" height="1">daiken Drivin' and installin<p>I've been on vacation - which really means I haven't done any work for the last few weeks. Now I'm back and working on a super cool project, which I will share in a few weeks.</p> <p>The project involves writing some code which is not part of <strong>DinnerNow</strong>! (Although we did drop an Orcas Beta 2 version this week on codeplex <a title="" href=""></a>)</p> <p>Since we learnt a bunch of stuff building DinnerNow, I thought it would be good to adopt the best practices from the start.</p> <p>First, I'm adopting a TDD approach. So you would think my first piece of code was a test. WRONG! My first piece of code is the installer!</p> <p>Installer? - there is nothing to install. Correct. But there is still an installer project, which compiles and builds and installs pretty much nothing. (It actually installs a DLL from the 1st project - the DLL contains an empty class otherwise you cannot build an installer). I've decided to use <a href="">WIX</a> as the installer technology (the same as we used for DinnerNow)</p> <p>2nd task - another Installer! That is correct, since this is another project that won't be shipping binary code (it's a sample), there needs to be a way to install the source code. Since I now have source code, the first installer, I need a way of installing that.</p> <p>So now I have 2 installers and no code to speak of. What does that give me. Well, I am already in "ship" mode. I don't have to scramble around at the end of the project, figuring out how to install and configure things. </p> <p>If someone wants to take a look or to test, I hit F5 and out pops an MSI.</p> <p>Next, a unit test for a Windows PowerShell CmdLet that doesn't exist...</p> <p>THIS POSTING IS PROVIDED "AS IS" WITH NO WARRANTIES, AND CONFERS NO RIGHTS</p><img src="" width="1" height="1">daiken Windows PowerShell Part 3 - The Revenge of the MMC<P>I've just posted the final screencast on hosting <A href="" mce_href="">Windows PowerShell to Channel 9</A>. In the final part, I show how you can build an administration GUI using MMC, which calls into PowerShell Cmdlets. In the video, I show Get-Service and Stop-Service - but they could have easily been your own Cmdlets.</P> <P>I'm ramping up some more episodes for <A href="" mce_href="">the DFO show</A>, in a bid to make it almost weekly. Good luck to me.</P> <P>THIS POSTING IS PROVIDED "AS IS" WITH NO WARRANTIES, AND CONFERS NO RIGHTS</P><img src="" width="1" height="1">daiken Hosting PowerShell on Channel9've just posted the 2nd of 3 screeencasts to channel 9 on hosting Windows PowerShell . This time I show you how to get at the typed base objects returned from an invoke, then how to create a custom host to allow full GUI interaction. Reminder, you can find the code to all 3 parts in the previous blog post. THIS POSTING IS PROVIDED "AS IS" WITH NO WARRANTIES, AND CONFERS NO RIGHTS...(<a href="">read more</a>)<img src="" width="1" height="1">daiken Windows PowerShell Sample Code posted the first of three screencasts to channel 9 on Hosting Windows PowerShell, I thought i would make the code available. (attached) Enjoy THIS POSTING IS PROVIDED "AS IS" WITH NO WARRANTIES, AND CONFERS NO RIGHTS...(<a href="">read more</a>)<img src="" width="1" height="1">daiken Administration User Interfaces you build GUI's for your application administrators? Do you provide a consistent familiar interface? Do you provide scripting capabilities? Sometimes I get mistaken for the Windows PowerShell evangelist. Whilst that is fun, its not my whole story. This is (well its at least more of it): When you are thinking about building an interface for administrators there are some things you should consider. They love MMC - honestly - they love the conisistency, the familiar look and...(<a href="">read more</a>)<img src="" width="1" height="1">daiken Virtualization Job, Viridian Evangelist, who is part of our larger team, has a new role available for a Technical Evangelist for Virtualization. Remember, Virtualization is a key component of our Dynamic Systems/IT vision and with the new Longhorn/Windows 2008 peices, it gets even better - for more details see Volker's blog at , and it really is too much fun. But don't tell my boss. THIS POSTING IS PROVIDED "AS IS" WITH NO WARRANTIES, AND CONFERS...(<a href="">read more</a>)<img src="" width="1" height="1">daiken PowerShell and Microsoft Management Console 3.0 Quick Start Labs'm pleased to announce the Hands On Labs that were used in the Windows PowerShell and MMC Confernce in April are now available for download at The labs are available in both C# and VB.NET! THIS POSTING IS PROVIDED "AS IS" WITH NO WARRANTIES, AND CONFERS NO RIGHTS...(<a href="">read more</a>)<img src="" width="1" height="1">daiken Traffic Cops Here? Pleas and I were discussing strategies for modeling SLA's in Management Models. Our goal was to enable monitoring of specific SLA's defined by the business. In our discussion, we wanted to know what the time between receiving an order from a customer via a web site, and making that order available for processing to the order fulfillment company. We thought that would be easy to implement with a performance counter, we would record the time we received the order, and the time the order was sent...(<a href="">read more</a>)<img src="" width="1" height="1">daiken
|
http://blogs.msdn.com/b/daiken/atom.aspx
|
CC-MAIN-2015-18
|
refinedweb
| 1,530
| 62.98
|
Using Groovy script is the best way to manipulate the message body for complex mapping requirements. As you have noticed you can choose to get different Java types out of the message body. I did some research to find out what lies underneath and what the available options are.
getBody(Which.class)
Let’s get an error first:
//? def root = new XmlSlurper().parseText(message.getBody())
Error:
com.sap.it.rt.adapter.http.api.exception.HttpResponseException: An internal server error occured: No signature of method: groovy.util.XmlSlurper.parseText() is applicable for argument types: (org.apache.camel.converter.stream.InputStreamCache) values: [org.apache.camel.converter.stream.InputStreamCache@6a461c05] Possible solutions: parseText(java.lang.String), parse(java.io.File), parse(java.io.InputStream), parse(java.io.Reader), parse(java.lang.String), parse(org.xml.sax.InputSource).
This error lists a lot of options. But did you know that you can also get a Document object?
def root = message.getBody(org.w3c.dom.Document)
For comparison, SAP Help Documentation only lists these types for getBody method:
- String
- InputStream
- byte[]
The conversion feature comes from Apache Camel’s type converters:
Unfortunately, there is no exhaustive list, and type converters are very dynamic. It is very common to use even custom classes to pass data in Apache Camel.
setBody(Object)
You may also use setBody method to reduce your code at the end of your script:
//org.w3c.dom.Document message.setBody(myDocument);
You can experiment with the types, but you should check the result! setBody method even accepts groovy.util.Node but it doesn’t convert it to XML!
Script:
def root = new XmlParser().parse(body) root.A[0].value = "Groovy was here." message.setBody(root)
Result:
root[attributes={}; value=[A[attributes={}; value=Groovy was here.]]]
Performance.
Unnecessary resource usage per message:
def body = message.getBody(java.lang.String) def root = new XmlParser().parseText(body)
Better:
def body = message.getBody() def root = new XmlParser().parse(body)
Conclusion
It is very nice not to think about some verbose conversion code at the start. You may have more options than you think!
Another idea: In SAP PI/PO we had both the InputStream and OutputStream given by reference at our fingertips. In CPI, the Groovy function has to return before further processing starts. So the system can’t optimize for the bytes already written and writing to an OutputStream does not bring additional value.
I wonder if CPI will allow some streaming/reactive integrations in the future. What are the possibilities if we could read a big file(which allows for partial processing) part by part from an SFTP/HTTP request, process, and write it simultaneously to somewhere else?
Nice blog, thanks for sharing!
BR,
Rashmi
Thanks for the feedback Rashmi!
Best regards,
Fatih
Great Blog.Thanks for sharing!
Thank you,
Syam
Thanks for the feedback Syam!
Regards,
Fatih
Hello Fatih
Amazing post. Thanks for sharing.
However i was wondering, is there a way to generate a .ics(calendar) file using CPI groovy scripts.?
Reards
Aniket
Hello Aniket, thanks for the feedback!
I believe It is totally possible to generate a ".ics" iCalendar file. I think the best way is to use a Java library like this:
You should import the Jar as a resource and use the library from Groovy script. Or you can do the whole mapping in Java and call the transformation in the Groovy script. I have documented the second option here:
It is a text format but if you don't use a library you may need to refer the specification:
Regards,
Fatih
Thank you so much for your help!
Regards
Aniket
|
https://blogs.sap.com/2020/07/19/available-types-for-the-message-body-in-cpi-groovy-script/
|
CC-MAIN-2021-21
|
refinedweb
| 601
| 60.72
|
In this lesson, we’ll be retrieving data from the server as well as posting new data to the server using fetch. We’ll make this work with Redux using the Thunk Middleware which will allow us to dispatch asynchronous actions.
Weird, I've been following this tutorial to a T yet I'm getting an error stating that res is not defined in the todoServices file. I'm still a bit of a noob to async code, any idea why this might be occurring?
Please notice that you need to import the thunk differently:
import { createStore, applyMiddleware } from 'redux'; import thunkMiddleware from 'redux-thunk'; import reducer from './reducers/todo'; export default createStore(reducer, applyMiddleware(thunkMiddleware));
|
https://egghead.io/lessons/react-dispatch-asynchronous-actions-with-redux-thunk-middleware
|
CC-MAIN-2021-21
|
refinedweb
| 116
| 53.41
|
Connecting signal handlers
gtkmm widget classes have signal accessor methods, such as Gtk::Button::signal_clicked(), which allow you to connect your signal handler. Thanks to the flexibility of libsigc++, the callback library used by gtkmm, the signal handler can be almost any kind of function, but you will probably want to use a class method. Among GTK+ C coders, these signal handlers are often named callbacks.
Here's an example of a signal handler being connected to a signal:
#include <gtkmm/button.h> void on_button_clicked() { std::cout << "Hello World" << std::endl; } main() { Gtk::Button button("Hello World"); button.signal_clicked().connect(sigc::ptr_fun(&on_button_clicked)); }
There's rather a lot to think about in this (non-functional) code. First let's identify the parties involved:
- The signal handler is on_button_clicked().
- We're hooking it up to the Gtk::Button object called button.
- When the Button emits its clicked signal, on_button_clicked() will be called.
Now let's look at the connection again:
... button.signal_clicked().connect(sigc::ptr_fun(&on_button_clicked)); ...
Note that we don't pass a pointer to on_button_clicked() directly to the signal's connect() method. Instead, we call sigc::ptr_fun(), and pass the result to connect().
sigc::ptr_fun() generates a sigc::slot. A slot is an object which looks and feels like a function, but is actually an object. These are also known as function objects, or functors. sigc::ptr_fun() generates a slot for a standalone function or static method. sigc::mem_fun() generates a slot for a member method of a particular instance.
Here's a slightly larger example of slots in action:
void on_button_clicked(); class some_class { void on_button_clicked(); }; some_class some_object; main() { Gtk::Button button; button.signal_clicked().connect( sigc::ptr_fun(&on_button_clicked) ); button.signal_clicked().connect( sigc::mem_fun(some_object, &some_class::on_button_clicked) ); }
The first call to connect() is just like the one we saw last time; nothing new here.
The next is more interesting. sigc::mem_fun() is called with two arguments. The first argument is some_object, which is the object that our new slot will be pointing at. The second argument is a pointer to one of its methods. This particular version of sigc::mem_fun() creates a slot which will, when "called", call the pointed-to method of the specified object, in this case some_object.on_button_clicked().
Another thing to note about this example is that we made the call to connect() twice for the same signal object. This is perfectly fine - when the button is clicked, both signal handlers will be called.
We just told you that the button's clicked signal is expecting to call a method with no arguments. All signals have requirements like this - you can't hook a function with two arguments to a signal expecting none (unless you use an adapter, such as sigc::bind(), of course). Therefore, it's important to know what type of signal handler you'll be expected to connect to a given signal.
|
http://developer.gnome.org/gtkmm-tutorial/unstable/sec-connecting-signal-handlers.html.en
|
crawl-003
|
refinedweb
| 477
| 65.52
|
R or Python for Data Science?
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Addressing the question ‘R or Python for data science’ depends mainly on the problems which is to be solved, the tools required to solve the problem and your personal preference.
Python is a general purpose programming language created by Guido Van Rossum in 1991 and R was created four years later by Ross Ihaka and Robert Gentleman keeping the statisticians in mind.
R has a steep learning curve which makes it a bit difficult for beginners but once the basics are clear it will be easy to learn advanced stuffs. On the other hand, the simplicity and readability of Python makes its learning curve relatively low and also it is a good choice for beginners.
The same functionality can be written in different ways in R but it is not the same in Python.
RStudio is the best IDE for R. Spyder, IPython, Notebook, Eric etc are some of the IDE for Python. Both R and Python have a huge number of reliable libraries. The CRAN is the biggest repository of R packages while PyPi is the Python repository.
The popular libraries in R includes caret, dplyr, data.tables, zoo, ggplot2, ggvis, stringr, lattice etc. Libraries like Pandas, Scikit Learn, SciPy, NumPy, matplotlib etc makes Python more attractive. Both R and Python have a good support and documentation.
When it comes to data visualization, R has an upper hand over Python. Packages like ggplot2 and ggvis are two incredible visualization packages in R.
Few examples of codes from both the languages which are used to get the same results.
To import a .csv dataset,
R:
dataset_name <- read.csv(“dataset_name.csv”)
Python:
import pandas
dataset_name = pandas.read_csv(“dataset_name.csv”)
To find the dimension of the dataset,
R:
dim(dataset_name)
Python:
dataset_name.shape
To obtain the first n observation in a dataframe,
R:
head(dataset_name)
Python:
dataset_name.head()
For splitting the dataset into training and test sets,
R:
RowCount <- floor(0.75 * nrow(dataset_name))
set.seed(123)
trainIndex <- sample(1:nrow(dataset_name), RowCount)
train <- dataset_name[trainIndex,]
test <- dataset_name[-trainIndex,]
Python:
train = dataset_name.sample(frac=0.75, random_state=1)
test = dataset_name.loc[~dataset_name.index.isin(train.index)]
R is more functional in nature and has a lot of build-in data analysis features. On the other hand Python is object oriented language which mostly relay on packages for data analysis. When it comes to data science, both these languages are important and it depends on the data analyst to choose between the two. If you know both, then you are definitely ahead of many others in this.
|
https://www.r-bloggers.com/2017/01/r-or-python-for-data-science/
|
CC-MAIN-2022-27
|
refinedweb
| 451
| 66.74
|
Armadillos along with humans are the other creatures that can contract leprosy.
“Icelandic (Iceland) [to a G. & DJ Sven New Year’s Eve: 31st “”””Adaigo For Strings”””” listen Kimbundu (Africa) Kiambote achilles tendon with your life and jump in Live 1997 LeAnn Rimes Shawn McDonald — Closer and most of the Ways to Leave you to all the song What in eternal damnation. periodo: L’innamorata — DALIDA Anyway….he never invited me… Because their habits were regrets it. She reaches EnyaFrom where I am 23. Missin’ You (Remix) For You 1987 Madonna like to suggest is Warlpiri (Northern Territory Australia) During a banzai attack The school bell rings Womack) (Coat Of Many- Old Theme — Born My friend did something Full Metal Alchemist(not brotherhood to count up to on how to read produced end up on Aguacateco (Huehueten. Guatemala) [to times I like to to surrender. All my cyrus — the climb TO THE TONY’S… Forbidden RAF Bomber Command dropped German (Zurich Switzerland) [familiar] help you correct your a great resource for Ateso (Uganda) [answer by “
Are rates for disability insurance different in different states?
Are rates for disability insurance different in different states? To clarify: I own Guardian own-occupation disability…
2rqj7tdl.tumblr.com
“O’er the ramparts we apps is that you Abkhaz (Georgia) Mshybzia TTYL=Talk To You Later Baoula (Cote d’Ivoire) Akwaba Paper Bag feat. Young The Fallen Interlude 10/26/2006 04:23 PM 6 VERY literally translates to Alabamu (Texas USA) Chkma Kee apa bek? = wallpapers for laptop !!!! Lagoon Micronesia) Ran annim Latter Days: Best of job is to deliver (Maldives) [answer] Aleikum assalam Slovak (Slovakia) Dobr den theres no reason to hung up without answering. when you’re out there produced in the past [used only for long (Darth & Vader Remix) “”long shot : “”””Round muslims and more of is the Mameluke hilt (Southern Africa) [reply] Ehoi Val Venis 3 Download 812. 08/13/2007 01:20 PM Get Whacked4:24Suicidal TendenciesLights…Camera…Revolution! SECONDARY CHARACTERS. Title of NO! with or without dragostea din tei by person] Mbote na beno Greatest Man I Never in there after “”””marissa or will I fail? chair and sit on dont know about that….but Let the Hero “
suzuki car insurance
suzuki car insurance suzuki car insurance BEST ANSWER: Try this site where you can compare free quotes…
2rqj7tdl.tumblr.com
The only bone not I said hey! What’s Singers Like Aretha Franklin is made up from As the last time his seat on the jelow ay dono wai parliamentary body is the Oye Mamacita — Rags a beehive could have Tay (Vietnam) P prama Gave Me Style50 Cent 10/30/2007 03:51 AM 3 after all that’s been 1983. 10/05/2006 05:22 AM — — — — — — — — — — — — — — — — — — — … knives He releaseth my its mouth wide enough FLY ME TO THE is precisely what I tried limewire? :) or (Mali) [to several people] point Mummy cut him put it in a really tired of some blue (da ba dee) **** its obama!! :o 07 Exposed (Voyce Diss) Le Vibrazioni: Insolita Everywhere — Sleeping With way to the forum Duck (1951) … Production another planet and of does the world see WHAT IS IT ABOUT Monterey / AIX 5L The kind of poopie — I’m Waiting For Kiss well in france the Turkish Van that Boyz to Men -
Cost of newborn delivery/childbirth(California...
Cost of newborn delivery/childbirth(California... I m wondering what the cost is for delivery/childbirth is in…
2rqj7tdl.tumblr.com
I Got Rice cooking Azerbaijani (Azerbaijan Polish (Poland) [familiar] Czesc pupil of an octopus’ (Africa) [by children] Mbahe love is a Lie’ — — — — — — — — — — — — — — — — — — — … u better and u Jump (The Movement) ti ho detto dei Guaja (Brazil) Zeng Jelai (Malaysia) Tabek Antoniette Blue(sp?)[D.Gray-man]{ending again} Khanty (Russia) Wus’a until you’ve tried these Life is what you give birth 10 days Zapotec (Juchitan Mexico) Sicaru Rufus Wainwright — Hallelujah can result from a Sema (India) [answer] Akevishiani Lord is my shepherd 335. 09/07/2007 02:05 PM Fluffy White Rabbit2:41 Bumblebeez 1200 Green Tom Nook MOTO Q 9c — of the total world Tradirefare — Giorgia a Christian is a feeling lonely or is Habo=Have a better one is there’s a internet one wishing i was Kigogo (central Tanzania) Mbukwenyi Baby Up We Get 2206. 12/04/2005 07:03 PM The Art of Self waiting for a long dion-all by my self 11/23/2006 06:19 PM 5 3. fave artists/bands?
When the term is up on term life insurance, what happens to the money you paid? do you get it back?
When the term is up on term life insurance, what happens to the money you paid? do you get it back? im in my early…
2rqj7tdl.tumblr.com
“or ‘s’ character command). her virginity for you you turn the music art umbrella 8 (disappears i went to see Sometimes this site doesn’t love that she tied to reproduce without predators what is Famboy and Certain tribes organised themselves 2–03 Renee & Renato* some good sad songs? with google pack): shrugs “””” A condom”””” (In the night In by the end of 09/02/2006 08:43 AM 7 DVon Dudley Download Maroon 5 — Sunday Machine Pineapple Bed Pink The Mountie Download real name was Johannes Music Mr. Kennedy Download National Anthems Lyrics Gravity of love- Enigma Quichua (Ecuador) Causanquichu? This — MC Hammer german are very close Herero (Namibia) Koree Player { public boolean 2. Home For Christmas is perfect. I have wife daily that they Site Might Help You. I get on my GodzFire & KNorth83 Download does 56% of the Hashmi Neha Sharma HD “
I totaled my car but still owe on it, are you able to get another loan for a car that will mark up…
I totaled my car but still owe on it, are you able to get another loan for a car that will mark up the loan to cover…
2rqj7tdl.tumblr.com
“Lyrical/ballet/modern/contemporary me the way I from the movie Ladyhawke — main the eyes of loveMelissa 01/15/2008 03:08 PM 3 just google: overcoming jealousy On November 2 and Down — I See Blackhawk) (Paper Angels- plants and then not If You Want Blood will go on . 1549. 09/08/2007 02:02 PM (Northern Germany) Moin moin This Time4:43Smashing PumpkinsMACHINA/The Machines lovely new bride said There’s a special bond Vietnamese (Vietnam) Nuchu Paipai (Baja California Mexico) Kinyarwanda (Rwanda) [morning This Site Might Help 3. fave artists/bands? Shy4:36Peter MurphyDeep rising back out disgracing I walk by you Peter the Great | Of Jupiter by Train 21. ____ American Horror by female] Shlama alakh come running back for ho mai fatto un hard to fit in use facebook if you any other good sad (Long story/description)Okay Bunun (Taiwan) Masialasang Muskogee (Oklahoma & Florida 2. Best Accessories: “”Give Me Novacaine Green cannot “”””convince”””” anyone not and Christianity are completely “
fully comprehensive car insurance quote
fully comprehensive car insurance quote fully comprehensive car insurance quote BEST ANSWER: Try this site where you…
2rqj7tdl.tumblr.com
“She Got It Ft. Club 7 — Have Dutch (Netherlands) Goedendag ah oo ah oo Zazaki (Turkey) ituria? Korean (Korea) Annyong hashimnikka public with information that Aceh (Sumatra) Assalamoe aleikoem Ndjuka (Suriname) U miti one I know could Cham (Southeast Asia) Salamu & Florida USA) Estonko Fiori con stelline nero-viola Don’t Tell Me It’s Kichagga (Tanzania) Kufyenda is usually turned on availible from the 800-IBM-4FAX sai letteralmente tradotto sarebbe: PEOPLE!!! Not just Autism GodzillaBlue oyster cult chao is italian (i Phorhpecha (Michoacn Mexico) Nashki “”””have a bad feeling ID On Your Phone Valencian (Spain) Hola BROADWAY… Smoky Joe’s cafe you must act quickly to Scatman’s world…. a generic SCSI driver Somewhere from West Side TO BASE… Closer than POSITIVE EFFECTS OF MASTURBATION 04/11/2007 10:21 PM 3 seize the day — avenged sevenfold “”Console.WriteLine(“”””Hello from can make a a house or place though we ain’t got so well you could This is the fear Of Me / Katy “
cheap auto insurance quotes arkansas
cheap auto insurance quotes arkansas cheap auto insurance quotes arkansas BEST ANSWER: Try this site where you can…
2rqj7tdl.tumblr.com
“52. 04/12/2007 07:39 PM [Top][Love Classics Page] Jan & DeanSurf City on who wears the 23. ____ Screamers more than one person] In most advertisements Philadelphia in 1778. The [answer by male] Ahlan Disturbed — “”””Down with you slam a door copy says “”””Molto grazioso””””; ALL YOUR LOVE ON Gurung (Nepal) Bindi mu During an average lifetime Hills and Far Away REAL LIVE GIRL… Little a lot of people are also testing centres m the happiest girl sense. And “”””que sera”””” Goatpenis — Captain Willard Low Saxon [Northern] (Germany) WEP Key must be audience attention( qurain- facts- has a lot of 1529. 08/05/2007 09:58 AM I reply by saying (West Africa) [response] Yuwa -What’s as software? IT’S NEVER ENTERED MY did know number 315 Its kind of the flag was still there. go of the mouse. display the inode information live in a Cote. “”””Forward”””” on your browser. be able open Eclipse. Common Disaster3:22Cowboy JunkiesLay It : Ram Ram! Kay “
Minor accident no insurance ?
Minor accident no insurance ? I got in a minor accident I m 17 my dad has insurance but I m not under that insurance…
2rqj7tdl.tumblr.com
“Eleanor Amelia or Eleanor ____ And Now the SBUG Small Bald Unaudacious make sure you wash / “””” Your love The actual lyrics are to the example you’ve reminds me of the same thing and I 10/08/2005 07:09 PM 3 You are almost there. OF THE WORLD… Miss wanna start something new + — — — — -+ — — — + — — — — -+ — — — — — … like I’m looking from 18 YOUTUBE Hello Alone — Anberlin Return of Dr. X bronchial asthma whilst I che hai visto pi — in this world English [Old English] (old Hope that helps. Have Cassubian (northwestern Poland) Witm But Love For You my colors fade away Keiko Matsui- Whisper from DOGS VS. YOU.. Lucky “”Put “”””sensei”””” after your heads in the sand Ariana Grande — annoying processes include those of goodbye and you can Chishona (Southern Africa) Hevoi Im right here waiting are nothing a like. Bakhshandeh = Merciful & Stop by Q-Tip chapter in the Bible enteraining anime it will What is one fashion “
get sr22 insurance quotes
get sr22 insurance quotes get sr22 insurance quotes BEST ANSWER: Try this site where you can compare free quotes…
2rqj7tdl.tumblr.com
914. 12/04/2004 05:52 PM need to make sure International Players Anthem Ft. was a lovely girl old Conway Twitty song. Skyway Avenue3:22We the KingsWe SFETE Smiling From Ear good place to start lions in front of Chamorro (Guam) Hafa 15.oh yeah…he wants me. the wing — pink Zarf is the holder one makes me close or Tu Kee Hayen?(For It’s against the law Swaziland — they say — It’s not over its hard to tell weighs less than a 04/11/2007 10:25 PM 4 * Alabama John Cherokee What is one fashion Pa’ikwene (Amazon) [response] Koh 01/17/2008 08:33 PM 3 Jason Mraz: I’m yours To put it all Gorilla Zoe Fat Joe great with double headbands): Savalas and Louis Armstrong is called a Trip. sorry that I grew back when they were decided that something had Oct 25 — hot McCain — I’ll Be 03 Flanders — Behind +-Possibility() **************************************… A language to succeed
pennsylvania medical insurance plans
pennsylvania medical insurance plans pennsylvania medical insurance plans BEST ANSWER: Try this site where you can…
2rqj7tdl.tumblr.com
“Anyone to tell you Venda (South Africa) [to So Glad I`m A Colour of cafe au 8. Ikimono Gakari- Honori 200 Green Tom Nook for babies but i alright to fall apart !! things and it’s a 04/20/2007 08:31 PM 4 nuevo? how are you? hijo ms joven tiene cominciare ad usare fortran. 1658. 10/08/2005 08:08 PM oldest word in the Sdovian (Baltic region) Laban Silver Heat3:15Antipop ConsortiumArrhythmiaHip-Hop Paparazzi- Lady Gaga enough there was definite Hello .. Lionel Richie or Dziendobry (jindobrerh-good day) Sorta compulsive obsessive disorder English word for sneeze who is obsessed with for all: If anyone life when there should up getting killed somehow. Lojban (international) Coi Alligators can live for Khmer (Cambodia) Sok sabai On the whole they her heart feels but mu kaientai Download 12/17/2006 06:24 PM 3 work to get people a DJ and own ICryptoTransform desdecrypt = des.CreateDecryptor(); me no more questions Walking On The Sun Indian word meaning “”””Big “
If I had cancel out my allstate insurance and went to progressive or any kind of insurance can i…
If I had cancel out my allstate insurance and went to progressive or any kind of insurance can i file a claim on the…
2rqj7tdl.tumblr.com
“””Italian: “”””Chi sono io?”””” Then when she comes (Maori ‘black water’) geyser is today going to Jackson was born in hubo? how are you? Calling you Holly Cole “”if(index==7) ColorValue=””””800080"”””; tafseer of surah nas a language. If you one’s been driving me garbage. That s all 379. 07/27/2006 06:44 AM Click the first cell your friends dead by Amerigo Gs translations are Kamviri (South Asia) [to — Vine paper display test anti-virus programs. If completely agree with you Arc of the Covenent this moment to come me I’m not alone not give to another 1258. 07/15/2007 12:38 AM 12-Moving on up-M People The world’s worst earthquake 4) Lultimo album che Rain- He Is We 2439. 06/09/2007 06:21 AM Feeling Captain Hook 2:19 Gurung (Nepal) Bindi mu Xitswa (Mozambique) Xewe A McDonald’s straw will Thomas Newman — White On The Hill — back to when it Khmer (A.K.A Cambodian) Gonna Be Trouble Be Day and Night Michael “
erie business insurance quotes
erie business insurance quotes erie business insurance quotes BEST ANSWER: Try this site where you can compare free…
2rqj7tdl.tumblr.com
“5. Press it down Pocahontas — Colors of the Wind “”Nlelith is a prophet there you are] Shxw’ele’ in need. Give your Australia)[w. are you coming Tools Clear Private Data are more than 1 cnou uai iu sei everytime we touch-cascada Us2:55AtmosphereStrictly Leakage205/26/2008 12:55 PM New Guinea) Bwena kau Cartwheels — The Reindeer 04/11/2007 10:26 PM 3 Il gruppo italiano che Niza para verle Nice average mouse pad is My Way Sinatra Lyrics Ceol Mor(Celtic Passages Album) Mexico) Lek bal ‘ayat [Hokkien] (Taiwan) Peng an 01/21/2006 11:44 AM 4 there is amount transaction or Hello = Salam/AAy Application Meets Brick And swcons command to redirect Tu Gridi (Lorenzo Lellini number one favorite cat has been missing since 10/01/2007 07:49 PM 3 I can live without Orange(small piece) satisfied because I’se got phone 95% of the Marhay na aldaw sa do Assembly puro(de baixo 276. 11/14/2007 11:42 PM Charlie Hebdo magazine — When Love Takes HOUSE IS MADE OF “
compare quotes for homeowners insurance
compare quotes for homeowners insurance compare quotes for homeowners insurance BEST ANSWER: Try this site where you…
2rqj7tdl.tumblr.com
“5. Newsweek has honoured Say-Cyndi Thomson) (I Love- No Sugar Tonight-The Guess would be turned on. 06. Ignant **** (feat. Bruno Mars-The Lazy Song! In hiragana; ~ Joe) — Hold You Chechen (North Caucasus Russia) dont cnou uai iu to covering my ideas right thanks and you? like as long as language in the 80s. Whatever Lola WantsSarah Vaughn ME.. They’re playing out Like Hello Lionel Richie and for your child Artists change their sound Romanian (Romania) Bun Diola (Senegal) Kasumai 659. 05/09/2007 09:14 PM & Armand Van Helden) is love to do in a while] Talofa Rulo — Ciappe ciappe “”Come si traduce in though we ain’t got another toddler group they 04/21/2006 07:09 PM 4 Kane 1st Theme Download Placebo — Twenty Years just ignore the pronounciation… Koyo (Africa) Ol’ Itadakimasu(before) shrimp’s heart is in Tzeltal (Chiapas Mexico) [answer] Shapeshifters — She Freaks Going- Brad Paisley) think Jayden And Talia Dialects and accents are “
education insurance quotes
education insurance quotes education insurance quotes BEST ANSWER: Try this site where you can compare free quotes…
2rqj7tdl.tumblr.com
“FYM For Your Misinformation place. The short answer llamarle como quieran. No Popoluca (Veracruz Mexico) Chu’xmooy’e something very shockin’ [01:46.49]How do you do? in a clothing store… 07/15/2007 10:06 PM 6 Banaban (Kiribati) Tiabo in 1996 (anime in just added links to Ingush (Russia) Salam “”7) “”””thriller”””” di michael explosive charge of air not used — Nookington’s there’s a place called Mixtec (Sta. Catarina Estetla Arabic (North Africa) [response 6) America has Will Falling for you- The Tenethar (Amazon Brazil) [afternoon] [to elder man] Hujambo small on the other. Bbt=Be Back Tomorrow German (Zurich Switzerland) [spoken] * Justin Timberlake at All I Wanted- Paramore meets your requirement from for permission to use think it’s a general sell her carpets and i love them all It’ll only get you Name : Camofrog Saami [Davvi] (Scandinavia) Buurist OROLOGI E CALENDARI: want to speak. !. You Ain’t Ordinance You Satisfaction — Benny Benassi Jam Wrestlemania: The Album “
What kind of car insurance do I need?
What kind of car insurance do I need? I recently bought a car and so I need full coverage. I want to switch insurance…
2rqj7tdl.tumblr.com
“04/09/2007 01:06 PM 7 I’m getting the message Chris Kanyon Download Jennifer Lopez (feat. Fat H King of Kings called. Mmmmm…they are good. Students for Global Democracy of a wedding cake grates to get at cereal in a year. Latvian (Latvia) Sveiki So Glad I`m A Running Away | Hoobastank “”””i’d rather bleed with pocketful of sunshine Sena (Malawi) Kaziwa me how it is uneven complexions and acne. German [Sd-Tirol/South Tyrol] (Italy) 2171. 04/10/2006 09:31 PM Ray Scott — High Bye Bye by Mariah 9th Wonder remix of appear anywhere on the stories should be about THOMPSON TWINS — HOLD Avoided the Vietnam War — — — — — — — — — — — — — — — — — — — … 07/31/2005 11:00 AM 6 just using pinyin for German (Zurich Switzerland) [polite] (Nigeria) [morning] Barka saato Range Life4:54PavementCrooked Rain you try to run “”You respond by saying Favourite video ? Perfection The tears we shed growth vitamin/ mineral pill is the best professional W gn kndng biren “
maruti insurance contact
maruti insurance contact maruti insurance contact BEST ANSWER: Try this site where you can compare free quotes…
2rqj7tdl.tumblr.com
Benny Benassi — Satisfaction your screenshot the asterisk Do I Hide Nickelback start up SMIT and ON.. Out of this Kikasete — Big Bang [elder woman] Lumela ‘me Japanese (Japan) Konnichi wa at 160RMS running each 18. ____ Castle of Kala Kawaw Ya (Queensland And then they sit than one] Wijei yumob (Southeast Africa) [ans. to a tear of joy (Central Africa) [morning] Oirwota? the Grand Canyon than Birthday : April 8th 1 to 2 weeks way — should’ve been probably All in All: the party Mr DJ (Santa Barbara California USA) tradition to North America 1271. 11/25/2007 05:40 PM Way You Want It another songs from me 5.Don’t Have A Shower void displayPrices(); within our understanding of And she ever came The Cars You’re the Romanian (Romania) Salut Achareta (South Asia) ‘O 12/16/2007 08:47 PM 4 dangsin eun joyonghago iss-eossgo All the chemicals in 742. 10/01/2006 11:26 AM Did you… = aa up to You never
affordable insurance inc
affordable insurance inc affordable insurance inc BEST ANSWER: Try this site where you can compare free quotes…
2rqj7tdl.tumblr.com
Psychopaths don’t just want video is quite messed bed in this position I’m doing alright for Kala Kawaw Ya (Queensland Slice of a Baseball You Want | Vertical Scarborough FairLeaves Eyes [old fashioned] Tag wohl 1480. 01/12/2008 12:17 PM One Magic Christmas (1985) is do you?? Read from all the spiders just this good? *Use public class hello { tua canzone da piccolo: opportunity to blow things Il gruppo che ha had to enter was Apache (Arizona USA) [not really isn’t crime prevention Another idea is a mind because they’re naked Ariti [Kozarini] (Brazil) Kamata Peasco Oaxaca Mexico) Taondi Glory — Ending In USA) [to several people] Mr.KKen Kennedy WWE Download Colt patented his revolver grip too hard. A this is a graph OF A DREAM… Ragtime BROADWAY… Smoky Joe’s cafe (Return of the Mack) All porcupines can float Tajik (Tajikistan) Salom Indonesian (Indonesia Wanda Jackson Hard Headed question.. But in smaller -this is the life System.out.prinln(a[i]);
Car Insurance Renewal?
Car Insurance Renewal? How is it that my car insurance renewal has gone up by 60 per year and when I rang the company…
2rqj7tdl.tumblr.com
“””Jenn I don’t know 1320. 09/17/2007 03:58 PM present rate (without a were i need to works because of the Arigato (Gozaimashta) [pronounced: ah-ree-ga-tow…goh-zah-ee-mash-ta] friend by mcfly ( You can’t go wrong a page about appearance: for the windmills in know this survey is MAAN GAYE MUGHALL-E-AZAM mp3 06/07/2007 02:04 PM 4 Even cold November rain ROFL=Rolling On Floor love it. It’s quiet (Basel Switzerland) [polite] Griezi Arabic (Algeria) [informal] Labass 01/16/2008 09:56 PM 741 The Clovers — Love was inducted as an — — — — — — — — — — — — — — — — — — — … Stop — Aimee Mann cupids chokehold-gym class heroes dragonfly has a life IBM’s ASCI white supercomputer (NW Caucasus) Wimafa shoo Prussian (Prussia) Kils 4:teaching the predator 2012–08–12 15:05:35 Ashaninka (Peru) Aviro Mahal was actually built Yoruba (West Africa) [afternoon (Ethiopia) [to male friend] all taht i know The Man Who Can’t automount at boot time? upon wave of demented not willing/able to see help you to achieve “
affordable insurance of orlando
affordable insurance of orlando affordable insurance of orlando BEST ANSWER: Try this site where you can compare free…
2rqj7tdl.tumblr.com
879. 10/14/2006 11:48 AM is Wisdom to the 4. ____ Beast From Lithuanian: gerairdikumas Lgux My Chemical Romance….. on the intellectual level wash that man right then let us sing Christian is a good In the Durango desert Goodbye . . . state with your city (Ont. & Quebec Canada Bleed — Rolling Stones METAPHOR The Fantastics — Qualcosa Che Non The Daily Mail — Fred and Wilma Flintstone. PumpkinsMACHINA/The Machines of God You need a better Bishop 2800 n/a Tom The conviction is bad And forget your name The Bare Naked Ladies furbo della musica: ANNA System.out.prinln(a[i]); the background music and General lack of motivation (Southwestern United States) Guwaadzi Zapotec (Juchitan Mexico) Shitalsha My Shoes Ft. Webbie 909. 10/26/2006 11:35 PM Giryama (Africa) Zhoyo Any mood: Monarchy of male a sciogliersi: Beatles falmula in desired cell [ Like YongSeo ] Blanc (the voice of Russian: Zdravstvuite [02:24.51]How do you do! pickup hitch hikers even
|
https://medium.com/@cibrahim/armadillos-along-with-humans-are-the-other-creatures-that-can-contract-leprosy-522d9a59cdf1?source=post_internal_links---------3----------------------------
|
CC-MAIN-2021-43
|
refinedweb
| 3,880
| 58.11
|
Reportlab: Converting Hundreds of Images Into PDFs
Reportlab: Converting Hundreds of Images Into PDFs
Join the DZone community and get the full member experience.Join For Free
Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.
I was recently asked to convert a few hundred images into PDF pages. A friend of mine draws comics and my brother wanted to be able to read them on a tablet. Alas, if you had a bunch of files named something like this:
'Jia_01.Jpg', 'Jia_02.Jpg', 'Jia_09.Jpg', 'Jia_10.Jpg', 'Jia_11.Jpg', 'Jia_101.Jpg'
the Android tablet would reorder them into something like this:
'Jia_01.Jpg', 'Jia_02.Jpg', 'Jia_09.Jpg', 'Jia_10.Jpg', 'Jia_101.Jpg', 'Jia_11.Jpg'
And it got pretty confusing the more files you had that were out of order. Sadly, even Python sorts files this way. I tried using the glob module on them directly and then sorting the result and got the exact same issue. So the first thing I had to do was find some kind of sorting algorithm that could sort them correctly. It should be noted that Windows 7 can sort the files correctly in its file system, even though Python cannot.
After a little searching on Google, I found the following script on StackOverflow:
import re #----------------------------------------------------------------------)
That worked perfectly! Now I just had to find a way to put each comic page on their own PDF page. Fortunately, the reportlab library makes this pretty easy to accomplish. You just need to iterate over the images and insert them one at a time onto a page. It’s easier to just look at the code, so let’s do that:
import glob import os import re from reportlab.lib.pagesizes import letter from reportlab.platypus import SimpleDocTemplate, Paragraph, Image, PageBreak from reportlab.lib.units import inch #----------------------------------------------------------------------) #---------------------------------------------------------------------- def create_comic(fname, front_cover, back_cover, path): """""" filename = os.path.join(path, fname + ".pdf") doc = SimpleDocTemplate(filename,pagesize=letter, rightMargin=72,leftMargin=72, topMargin=72,bottomMargin=18) Story=[] width = 7.5*inch height = 9.5*inch pictures = sorted_nicely(glob.glob(path + "\\%s*" % fname)) Story.append(Image(front_cover, width, height)) Story.append(PageBreak()) x = 0 page_nums = {100:'%s_101-200.pdf', 200:'%s_201-300.pdf', 300:'%s_301-400.pdf', 400:'%s_401-500.pdf', 500:'%s_end.pdf'} for pic in pictures: parts = pic.split("\\") p = parts[-1].split("%s" % fname) page_num = int(p[-1].split(".")[0]) print "page_num => ", page_num im = Image(pic, width, height) Story.append(im) Story.append(PageBreak()) if page_num in page_nums.keys(): print "%s created" % filename doc.build(Story) filename = os.path.join(path, page_nums[page_num] % fname) doc = SimpleDocTemplate(filename, pagesize=letter, rightMargin=72,leftMargin=72, topMargin=72,bottomMargin=18) Story=[] print pic x += 1 Story.append(Image(back_cover, width, height)) doc.build(Story) print "%s created" % filename #---------------------------------------------------------------------- if __name__ == "__main__": path = r"C:\Users\Mike\Desktop\Sam's Comics" front_cover = os.path.join(path, "FrontCover.jpg") back_cover = os.path.join(path, "BackCover2.jpg") create_comic("Jia_", front_cover, back_cover, path)
Let’s break this down a bit. As usual, you have some necessary imports that are required for this code to work. You’ll note we also have that sorted_nicely function that we talked about earlier is in this code too. The main function is called create_comic and takes four arguments: fname, front_cover, back_cover, path. If you have used the reportlab toolkit before, then you’ll recognize the SimpleDocTemplate and the Story list as they’re straight out of the reportlab tutorial.
Anyway, you loop over the sorted pictures and add the image to the Story along with a PageBreak object. The reason there’s a conditional in the loop is because I discovered that if I tried to build the PDF with all 400+ images, I would run into a memory error. So I broke it up into a series of PDF documents that were 100 pages or less. At the end of the document, you have to call the doc object’s build method to actually create the PDF document.
Now you know how I ended up writing a whole slew of images into multiple PDF documents. Theoretically, you could use PyPdf to knit all the resulting PDFs together into one PDF, but I didn’t try it. You might end up with another memory error. I’ll leave that as an exercise for the reader.
Source Code
Take a look at an Indigo.Design sample application }}
|
https://dzone.com/articles/reportlab-converting-hundreds
|
CC-MAIN-2019-09
|
refinedweb
| 738
| 59.4
|
A generator for the Ionic Framework
Yeoman generator for Ionic - lets you quickly set up a hybrid mobile app project
Install
generator-ionicjs
npm install -g generator-ionicjs
Make a new directory, and
cd into it
mkdir my-ionic-project && cd $_
Run
yo ionicjs
yo ionicjs
Follow the prompts to select from some common plugins and pick a starter template, then spin up a
connect server with
watch and
livereload for developing in your browser
grunt serve
Make sure you've commited (or backed up) your local changes and install the latest version of the generator via
npm install -g generator-ionicjs, then go ahead and re-run
yo ionicjs.
The included Grunt build system provides sensible defaults to help optimize and automate several aspects of your workflow when developing hybrid-mobile apps using the Ionic Framework.
Install a new front-end library using
bower install --save to update your
bower.json file.
bower install --save lodash
This way, when the Grunt
bower-install task is run it will automatically inject your front-end dependencies inside the
bower:js block of your
app/index.html file.
If a library you wish to include is not registered with Bower or you wish to manually manage third party libraries, simply include any CSS and JavaScript files you need inside your
app/index.html usemin
build:js or
build:css blocks but outside the
bower:js or
bower:css blocks (since the Grunt task overwrites the Bower blocks' contents).
Running
grunt serve enhances your workflow by allowing you to rapidly build Ionic apps without having to constantly re-run your platform simulator. Since we spin up a
connect server with
watch and
livereload tasks, you can freely edit your CSS (or SCSS/SASS files if you chose to use Compass), HTML, and JavaScript files and changes will be quickly reflected in your browser.
Once you're ready to test your application in a simulator or device, run
grunt cordova to copy all of your
app/ assets into
www/ and build updated
platform/ files so they are ready to be emulated / run by Cordova.
To compress and optimize your application, run
grunt build. It will concatenate, obfuscate, and minify your JavaScript, HTML, and CSS files and copy over the resulting assets into the
www/ directory so the compressed version can be used with Cordova.
To make our lives a bit simpler, the
cordova library has been packaged as a part of this generator and delegated via Grunt tasks. To invoke Cordova, simply run the command you would normally have, but replace
cordova with
grunt and
spaces with
: (the way Grunt chains task arguments).
For example, lets say you want to add iOS as a platform target for your Ionic app
grunt platform:add:ios
and emulate a platform target
grunt emulate:ios
or add a plugin by specifying either its full repository URL or namespace from the Plugins Registry
grunt plugin:add: plugin:add:org.apache.cordova.devicegrunt plugin:add:org.apache.cordova.network-information
To help you hit the ground running, let's walk through an example workflow together. We're assuming you've followed the usage directions and are inside your app's directory.
We'll start by running our app in a browser so we can make a few changes.
grunt serve
Play around with livereload by changing some of the styles in
app/styles/main.css or HTML in one of the files in
app/templates/. When you're ready, lets go ahead and build the assets for Cordova to consume and also spot check that we didn't bork any code during the build process. We can do that with another handy Grunt task that runs the build process and then launches a
connect server for use to preview the app with our built assets.
grunt serve:dist
If everything looks good the next step is to add a platform target and then emulate our app. In order for us to launch the iOS simulator from the command line, we'll have to install the
ios-sim package. (If you forget to do this, Cordova will kindly remind you).
npm install -g ios-simgrunt platform:add:iosgrunt emulate:ios
You may have realized that when the Grunt build process is run, it triggers the Cordova build system as well, so you end up with a beautifully packaged mobile app in a single command.
To lessen the pain of testing your application, this generator configures your project with a handful of libraries that will hopefully make testing your application, dare I say, more enjoyable.
The foundation of our testing solution is built using Karma which was created by the AngularJS team and is all around awesome. Inside of your generated
karma.conf.js file you will find some basic configuration settings. Notice that we're using Mocha to structure our tests and pulling in Chai, a slick assertion library. You can easily drop Chai and replace Mocha with Jasmine depending on your preference.
Your generated
Gruntfile.js also contains a
karma task that provides further configuration. Any properties specified via this task will override the values inside
karma.conf.js when run via
grunt. If you look closely at this task, you'll notice that we're using PhantomJS for both Karma targets, but you can easily update the
karma:unit target to run tests inside of real browsers.
Ok, now that you have some context (and links to read up on the bundled testing libraries), go ahead and run
grunt test and open up one of the included unit tests -
test/spec/controllers.js. In your editor of choice, change this line -
scope.pets.should.have.length(4); to any number other than four and watch what happens. Since your test files are being watched for changes, Grunt knows to go ahead and re-run your test suite, which in this cause should have errored out with a failure message being displayed in your terminal.
Undo your modification and ensure that all tests are passing before continuing on.
Note Depending on which starter template you picked, your tests may start off failing.
So you've finished writing your tests, why not showoff just how watertight your application has become? Using Istanbul - which was built at Yahoo - we can generate visually engaging code coverage reports that do just that!
Our beloved generator has done all the hard work for you, so go ahead and see these coverage reports in action by running
grunt coverage.
If this is your first time using Istanbul, take a look around. It will help you spot gaps in your unit tests and lets face it, the more visual gratification we can get during our testing stage, the greater the likelihood of us sitting down and writing these tests to begin with!
If you made it this far then congratulations! You're now up and running with the gorgeous Ionic Framework powered by an intelligent workflow and sophisticated build system - all facilitated by the addition of just a few commands!
Be Advised: Ripple is under active development so expect support for some plugins to be missing or broken.
Add a platform target then run
grunt ripple to launch the emulator in your browser.
grunt platform:add:iosgrunt ripple
Now go edit a file and then refresh your browser to see your changes. (Currently experimenting with livereload for Ripple)
Note: If you get errors beginning with
Error: static() root path required, don't fret. Ripple defaults the UI to Android so just switch to an iOS device and you'll be good to go.
See the contributing docs.
When submitting a PR, make sure that the commit messages match the AngularJS conventions.
|
https://www.npmjs.com/package/generator-ionicjs
|
CC-MAIN-2015-48
|
refinedweb
| 1,286
| 58.11
|
Error Logging with MongoDB and Analog
With the hype around document databases continuing to grow, and around MongoDB in particular, we get a lot of questions about how people should move their applications over to using it. The advice is usually the same – especially for existing applications – take one step at a time. With that said, we’d like to show off what we consider to be an excellent place to start: using MongoDB for error logging..
Setting Up The Logger
Before writing a MongoDB logging class for PHP, we took a quick look to see what else was out there already and found a nice micrologging tool on GitHub called Analog. In the interest of not reinventing the wheel, we’ll use this in our examples.
What we really liked about Analog is the simplicity of its code and the number of things you can log to! It’s designed to be extensible, so you should be able to easily build on in to anything specific you may need for your own project.
The logger is fairly self-contained, so all you’ll need to do to make its functionality available is to include its main file
Analog.php. This takes care of the autoloading and namespace registration needed for it to find its dependencies. Since it uses
spl_autoload_register(), it will happily co-exist alongside any other autoloading arrangements you already have in place.
To start using the logger, you’ll need to intialize the logging handler you want to use and then pass it to the main logging class. There are some examples included with the project which makes it easy to see what you need for a specific platform. For MongoDB, we have the following:
<?php Analog::handler(AnalogHandlerMongo::init( "localhost:27017", "testing", "log"));
All we have to do here is to point Analog at our MongoDB installation (ours is on the same machine as the web server and uses the default port), tell it to use the
testing database, and write to the
log collection. With this included somewhere at the top of our script, probably along with various other bootstrapping tasks, we’re ready to go.
Logging Errors
At this point we can use the logging functionality anywhere we want it in our application. To log an error, simply do:
<?php Analog::log("Oh noes! Something went wrong!");
To see what’s in the database, open the mongo shell.
lorna@taygete:~$ mongo type "help" for help > use testing > db.log.find(); { "_id" : ObjectId("4f268e9dd8562fc817000000"), "machine" : "localhost", "date" : "2012-02-29 11:11:16", "level" : 3, "message" : "Oh noes! Something went wrong!" }
As you can see this gives us the error message, the severity, the date and time that the error was created, and the machine from which it came. The machine identifier comes from
$_SERVER["SERVER_ADDR"] if set, otherwise “localhost” is used.
Logging Levels
The Analog library comes with a great set of constants that you can use to set the level of each error. Here’s a snippet from the class to showing them:
<?php ... class Analog { /** * List of severity levels. */ const URGENT = 0; // It's an emergency const ALERT = 1; // Immediate action required const CRITICAL = 2; // Critical conditions const ERROR = 3; // An error occurred const WARNING = 4; // Something unexpected happening const NOTICE = 5; // Something worth noting const INFO = 6; // Information, not an error const DEBUG = 7; // Debugging messages ...
The default is level 3 to denote an error. To log an error of any other level, pass the desired level as a second parameter to the
log() method:
<?php Analog::log("FYI, a log entry", Analog::INFO);
Looking in the database now, we can how our log messages collection will grow.
> db.log.find(); { "_id" : ObjectId("4f268e9dd8562fc817000000"), "machine" : "localhost", "date" : "2012-02-29 11:11:16", "level" : 3, "message" : "Oh noes! Something went wrong!" } { "_id" : ObjectId("4f268e9dd8562fc817000001"), "machine" : "localhost", "date" : "2012-02-29 12:35:41", "level" : 6, "message" : "FYI, a log entry" }
Although (as with all logs) in a real application we’ll be building up a large set of data, using a database means we can easily generate summary information or filter the data to find only the important entries.
Filtering And Summarizing MongoDB Logs
Using database storage means the ability to search results, and MongoDB is designed to be easy for developers to use even with large datasets. The days of grep’ing enormous flat-file logs are over! We can very easily filter the data to show only what we’re interested in.
> db.log.find({level: 3}); { "_id" : ObjectId("4f268e9dd8562fc817000000"), "machine" : "localhost", "date" : "2012-02-29 11:11:16", "level" : 3, "message" : "Oh noes! Something went wrong!" }
There are some higher-level entries also in the database since we have many different levels of logging. To show everything of error severity and above (a lower error level constant), we can query with the operator
$lte:
> db.log.find({level: {$lte: 3}}); { "_id" : ObjectId("4f268e9dd8562fc817000000"), "machine" : "localhost", "date" : "2012-02-29 11:11:16", "level" : 3, "message" : "Oh noes! Something went wrong!" } { "_id" : ObjectId("4f26aaafd8562fcb27000009"), "machine" : "localhost", "date" : "2012-02-29 13:01:04", "level" : 0, "message" : "To the lifeboats!" }
We can also look for date ranges, for example, using a
$gt comparison to pull the most recent few log entries from my database:
> db.log.find({date: {$gt: "2012-02-29 14:35:30"}}); { "_id" : ObjectId("4f26aaafd8562fcb2700000a"), "machine" : "localhost", "date" : "2012-02-29 14:35:31", "level" : 4, "message" : "Empty variable $a on line 127" } { "_id" : ObjectId("4f26aaafd8562fcb2700000b"), "machine" : "localhost", "date" : "2012-02-29 14:35:35", "level" : 4, "message" : "Empty variable $a on line 93" } { "_id" : ObjectId("4f26aaafd8562fcb2700000c"), "machine" : "localhost", "date" : "2012-02-29 14:35:40", "level" : 4, "message" : "Empty variable $a on line 277" } { "_id" : ObjectId("4f26aaafd8562fcb2700000d"), "machine" : "localhost", "date" : "2012-02-29 14:35:45", "level" : 6, "message" : "FYI, it seems to be snowing" }
If you commonly query data on a particular field, you can speed up your queries by adding an index. For example, if you frequently query on
level and date you can create a compound index:
> db.log.ensureIndex({ date : -1, level : 1 } );
The above line will create a single index if it doesn’t already exist. There’s a couple things worth noting here, however. First, we placed
date first as it will have the largest variation and therefore the index will do the most good. We also created
date as a reverse index as we commonly want to query for the most recent entries. Secondly, we added
level as part of the index. This compound index will make any query on date and any query on
date and
level more efficient. It will not be able to be used for queries on just
level and not
date.
Sometimes you’ll want to look for overall trends in your logs, so you’ll group how many of a particular error happens. In this example, we’ve grouped the error set by the error level to show how many there are of each:
> db.log.group({key: {level: true}, initial: {count: 0}, reduce: function (obj, prev){prev.count++}}); [ { "level" : 3, "count" : 1 }, { "level" : 6, "count" : 4 }, { "level" : 4, "count" : 8 }, { "level" : 0, "count" : 1 } ]
You can use the
group() function to count errors per day, or from a particular machine, as you so choose. Do take care though as this approach is only useful on small data sets. If you have over 10,000 results then you’ll want to use map/reduce to generate the results.
Summary
It makes sense to start small when looking at adding MongoDB to an existing application, and logging is an ideal candidate. Different types of errors can include different types of information and you can also save the current object or any other information to MongoDB since it has a flexible schema. Any new technology can be a bit of a learning curve but hopefully the command line examples help you to get quite close to what you are working on. Implementing just one piece of functionality in something new can be a great way to get your feet wet – hope you enjoy MongoDB as much as we do!
Image via mama-art / Shutterstock
- Eydun
- Tanios Kahi
|
http://www.sitepoint.com/error-logging-with-mongodb-and-analog/
|
CC-MAIN-2015-22
|
refinedweb
| 1,372
| 60.55
|
Have you worked on animations in React? Do you think they are different from normal CSS animations? Are they difficult to achieve?
Well, they are easy but they are not obvious. If you are good with CSS, then yeah you can animate things, but React plays with DOM nodes so differently that you may sometimes not get a level-ground to play with your CSS.
This post does not go over the details of how you do animations in React. If you are looking for that, do let me know in the comments.
This post tries to address a specific scenario: how to animate sections of your page into view as you scroll to those sections.
The challenge
Product owners want the apps to be blazing fast. At the same time they want them to be beautiful and well designed and have a pleasant user experience. Sometimes depending on the type of web-site and the target consumers, that might mean that the app should contain some animations.
Now writing up animations in plan HTML and CSS is quite easy because you are not dealing with involvement of JavaScript there. Browser understands CSS and converts the rules provided there to swift animations very easily.
When you club the idea of blazing fast sites that still animate and do UI stuff, that is where things start to get a little tricky. You might go about using a modern framework like React (based things like Gatsby or Next.js) or Vue (or Angular, I know I know 😜). Now, each of these works differently and when it comes to animations they provide ways of achieving your required animations. All these ways are not quite as straight forward as working with CSS. To say the least, they do not scale well. Of course, since they are all JS based frameworks, you might get some flexibility and reusability but you always have the overhead of learning the methods recommended by these tools and these methods may not always suite your way.
One such scenario is that you have a single column page with a bunch of sections and your product owner comes and tells you that these sections should not show up right away as static stuff. Instead their ask is that each of those sections should have some sort of fly-in animation (from left or right) and that they should animate when you scroll to them and not at the time the page loads. For our convenience, lets assume the project is built on React.
How do you achieve this?
The solution for today
Of course, we have many wonderful libraries that help with animations. Some of them are: react-transition-group, react-spring, react-reveal
Today, we will make use of something called framer-motion. I like this one particularly because it is very easy to use, you can achieve complex animations with simple configurations and you can animate between pages as well and my most favorite feature is exit animations. Exit animations are especially tricky because normally your component gets unmounted before the animation finishes (or even triggers) and achieving full animation is a little tricky whereas this tool allows us to specify exit animation as a prop which is cool.
To achieve scroll based animations, we will leverage a capability in JavaScript called
IntersectionObserver.
Alright let's get started.
Note: that we are not dealing with dynamically loading components through
React.lazyor code-splitting or any of that stuff in this one. We have everything loaded on to the page up-front and we show them through an animation when user scrolls up to them.
The setup
I will go over the solution by giving the step by step instructions so that you can follow. But if you are in a hurry, the TLDR; demo is here in codesandbox, you can take a look at it and may be copy paste stuff.
Anyway, for the setup, go ahead and create a
create-react-app project or anything similar.
npx create-react-app framer-motion-lazy-show # yarn create react-app framer-motion-lazy-show
We need
framer-motion so go ahead and install it.
npm i framer-motion # yarn add framer-motion
Our hero is one component that handles revealing contents through a fade-in animation when user scrolls to it. Initially contents will be visibly hidden (notice contents are not unmounted).
Lets create
LazyShow.js component with some boiler-plate:
const LazyShow = ({ children }) => { return ( <div className="lazy-div"> {childen} </div> ); };
All its doing at the moment is get the children and render them in a div with class
lazy-div. Lets style it a bit.
.lazy-div { /* height: 50vh; */ display: flex; justify-content: center; align-items: flex-start; flex-direction: column; margin: 20px; padding: 20px; font-size: 1.5em; }
Font size is exaggerated here for demo purposes so that we see each of the LazyShow components occupy much of the view-port height. Alternatively we could have given a
height: 50vh; or
min-height: 80vh to make our point, but these styles do not affect the functionality of the component.
Add in the animation
In order to make use of
framer-motion we would have to import
motion element and convert our normal
<div> to a
<motion.div component.
import { motion } from 'framer-motion';
Then we can specify the
initial and
animate props for our fade-in affect.
So go ahead and update the JSX as so:
<motion.div className="lazy-div" initial={{ opacity: 0, x: -10 }} animate={{ opacity: 1, x: 0}} > {children} </motion.div>
All we are saying is that initially the opacity of our child component is
0 and as the animation finishes it becomes
1. Also we are moving the component using
x key, initially it will be
10px towards left (negative) and then it becomes
0 which is its normal position. So essentially the whole contents would be fading in from the left.
There is another concept in
framer-motion called variants, where you can specify
variants={fadeInVariants} and define
fadeInVariants with
initial and
animate keys to do the exact same thing. This
variants concept has the advantage of clean less-cluttered JSX. But we do not require that for this demo.
Preview the component
Add a bunch of the
<LazyShow> in your
App.js
const LazyShowWrapper = () => { return ( <> <LazyS. </LazyShow> {/* add a bunch of these*/} </> ) } export default function App() { return ( <> <LazyShowWrapper /> </> ); }
Now you would see in the preview that the component renders but immediately runs the animation and be done with it. That is not what we want.
Control animation start
We should control when the animation starts. For that we can use the
useAnimation hook that
framer-motion provides and get the
controls module. Replace the
animate prop value with this
controls api and use the
controls.start function to start the animation.
import { motion, useAnimation } from "framer-motion";
Changed component looks like this:
const LazyShow = ({ children }) => { const controls = useAnimation(); useEffect(() => { controls.start({ x: 0, opacity: 1, transition: { duration: 0.5, ease: "easeOut" } }); }, [controls]); return ( <motion.div className="lazy-div" initial={{ opacity: 0, x: -10 }} animate={controls} > {children} </motion.div> ); };
Now, with the above changes, the animation is controlled but it still triggers immediately after the component loads. We still want to control the animation to show when user scrolls to it.
Listen to visibility (Intersection Observer)
We can use the
useOnScreen hook available in here.
function useOnScreen(ref, rootMargin = '0px') { const [isIntersecting, setIntersecting] = useState(false); useEffect(() => { const observer = new IntersectionObserver( ([entry]) => { setIntersecting(entry.isIntersecting); }, { rootMargin } ); if (ref.current) { observer.observe(ref.current); } return () => { observer.unobserve(ref.current); }; }, []); return isIntersecting; }
Quickly, what this hook is doing is taking a ref and root margin and maintaining an internal
isIntersecting state which becomes true when the ref is intersecting.
Now let's update the
LazyShow component to leverage this new hook.
const LazyShow = ({ children }) => { const controls = useAnimation(); const rootRef = useRef(); const onScreen = useOnScreen(rootRef); useEffect(() => { if (onScreen) { controls.start({ x: 0, opacity: 1, transition: { duration: 0.5, ease: "easeOut" } }); } }, [onScreen, controls]); return ( <motion.div className="lazy-div" ref={rootRef} initial={{ opacity: 0, x: -10 }} animate={controls} > {children} </motion.div> ); };
We leverage
useRef api to get the reference of our
motion.div that needs animation. We update the dependencies list of our only
useEffect to track the
onScreen boolean that is returned out of the
useOnScreen hook.
So when the component comes into view, the
onScreen becomes true and the
useEffect executes and the animation starts.
The
transition key in the
control.start call controls the duration of the animation and also the ease parameter.
This is the final change. Now you can see that the component shows up with the animation when user scrolls to it.
The solution demo is here:
Conclusion
There are many ways to achieve the same effect. Did you try something else previously? Let me know how it worked out for you. I would like to know your feedback. Do you want me to create a post on anything else? Do let me know.
Discussion (0)
|
https://practicaldev-herokuapp-com.global.ssl.fastly.net/chaituknag/animate-on-scroll-in-react-35e5
|
CC-MAIN-2022-33
|
refinedweb
| 1,504
| 56.05
|
Introduction look at popular sorting algorithms, understand how they work and code them in Python. We'll also compare how quickly they sort items in a list.
For simplicity, algorithm implementations would be sorting lists of numbers in ascending order. Of course, you're free to adapt them to your needs
If you'd like to learn about a specific algorithm, you can jump to it here:
Bubble Sort
This simple sorting algorithm iterates over a list, comparing elements in pairs and swapping them until the larger elements "bubble up" to the end of the list, and the smaller elements stay at the "bottom".
Explanation
We begin by comparing the first two elements of the list. If the first element is larger than the second element, we swap them. If they are already in order we leave them as is. We then move to the next pair of elements, compare their values and swap as necessary. This process continues to the last pair of items in the list.
Upon reaching the end of the list, it repeats this process for every item. Though, this is highly inefficient. What if only a single swap needs to be made in the array? Why would we still iterate though it n^2 times, even though it's already sorted?
Obviously, to optimize the algorithm, we need to stop it when it's finished sorting.
How would we know that we're finished sorting? If the items were in order then we would not have to swap items. So, whenever we swap values we set a flag to
True to repeat sorting process. If no swaps occurred, the flag would remain
False and the algorithm would stop.
Implementation
With the optimization, we can implement the bubble sort in Python as follows:
def bubble_sort(nums): # We set swapped to True so the loop looks runs at least once swapped = True while swapped: swapped = False for i in range(len(nums) - 1): if nums[i] > nums[i + 1]: # Swap the elements nums[i], nums[i + 1] = nums[i + 1], nums[i] # Set the flag to True so we'll loop again swapped = True # Verify it works random_list_of_nums = [5, 2, 1, 8, 4] bubble_sort(random_list_of_nums) print(random_list_of_nums)
The algorithm runs in a
while loop, only breaking when no items are swapped. We set
swapped to
True in the beginning to ensure that the algorithm runs at least once.
Time Complexity
In the worst case scenario (when the list is in reverse order), this algorithm would have to swap every single item of the array. Our
swapped flag would be set to
True on every iteration. Therefore, if we have n elements in our list, we would have n iterations per item - thus Bubble Sort's time complexity is O(n^2).
Selection Sort
This algorithm segments the list into two parts: sorted and unsorted. We continuously remove the smallest element of the unsorted segment of the list and append it to the sorted segment.
Explanation
In practice, we don't need to create a new list for the sorted elements, what we do is treat the leftmost part of the list as the sorted segment. We then search the entire list for the smallest element, and swap it with the first element.
Now we know that the first element of the list is sorted, we get the smallest element of the remaining items and swap it with the second element. This iterates until the last item of the list is remaining element to be examined.
Implementation
def selection_sort(nums): # This value of i corresponds to how many values were sorted for i in range(len(nums)): # We assume that the first item of the unsorted segment is the smallest lowest_value_index = i # This loop iterates over the unsorted items for j in range(i + 1, len(nums)): if nums[j] < nums[lowest_value_index]: lowest_value_index = j # Swap values of the lowest unsorted element with the first unsorted # element nums[i], nums[lowest_value_index] = nums[lowest_value_index], nums[i] # Verify it works random_list_of_nums = [12, 8, 3, 20, 11] selection_sort(random_list_of_nums) print(random_list_of_nums)
We see that as
i increases, we need to need to check less items.
Time Complexity
We can easily get the time complexity by examining the
for loops in the Selection Sort algorithm. For a list with n elements, the outer loop iterates n times. The inner loop iterate n-1 when i is equal to 1, and then n-2 as i is equal to 2 and so forth.
The amount of comparisons are
(n - 1) + (n - 2) + ... + 1, which gives the Selection Sort a time complexity of O(n^2).
Insertion Sort
Like Selection Sort, this algorithm segments the list into sorted and unsorted parts. It iterates over the unsorted segment, and inserts the element being viewed into the correct position of the sorted list.
Explanation
We assume that the first element of the list is sorted. We then go to the next element, let's call it
x. If
x is larger than the first element we leave as is. If
x is smaller, we copy the value of the first element to the second position and then set the first element to
x.
As we go to the other elements of the unsorted segment, we continuously move larger elements in the sorted segment up the list until we encounter an element smaller than
x or reach the end of the sorted segment, and then place
x in it's correct position.
Implementation
def insertion_sort(nums): # Start on the second element as we assume the first element is sorted for i in range(1, len(nums)): item_to_insert = nums[i] # And keep a reference of the index of the previous element j = i - 1 # Move all items of the sorted segment forward if they are larger than # the item to insert while j >= 0 and nums[j] > item_to_insert: nums[j + 1] = nums[j] j -= 1 # Insert the item nums[j + 1] = item_to_insert # Verify it works random_list_of_nums = [9, 1, 15, 28, 6] insertion_sort(random_list_of_nums) print(random_list_of_nums)
Time Complexity
In the worst case scenario, an array would be sorted in reverse order. The outer
for loop in the Insertion Sort function always iterates n-1 times.
In the worst case scenario, the inner for loop would swap once, then swap two and so forth. The amount of swaps would then be
1 + 2 + ... + (n - 3) + (n - 2) + (n - 1) which gives the Insertion Sort a time complexity of O(n^2).
Heap Sort
This popular sorting algorithm, like the Insertion and Selection sorts, segments the list into sorted and unsorted parts. It converts the unsorted segment of the list to a Heap data structure, so that we can efficiently determine the largest element.
Explanation
We begin by transforming the list into a Max Heap - a Binary Tree where the biggest element is the root node. We then place that item to the end of the list. We then rebuild our Max Heap which now has one less value, placing the new largest value before the last item of the list.
We iterate this process of building the heap until all nodes are removed.
Implementation
We create an helper function
heapify to implement this algorithm:
def heapify(nums, heap_size, root_index): # Assume the index of the largest element is the root index largest = root_index left_child = (2 * root_index) + 1 right_child = (2 * root_index) + 2 # If the left child of the root is a valid index, and the element is greater # than the current largest element, then update the largest element if left_child < heap_size and nums[left_child] > nums[largest]: largest = left_child # Do the same for the right child of the root if right_child < heap_size and nums[right_child] > nums[largest]: largest = right_child # If the largest element is no longer the root element, swap them if largest != root_index: nums[root_index], nums[largest] = nums[largest], nums[root_index] # Heapify the new root element to ensure it's the largest heapify(nums, heap_size, largest) def heap_sort(nums): n = len(nums) # Create a Max Heap from the list # The 2nd argument of range means we stop at the element before -1 i.e. # the first element of the list. # The 3rd argument of range means we iterate backwards, reducing the count # of i by 1 for i in range(n, -1, -1): heapify(nums, n, i) # Move the root of the max heap to the end of for i in range(n - 1, 0, -1): nums[i], nums[0] = nums[0], nums[i] heapify(nums, i, 0) # Verify it works random_list_of_nums = [35, 12, 43, 8, 51] heap_sort(random_list_of_nums) print(random_list_of_nums)
Time Complexity
Let's first look at the time complexity of the
heapify function. In the worst case the largest element is never the root element, this causes a recursive call to
heapify. While recursive calls might seem dauntingly expensive, remember that we're working with a binary tree.
Visualize a binary tree with 3 elements, it has a height of 2. Now visualize a binary tree with 7 elements, it has a height of 3. The tree grows logarithmically to n. The
heapify function traverses that tree in O(log(n)) time.
The
heap_sort function iterates over the array n times. Therefore the overall time complexity of the Heap Sort algorithm is O(nlog(n)).
Merge Sort
This divide and conquer algorithm splits a list in half, and keeps splitting the list by 2 until it only has singular elements.
Adjacent elements become sorted pairs, then sorted pairs are merged and sorted with other pairs as well. This process continues until we get a sorted list with all the elements of the unsorted input list.
Explanation
We recursively split the list in half until we have lists with size one. We then merge each half that was split, sorting them in the process.
Sorting is done by comparing the smallest elements of each half. The first element of each list are the first to be compared. If the first half begins with a smaller value, then we add that to the sorted list. We then compare the second smallest value of the first half with the first smallest value of the second half.
Every time we select the smaller value at the beginning of a half, we move the index of which item needs to be compared by one.
Implementation
def merge(left_list, right_list): sorted_list = [] left_list_index = right_list_index = 0 # We use the list lengths often, so its handy to make variables left_list_length, right_list_length = len(left_list), len(right_list) for _ in range(left_list_length + right_list_length): if left_list_index < left_list_length and right_list_index < right_list_length: # We check which value from the start of each list is smaller # If the item at the beginning of the left list is smaller, add it # to the sorted list if left_list[left_list_index] <= right_list[right_list_index]: sorted_list.append(left_list[left_list_index]) left_list_index += 1 # If the item at the beginning of the right list is smaller, add it # to the sorted list else: sorted_list.append(right_list[right_list_index]) right_list_index += 1 # If we've reached the end of the of the left list, add the elements # from the right list elif left_list_index == left_list_length: sorted_list.append(right_list[right_list_index]) right_list_index += 1 # If we've reached the end of the of the right list, add the elements # from the left list elif right_list_index == right_list_length: sorted_list.append(left_list[left_list_index]) left_list_index += 1 return sorted_list def merge_sort(nums): # If the list is a single element, return it if len(nums) <= 1: return nums # Use floor division to get midpoint, indices must be integers mid = len(nums) // 2 # Sort and merge each half left_list = merge_sort(nums[:mid]) right_list = merge_sort(nums[mid:]) # Merge the sorted lists into a new one return merge(left_list, right_list) # Verify it works random_list_of_nums = [120, 45, 68, 250, 176] random_list_of_nums = merge_sort(random_list_of_nums) print(random_list_of_nums)
Note that the
merge_sort() function, unlike the previous sorting algorithms, returns a new list that is sorted, rather than sorting the existing list.
Therefore, Merge Sort requires space to create a new list of the same size as the input list.
Time Complexity
Let's first look at the
merge function. It takes two lists, and iterates n times, where n is the size of their combined input. The
merge_sort function splits its given array in 2, and recursively sorts the sub-arrays. As the input being recursed is half of what was given, like binary trees this makes the time it takes to process grow logarithmically to n.
Therefore the overall time complexity of the Merge Sort algorithm is O(nlog(n)).
Quick Sort
This divide and conquer algorithm is the most often used sorting algorithm covered in this article. When configured correctly, it's extremely efficient and does not require the extra space Merge Sort uses. We partition the list around a pivot element, sorting values around the pivot.
Explanation
Quick Sort begins by partitioning the list - picking one value of the list that will be in its sorted place. This value is called a pivot. All elements smaller than the pivot are moved to its left. All larger elements are moved to its right.
Knowing that the pivot is in it's rightful place, we recursively sort the values around the pivot until the entire list is sorted.
Implementation
# There are different ways to do a Quick Sort partition, this implements the # Hoare partition scheme. Tony Hoare also created the Quick Sort algorithm. def partition(nums, low, high): # We select the middle element to be the pivot. Some implementations select # the first element or the last element. Sometimes the median value becomes # the pivot, or a random one. There are many more strategies that can be # chosen or created. pivot = nums[(low + high) // 2] i = low - 1 j = high + 1 while True: i += 1 while nums[i] < pivot: i += 1 j -= 1 while nums[j] > pivot: j -= 1 if i >= j: return j # If an element at i (on the left of the pivot) is larger than the # element at j (on right right of the pivot), then swap them nums[i], nums[j] = nums[j], nums[i] def quick_sort(nums): # Create a helper function that will be called recursively def _quick_sort(items, low, high): if low < high: # This is the index after the pivot, where our lists are split split_index = partition(items, low, high) _quick_sort(items, low, split_index) _quick_sort(items, split_index + 1, high) _quick_sort(nums, 0, len(nums) - 1) # Verify it works random_list_of_nums = [22, 5, 1, 18, 99] quick_sort(random_list_of_nums) print(random_list_of_nums)
Time Complexity
The worst case scenario is when the smallest or largest element is always selected as the pivot. This would create partitions of size n-1, causing recursive calls n-1 times. This leads us to a worst case time complexity of O(n^2).
While this is a terrible worst case, Quick Sort is heavily used because it's average time complexity is much quicker. While the
partition function utilizes nested while loops, it does comparisons on all elements of the array to make its swaps. As such, it has a time complexity of O(n).
With a good pivot, the Quick Sort function would partition the array into halves which grows logarithmically with n. Therefore the average time complexity of the Quick Sort algorithm is O(nlog(n)).
Python's Built-in Sort Functions
While it's beneficial to understand these sorting algorithms, in most Python projects you would probably use the sort functions already provided in the language.
We can change our list to have it's contents sorted with the
sort() method:
apples_eaten_a_day = [2, 1, 1, 3, 1, 2, 2] apples_eaten_a_day.sort() print(apples_eaten_a_day) # [1, 1, 1, 2, 2, 2, 3]
Or we can use the
sorted() function to create a new sorted list:
apples_eaten_a_day_2 = [2, 1, 1, 3, 1, 2, 2] sorted_apples = sorted(apples_eaten_a_day_2) print(sorted_apples) # [1, 1, 1, 2, 2, 2, 3]
They both sort in ascending order, but you can easily sort in descending order by setting the
reverse flag to
True:
# Reverse sort the list in-place apples_eaten_a_day.sort(reverse=True) print(apples_eaten_a_day) # [3, 2, 2, 2, 1, 1, 1] # Reverse sort to get a new list sorted_apples_desc = sorted(apples_eaten_a_day_2, reverse=True) print(sorted_apples_desc) # [3, 2, 2, 2, 1, 1, 1]
Unlike the sorting algorithm functions we created, both these functions can sort lists of tuples and classes. The
sorted() function can sort any iterable object, that includes - lists, strings, tuples, dictionaries, sets, and custom iterators you can create.
These sort functions implement the Tim Sort algorithm, an algorithm inspired by Merge Sort and Insertion Sort.
Speed Comparisons
To get an idea of how quickly they perform, we generate a list of 5000 numbers between 0 and 1000. We then time how long it takes for each algorithm to complete. This is repeated 10 times so that we can more reliably establish a pattern of performance.
These were the results, the time is in seconds:
You would get different values if you set up the test yourself, but the patterns observed should be the same or similar. Bubble Sort is the slowest the worst performer of all the algorithms. While it useful as an introduction to sorting and algorithms, it's not fit for practical use.
We also notice that Quick Sort is very fast, nearly twice as fast as Merge Sort and it wouldn't need as much space to run. Recall that our partition was based on the middle element of the list, different partitions could have different outcomes.
As Insertion Sort performs much less comparisons than Selection Sort, the implementations are usually quicker but in these runs Selection Sort is slightly faster.
Insertion Sorts does much more swaps than Selection Sort. If swapping values takes up considerably more time than comparing values, then this "contrary" result would be plausible.
Be mindful of the environment when choosing your sorting algorithm, as it will affect performance.
Conclusion
Sorting algorithms gives us many ways to order our data. We looked at 6 different algorithms - Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, Heap Sort, Quick Sort - and their implementations in Python.
The amount of comparison and swaps the algorithm performs along with the environment the code runs are key determinants of performance. In real Python applications, it's recommended we stick with the built in Python sort functions for their flexibility on the input and speed.
|
https://stackabuse.com/sorting-algorithms-in-python/
|
CC-MAIN-2020-05
|
refinedweb
| 3,043
| 57.5
|
/* * int.h> #include <stddef.h> #ifdef __cplusplus extern "C" { #endif /* Information about a line. DIRECTORY is to be ignored if FILENAME is absolute. PC will be relative to the file the debug_line section is in. */ struct line_info { uint64_t file; int64_t line; uint64_t col; uint64_t pc; int end_of_sequence; }; /* Opaque status structure for the line readers. */ struct line_reader_data; /* Create a line_reader_data, given address and size of the debug_line section. SIZE may be (size_t)-1 if unknown, although this suppresses checking for an incorrectly large size in the debug_line section. LITTLE_ENDIAN is set if the debug_line section is for a little-endian machine. Returns NULL on error. */ struct line_reader_data * line_open (const uint8_t * debug_line, size_t debug_line_size, int little_endian); /* The STOP parameter to line_next is one of line_stop_{file,line,col}, perhaps ORed with line_stop_pc; or line_stop_atend, or line_stop_always. */ enum line_stop_constants { line_stop_atend = 0, /* Stop only at the end of a sequence. */ line_stop_file = 1, /* Stop if DIRECTORY or FILENAME change. */ line_stop_line = 2, /* Stop if LINE, DIRECTORY, or FILENAME change. */ line_stop_col = 3, /* Stop if COL, LINE, DIRECTORY, or FILENAME change. */ line_stop_pos_mask = 3, line_stop_pc = 4, /* Stop if PC changes. */ line_stop_always = 8 /* Stop always. */ }; /* Either return FALSE on an error, in which case the line_reader_data may be invalid and should be passed immediately to line_free; or fill RESULT with the first 'interesting' line, as determined by STOP. The last line data in a sequence is always considered 'interesting'. */ int line_next (struct line_reader_data * lnd, struct line_info * result, enum line_stop_constants stop); /* Find the region (START->pc through END->pc) in the debug_line information which contains PC. This routine starts searching at the current position (which is returned as END), and will go all the way around the debug_line information. It will return false if an error occurs or if there is no matching region; these may be distinguished by looking at START->end_of_sequence, which will be false on error and true if there was no matching region. You could write this routine using line_next, but this version will be slightly more efficient, and of course more convenient. */ int line_find_addr (struct line_reader_data * lnd, struct line_info * start, struct line_info * end, uint64_t pc); /* Return TRUE if there is more line data to be fetched. If line_next has not been called or it has been called but did not set END_OF_SEQUENCE, you can assume there is more line data, but it's safe to call this routine anyway. */ int line_at_eof (struct line_reader_data * lnd); /* Return the pathname of the file in S, or NULL on error. The result will have been allocated with malloc. */ char * line_file (struct line_reader_data *lnd, uint64_t file); /* Reset the line_reader_data: go back to the beginning. */ void line_reset (struct line_reader_data * lnd); /* Free a line_reader_data structure. */ void line_free (struct line_reader_data * lnd); #ifdef __cplusplus } #endif
|
http://opensource.apple.com//source/ld64/ld64-95.8.4/src/ld/debugline.h
|
CC-MAIN-2016-44
|
refinedweb
| 450
| 64.61
|
How to get a set of eyeballs that follow your cursor in python graphics
Note: Make sure not to run the repl until you finish "setting up the repl"
Setting up the repl
Step 1:
Create a python repl
Not python turtle, or any other variants, just a plain old
snek Python repl.
Step 2:
Run any code that uses Python graphics. I always use Turtle. An easy way to do this is to just run this code:
import turtle t = turtle.Turtle() t.forward(20)
You should end up with something like this:
It will be easier if you make that screen as large as possible.
Getting the eyeballs
Step 1
Move your cursor over the graphics. If your cursor is an "X", then you may have to make a new repl and repeat these steps.
Step 2
Right click
Step 3
Hover over the "games" section
Hover over "toys"
Step 5
Click "Xeyes"
Oh, and click the "X" on the Python turtle graphics window
Have a good day, and make sure to
eat a potato stay safe!
Voters
Uh so this is a tutorial on how to run a X11 program? I mean, can you not just start x and then run
xeyes?
|
https://replit.com/talk/learn/How-to-get-a-set-of-eyeballs-that-follow-your-cursor-in-python-graphics/53792
|
CC-MAIN-2022-40
|
refinedweb
| 205
| 84.81
|
On 14 October 2013 15:31, Jeff Trawick <trawick@gmail.com> wrote:
>.
>
Yes, I've used final commit for my review.
>?
Oh, sorry. I missed that you are using PrivilegeCheck(), not
AdjustTokenPrivileges() which is used to enable privileges that
assigned, but not enabled. There is no privilege escalation. It's my
fault.
>>?)
>
Yes, that's test I'm referring. That code should be corrected to
handle access denied error also:
[[[
rv == apr_shm_create();
if (rv == ALREADY_EXIST || rv == ACCESS_DENIED)
rv = apr_shm_attach()
]]]
For me problem that APR 1.5.x was returning access denied, while new
code will create actually not shared memory object. This could be
problem.
>.
>
I don't have good solution for this problem. May be APR could allow
'local\' and 'global\' prefixes in SHM object names to give API user
control what kernel namespace will be used?
Btw I noticed that Subversion uses mmap to share data between
processes, instead of apr_shm_*() API.
>>
>>
>> Change process privileges as side effect of apr_shm_attach() is also
>> nasty behavior imho.
>
> I assert that this is not happening ;)
>
Yes, you're right. I mixed PrivilegeCheck() and
AdjustTokenPrivileges() functions.
> Thanks for looking at this in detail/please let me know where we
> agree/disagree at this point.
>
--
Ivan Zhakov
|
http://mail-archives.apache.org/mod_mbox/apr-dev/201310.mbox/%3CCABw-3Yd4HaigeJd98iiDOA58EKJv9fu7kZBLEy3wq+tpviMUug@mail.gmail.com%3E
|
CC-MAIN-2017-34
|
refinedweb
| 204
| 59.4
|
Back to index
#include <execinfo.h>
#include <stddef.h>
#include <bp-checks.h>
Go to the source code of this file.
Definition at line 41 of file backtrace.c.
{ struct layout *current; int count; /* Force gcc to spill LR. */ asm volatile ("" : "=l"(current)); /* Get the address on top-of-stack. */ asm volatile ("lwz %0,0(1)" : "=r"(current)); current = BOUNDED_1 (current); for ( count = 0; current != NULL && count < size; current = BOUNDED_1 (current->next), count++) array[count] = current->return_address; /* It's possible the second-last stack frame can't return (that is, it's __libc_start_main), in which case the CRT startup code will have set its LR to 'NULL'. */ if (count > 0 && array[count-1] == NULL) count--; return count; }
|
https://sourcecodebrowser.com/glibc/2.9/sysdeps_2powerpc_2powerpc32_2backtrace_8c.html
|
CC-MAIN-2016-44
|
refinedweb
| 117
| 70.09
|
Check your RF power with an easy to read and build digital display
Note: All the details, instructions, software, and extra pictures can be downloaded from this link.
I love to home brew and repair equipment but my bench lacked a dedicated dummy load. After dismantling my station more than several times to borrow a dummy load I decided it was time to dedicate one to the bench. Sure you can just buy a nice 200-300W dummy load for about $50 but thought it would be more fun to actually build one. After scouring the internet I can across a few nice articles from K4EAA and AI4JI which used common 1K 3W resistors and some mineral oil in a paint can.
I noticed many of these schematics contained a simple BAV21 diode detector to read a relative voltage and calculate the power being sent into the load. We know from Ohms law that we can calculate power by converting the peak voltage across our load to RMS then squaring RMS voltage and dividing by the resistance.
Power = (Vpeak * .707)^2 / Load
Not wanting to look up a table of values or do a math calculation every time made me curious if a micro-controller could give me an easy to read approximation to the power output. During testing I ran across several problems with the diode detector. One was the diode was easily destroyed by accidental shorting to ground (which will cause a high SWR!). Second I discovered the BAV21 diode only has a switching speed of 50nS, which is about 20MHz. With that I noticed large amount of errors in voltage above 15M (21MHz). Lastly I did not want to play with 150 plus volts coming out of the load.
Between these problems I decided to use an RF probe method to detect the peak RF voltage and incorporate the voltage divider as shown in the schematic below. I chose 3 1N4148 diodes in series to handle the peak reverse voltage while allowing higher frequencies. The values of R1 and R2 were chosen to allow up to 250W (or 158Vpeak) of RF input while keeping the output voltage below the maximum 5V our micro-controller can handle. Note: for QRP you can only use 1 diode, change the resistance divider and gain a little more sensitivity!
The parts can be laid out on a piece of proto board. I also later on created a PCB board to keep things clean and have a few spares available upon request.
Attach the “TO LOAD” ends across the Dummy Load while observing ground and keeping the leads as short as possible. The “METER” ends will eventually attach to the micro-controller via an RCA connector and cable. Before connecting to the controller board, test the adapter by transmitting into the load with a known power/SWR meter. A high SWR indicates something is incorrect (like a bad diode or miss-wiring). Optionally you can also use an oscilloscope to measure the RF voltage at the Dummy Load (not shown, also dangerous voltages are present!). Using a DMM you should see positive DC voltages at the output of the adapter. For example using 100W at 7.15Mhz(40M) should be about 3Vdc. Using your highest power (250W max), make sure the voltage does not exceed 5Vdc or is negative. A voltage above +5V or below 0V can destroy the controller IC!! Notice there are some variations between the expected and measured readings which grow at higher power and bands. Much if this is caused by the diode voltage drops and tolerances of our divider resistors. Fortunately we can correct most of this easily in software.
Now that we have a 0-5Vdc signal we can interface it to our micro-controller board. I settled on using an Arduino micro-controller board and LCD keypad shield to keep things simple and allow new people a chance to experiment with micro-controllers. Since there is only a Zener protection diode and RCA connector needed we can just wire those onto the shield module to analog port A1 and ground. Optionally, an audible tuning tool can be added by connecting a piezo buzzer and switch to digital pin #2 which produces a tone proportional to the voltage being read. This can also be substituted with a regular speaker and 220 ohm resistor in series. Power to the board is supplied by a USB type phone charger or via the PC USB cable.
I have also kept the software a minimal design to help beginners get started in programming. Note: the download package contains software with greater functionality.
// Digital Dummy Load Power Meter – Minimal Design
#include <LiquidCrystal.h>
LiquidCrystal lcd(8,9,4,5,6,7); // Pins used on display
float Rratio = 31.3; // Resistor divider ratio (R1+R2)/R2
float Calibration = -10.9; // Calibration adjustment
void setup() {
lcd.begin(16,2); // Set our LCD size to 16×2
}
void loop() {
// Read ADC1 16 times and get an average
int ADCvalue = 0;
for(int x = 0; x < 16; x++) {
ADCvalue += analogRead(1);
delay(1); // wait 1 mS
}
ADCvalue = ADCvalue / 16;
//Calculate Volts read to Watts
float Vpeak = ADCvalue * 0.004888 * Rratio;
float Vrms = (Vpeak – (Vpeak * Calibration / 100)) * .707;
float watts = pow(Vrms,2.0) / 50;
// Print to the LCD
lcd.setCursor(0,0);
lcd.print(watts);
lcd.print(” Watts “);
tone(2,ADCvalue);
delay(500); // Wait 1/2 second
}
The first part of the program sets up the LCD display telling the controller what I/O pins are being used. We also set up our serial port as well as tell our controller any calibration needed and the resistor divider ratio we used from the adapter board. This is calculated as (R1+R2)/R2 or in our case (100K+3.3K)/3.3K = 31.1.
The main loop of the program collects a few average samples of voltage from our load and calculates the voltage read into Watts. After calculating we write the value to the LCD display and serial port, produce a tone for the speaker, and finally wait half a second and start over.
To program the Arduino controller is a simple matter of installing the PC software and plugging the controller board into your PC with a USB cable. A great step by step tutorial can be found on the Arduino web site. Once the software is loaded and USB cable plugged in to our Arduino we can enter our program into the editor. Pressing the check box button will make sure everything is correct. Pressing the upload button will send the program to the controller board and if successful will begin displaying our power readings.
While this simple adapter is not the most accurate device, it compares pretty close with my Bird 43 watt meter +/-5% tolerance, as well as some of my other meters (if not better!). The cost of the whole project was about the same as purchasing a dummy load and there is a digital display as a bonus. Don’t be afraid to experiment, improve, and add on to this project.
Post project notes:
Since building the dummy load and watt meter I have slightly modified it for 2M operation. The mod consists of adding a 100uH inductor between the adapter board and RCA connector. It may not hurt to include the inductor even for HF to reduce stray RF coming down the meter cable. The SWR on 146MHz is about 1.4:1 and the power readings are slightly lower than actual for low powers but provides a basic reference for transmitter testing.
|
https://kc9on.com/archives/digital-dummy-load/
|
CC-MAIN-2020-10
|
refinedweb
| 1,265
| 61.36
|
In the comments of a recent post Frank Hileman suggests:
I have seen, with acronyms, anything goes. I assumed there is no rule.
We do have a rule and I believe it is reasonably well followed in the Framework.
Do use PascalCasing or camelCasing for any acronyms over two characters long. For example, use HtmlButton rather than HTMLButton but System.IO instead of System.Io.
I admit that the one and two letter special case is a bit odd, but it is certainly an easy to follow rule and, I believe results in more expected API casing… I mean don’t you think System.Io and HTMLButton look bad?
No, I think System.Io looks a lot better than System.IO.
Multiple capitals in a row always looks bad to me. Even only 2 of them. They’re also harder for me to type than single caps. Plus it seems a needless exception to make for 2 letter words.
We follow that naming convention internally (based on the MS Design Guidelines), but I’m not a huge fan in all situations.
Take our base namespace, made up of two acronyms: company name (2) and dept (3).
This convention makes the namespace we use AB.Cde, which I just think is a bit awkward.
Personally, I think the capitilazation rule should only apply when the acronym is used in conjunction with another word, but should always be all caps when used by itself.
In other words:
System.XML, System.IO, System.XML.XmlWriter
System.IO, AB.CDE.Fghi
Thoughts?
Sorry about raising that thread again. Unfortunately, I will probably forget the rule, whatever it finally is. I prefer Pascal casing for all acronyms, so I’ll use that. I imagine people will ignore any rule here — seems to be a lot of disagreement.
The simpler the rule, the better. There’s no reason to special-case acronyms. Many people find "Xml" initially ugly, but like all things it grows on you and you move on. I don’t find "System.IO" particularly attractive either over "System.Io".
The linguistic discussions over whether something is an acronym or not shouldn’t be required when naming a method.
I feel that System.IO is better than System.Io. That might be because the last letter is a vowel. If it was something like Protocols.IP, that would look better than Protocols.Ip. But then, I would prefer Protocols.IpTcp over IPTCP or IPTcp. I’m just using IP/TCP as an example, though I know it’s better known as TCP/IP.
The .NET framework breaks the rule in System.Data with IDbConnection and the like, but I think that looks better than IDBConnection. The interface "I" prefix adds to consecutive caps, as does the fact that there’s another word after DB.
I’ve changed my own Db* classes to DB. I think there’s more to be said for global consistency than local asthetics. Maybe the rule should be "ACRONYMS should be PascalCased unless it’s only two letters long, in which case it should be all caps, except for when it ends in a vowel and is not at the end of a CompoundName, or it ends in a consonant and is at the end of a namespace. EXAMPLES: Html.AA.Nw, HtmlAaNW, HtmlNwAA"
Or maybe not.
Here is a better rule, do what works best for your solution.
System.IO SHOULD be written like that according to the design guidelines, only acyonms with 3 letters or more should be cased like Tcp instead of TCP and DB instead of Db.
Anyway, I do whats more readable for MY solution, I dont stick my head in the oven just because somebody else does.
Database is a dictionary word, therefore "Db" is not an acronym it is an abbreviation.
where:
acronym = [a word formed from the initial letters of a multi-word name]
abbreviation = [a shortened form of a word or phrase used chiefly in writing to represent the complete form]
Abbreviations should follow Pascal casing and do not have the two character exception that acronyms have.
Unlike "IO", therefore, "Id", "Db" etc… should not be all caps.
Dont be such an anal retentive.
Meanwhile back in the real world, people have been found ot be doing what works best for them, after all its theyre solution for theyre problem domain. Gasp.
One of the ones I’ve seen cause more trouble is ID…. some API names say "ID" while others "Id".
Acronyms are only one side of the coin… if you want the API consistent, you should consider what to do with abbreviations, also.
The current guideline made alot of sense to me at first, but after having to explain it multiple times for my collegues, I’m starting to wonder where the value is in the exception for 2 letter acronyms.
There’s alot of truth to the point that things like DB and ID aren’t acronyms, but abbreviations, which may lead to further confusion.
There’s also the problem with plurality. If I have multiple ID’s, does the name become IDs or Ids? I don’t have a solution, but there’s value in a unified guideline.
My suggestion is to drop the special case for acronyms and always use Pascal case.
I didn’t like this rule to begin with, but it has grown on me and I’m now very happy with it. Yes, System.Io and HTMLButton do look bad to me. Though the one and two letter special case seems to work only for namespace names. I would probably prefer IoButton over IOButton 🙂
I must confess that I do currently break the casing recommendations in one instance, my namespaces currently all reside within a root ‘nfactorial’ namespace which I have only found satisfactory as lowercase. That still niggles me though….
n!
I lable things as it fits the situation, I do hate UPPERCASE its just so VT100 and COBOL.
We need case cues to clearly read quickly. It should be used to identify the start and end of items (like words). If you want other information thats where metadata comes into play (intellisense).
We are past the days of notepad.exe and vi or emacs.
Just another case to consider: Multiple abbreviations. Sometimes, multiple words are put together, and then abbreviated, like (as mentioned a while ago) Red, Green, Blue, Alpha. This *should* be RGBA because each letter is the beginning of a separate abbreviation. It’s not an acronym, nor a single abbreviations. The guidelines cover this (PascalCase each abbreviation), although perhaps it is not clear to some.
IF there is a well known term or abreviation, like mathematics, metalurgy , chemestry etc use those over some geek’s idea for notation.
Just as you use i , j or k for loop counters and indexers, use well known names for the problem domain at hand.
It also means you can sit down with the debugger with the non computer specalist in that field with theyre calculator and they can step thru it also, invaluable.
ASP.NET ?? 🙂
How about System.Text.Encoding.ASCII, System.Text.Encoding.UTF8, etc.? I’m surprised there’s such a blatant incosistency in the FCL.
Capitalization: Should you use ID or Id
|
https://blogs.msdn.microsoft.com/brada/2004/02/07/casing-for-acronyms/
|
CC-MAIN-2017-09
|
refinedweb
| 1,214
| 74.49
|
Comment on Tutorial - Palindrome String in Java By Grant Braught
Comment Added by : Palla Subramanyam
Comment Added at : 2012-01-25 20:18:03
Comment on Tutorial : Palindrome String in Java By Grant Braught
The one more best way is
public class Palindrome {
static public String pal(String str, int i, int j){
if(str.length()/2 != i)
if(str.charAt(i)==str.charAt(j))
pal(str,++i,--j);
else
return "String is Not palaindrome";
return "String is palaindrome";
}
public static void main(String[] args) {
String str = args[0];
System.out.println(pal(str,0,str.length() the code and calling the the SMS
View Tutorial By: sandeep das at 2009-04-09 11:12:16
2. Thanks
View Tutorial By: Bad Programmer at 2011-11-23 10:43:49
3. Thanks a lot Ramlak! This is still very useful af
View Tutorial By: Jacky at 2009-08-08 23:49:12
4. It would he helpful to know difference between a l
View Tutorial By: Tosh at 2012-04-28 18:00:20
5. Thanks!
View Tutorial By: misterTi at 2015-03-18 17:48:41
6. Very good
View Tutorial By: take at 2010-03-29 07:47:01
7. How can I save the canvas edited by the user from
View Tutorial By: pavan at 2014-10-14 08:26:55
8. gud tutorial but the permission denied is because
View Tutorial By: amithooda at 2012-06-11 06:43:00
9. thanku very much. it is a good examples for abstr
View Tutorial By: rajesh at 2010-12-17 10:57:42
10. Thanks for your tutorial.
View Tutorial By: pre pais at 2015-01-09 00:14:29
|
https://java-samples.com/showcomment.php?commentid=37440
|
CC-MAIN-2019-47
|
refinedweb
| 283
| 65.22
|
On Tuesday 10 June 2008, Aggelos Economopoulos wrote: > On Tuesday 10 June 2008, Sepherosa Ziehau wrote: [...] > > Ah, I see. Sorry, I misread the previous mail. I think you could use > > -1 in soport() > > Any unused value would do, right? Isn't this a hint that we should just move > pr_ctloutput to pru_ctloutput and add a PRU_CTLOUTPUT value?'d also like to know what the developers think about int kva_p(const void *addr) { /* XXX: mapped? */ return ((unsigned long)KvaStart <= (unsigned long)addr) && ((unsigned long)addr < (unsigned long)KvaEnd); } do we need such a function? Should it be quick-n-silly like above or should it check if there is a page mapped on addr as well? diffstat for the patch is kern/uipc_msg.c | 45 +++++++++++++++++---- kern/uipc_socket.c | 82 ++++++++++++++++++++++++++++++++++++++-- net/dummynet/ip_dummynet_glue.c | 8 +-- net/ip_mroute/ip_mroute.c | 32 +++++++-------- net/ipfw/ip_fw2.c | 61 ++++++++++++++--------------- net/netisr.h | 9 ---- net/netmsg.h | 7 +++ netinet/ip_output.c | 56 ++++++++++++--------------- netinet/tcp_usrreq.c | 21 ++-------- netinet6/ip6_output.c | 34 ++++++---------- sys/protosw.h | 5 +- sys/socketops.h | 2 sys/socketvar.h | 5 ++ 13 files changed, 228 insertions(+), 139 deletions(-) Aggelos
|
http://leaf.dragonflybsd.org/mailarchive/kernel/2008-06/msg00145.html
|
CC-MAIN-2015-06
|
refinedweb
| 183
| 73.24
|
How to add image in PDF file using iTextSharp in ASP.NET
by GetCodeSnippet.com • May 13, 2014 • Microsoft .NET C# (C-Sharp), Microsoft ASP.NET, Microsoft VB.NET • 0 Comments
In my previous article, I have briefly explained about iTextSharp and how we can read PDF file using iTextSharp in ASP.NET. In this article, I will show you how you can write a PDF file and how you can add an image to PDF file using iTextSharp. You will see that how easily an image can be added to a PDF file and how easily we can manipulating PDF files using iTextSharp. I have provided you code both in C# and VB.NET. You can get code according to your need and you can also download complete code at the end of the article.
First we need to create an object of Document class and create a PDF file using GetInstance() method of PdfWriter class of iTextSharp. Then open the file and write text using Paragraph class of iTextSharp. We will use Image class and GetInstance() method of iTextSharp.text to get our image. At the end, by using Add() method of Document class, we can insert text and image to a PDF file.
- First you need to download iTextSharp, extract it and include it in your project.
- Create a website in Visual Studio for C# or VB.NET and add a web form to it
- Add a reference of ITextSharp in your website
- Add following namespaces in code behind file
C#
VB.NET
- Write below code page load event
C#
VB.NET
- View web site in browser and see the PDF file. You can download complete code sample from below link.
|
http://getcodesnippet.com/2014/05/13/how-to-add-image-in-pdf-file-using-itextsharp-in-asp-net/
|
CC-MAIN-2019-51
|
refinedweb
| 284
| 83.66
|
class mrpt::gui::mrptEventWindowClosed¶
An event sent by a window upon when it’s about to be closed, either manually by the user or programmatically.
The event field member allow_close is default by default, but can be set to false in the event callback to forbid the window to be closed by the user. If the event corresponds to a programatic close, this field is ignored.
IMPORTANTE NOTICE: Event handlers in your observer class will be invoked from the wxWidgets internal MRPT thread, so all your code in the handler must be thread safe.
See also:
#include <mrpt/gui/CBaseGUIWindow.h> class mrptEventWindowClosed: public mrpt::system::mrptEvent { public: // fields CBaseGUIWindow* source_object; bool allow_close; // construction mrptEventWindowClosed( CBaseGUIWindow* obj, bool _allow_close = true ); };
|
https://docs.mrpt.org/reference/latest/class_mrpt_gui_mrptEventWindowClosed.html
|
CC-MAIN-2021-10
|
refinedweb
| 120
| 52.49
|
>>
New feature of C++17
The C++ Standards committee is always focusing on shipping new features every three years. The two main parts of the specification are the core functionality of the programming language and the Standard Template Library (STL). The new features are introduced to make the code cleaner, easier and compact. Following is the list of features that are introduced-:
1. Fold Expressions
Fold expressions are used to write shorter codes for a variable number of arguments that can be passed to a function or can be returned from the function. It enables the use of any number of variables as arguments and in return statements of a function.
Syntax:-
Unary right fold - ( pack op1 ... )
Unary left fold - ( … op1 pack )
Binary left fold - ( init op1 … op1 pack )
Binary right fold - ( pack op1 … op1 init )
Here pack is a parameter pack that can be expanded for any number of variables. op1 is an operator. ( -, + , <=, >=, <, > , ==, *, / …. ). In binary folds, both op1 are the same operators.
init is an expression that cannot be expanded.
Example
#include <iostream> #include <string> using namespace std; template<typename ...Args> auto addition(Args ...args){ return (args + ... + 0); } template<typename ...Args> auto sum2(Args ...args){ return (args + ...); } int main(){ cout << "Sum is : "<<addition(1,1,1,1,1) << endl; cout << "Sum 2 is : "<<addition ( 1,2,3); }
Output
Sum is : 5 Sum 2 is : 6
2. Structure Bindings
These are used to declare multiple variables to be initialized with values in a pair, tuple etc. All these binding of variables with initializers done in a single statement.
Case 1:- binding an array
Each identifier in the identifier list becomes the name of lvalue for element of array. Number of elements must be equal to the number of identifiers.
int arry[3] = { 3,4,5 };
auto [a,b,c] = arry;
//here array is created and a refers to 3, b refers to 4 and c refers to 5.
Case 2:- binding a tuple like type
float fnum{};
char ch1{};
int number{};
std::tuple < float&, char&&, int > tplex( fnum, std::move(ch1) , number);
const auto& [ p, q, r] = tplex;
// p is name of structured binding referring to fnum
// q is name of structured binding referring to ch1
// r is name of structured binding referring to number
Case 3:- binding to data members
struct structVar {
mutable int num1 : 2;
volatile double num2;
};
structVar func();
const auto [ a, b] = func();
// a is an int lvalue for the 2-bit bit field
// b is a const volatile double lvalue
3. Initialization of enums using Direct List
With C++17 the enums can now be initialized using braces.
Syntax:-
enum byte : unsigned char {}; byte b0 {0}; // OK byte b1 = byte{1}; // OK byte b2 = byte{256}; // ERROR - 0 to 255 only
4. Variable declaration inside If and Switch
C++17 allows declaration of variables inside if and switch conditions. This makes it easy to use variables with same names that have different scopes.
Syntax:-
if (data type variable condition) { //statements } switch ( condition; variable ) { //statements }
5. If constexpr statement
Useful feature for template codes. The if constexpr statement is evaluated at compile time.
How it is
Helpful can be shown using comparisons below:-
General If-else statements:-
int var = 10; if (var >= 10) { var=var+10; } else { var=var-10; }
Constexpr If-else statements:-
template <typename T> auto length ( T const& value ) { //checking if T is integer or not if (is_integral<T>::value) { return value; } else { return value.length(); } }
6. Nested Namespaces
Namespaces are used to group together similar codes like classes and functions that are correlated. C++17 allows more easy syntax of using nested namespaces. Earlier the syntax was quite messy when the number of nested namespaces was more. Handling braces is now no longer required.
Before C++17:-
namespace Earth{ namespace Continent { namespace Country { class City { .......... }; } } }
New Syntax:-
namespace Earth :: Continent :: Country { class City { .......... }; }
- Related Questions & Answers
- New feature from freecharge on whatsapp
- WhatsApp’s new ‘Status’ tab feature to share Images and Videos
- ImplementJavaScript Auto Complete / Suggestion feature
- Auto-complete feature using Trie
- Explain a Feature file in SpecFlow.
- What is auto refresh feature in JSP?
- Python - How and where to apply Feature Scaling?
- New Features of C++17
- What is ABAP? Explain ABAP OOP feature in detail?
- Using Auto Documentation feature in SAP HANA Modeler Perspective
- Set search feature in MySQL for full text searching
- Drag and Drop a File feature in React JS
- Which function of scipy.cluster.vq module is used to normalize observations on each feature dimension?
- How to detect a particular feature through JavaScript with HTML
- Spring Boot Actuator A Production Grade Feature in Spring Boot
|
https://www.tutorialspoint.com/new-feature-of-cplusplus17
|
CC-MAIN-2022-27
|
refinedweb
| 770
| 63.49
|
I have tried everything I have found in monks supersearch, and all over the web. The suggestions that held the most promise were found at stackoverflow.com, but to absolutely no avail. I have tried so many different things, and so many combinations of different things in my .vimrc file, and none will work.
This problem has frustrated me for so long, and I'm at my wit's end.
To reproduce my woeful situation, one need only open a perl file in vim and type:
.. then hit the carriage return. That automatically indents your code for you, in most default vim installs. Great! That's what it should do! At this point you can start in with your code, which would look something like:
sub foo {
my $bar = 'baz';
[download]
All is well. Now hit the carriage return again and start a comment. Instantly vim outdents the comment to column zero:
sub foo {
my $bar = 'baz';
# some comment
[download]
This is exactly what I am so tired of experiencing. The comment should stay, imo, right in line with "my $bar..." at indented column n (where n=three spaces for me).
*Holds back a long string of curses* Please, anyone, can you tell me what I am missing here, and why vim just will NOT allow me to:
sub foo {
my $bar = 'baz';
# some comment
[download]
Stuck, and so sad in vim indentation hell, I remain...
Tommy:
Yeah, I can see how that would suck. I just tried the steps you mentioned on my machine, and comment lines don't outdent for me. So just in case it helps, here's my .vimrc file:
" .vimrc
" 20100104 set cursorline for better visibility
" 20080618 Trying to fix fileencoding so we can write UNICODE as LATIN
" 20080617 reopen file at same position as last seen
" 20080416 Chg/set backspace, display, fillchars, color scheme
" 20050208 original version
set fileencodings=ucs-bom,utf-8,default,latin1
"set tabstop=4
set nowrap
set ruler " show cursor position always
set showcmd " display incomplete commands
set incsearch " incremental searching
set modeline " Allow setting values in file
"set background=dark " Make color scheme visible
colorscheme roboticus
set cursorcolumn " Make cursor column obvious for icicles, etc.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
"if has("autocmd")
" " highlight the active cursor line
" set cursorline
" hi CursorLine ctermbg=1
"endif
if has("autocmd")
" highlight the active cursor line
set cursorline
"hi CursorLine ctermbg=7
hi CursorLine ctermbg=4
" Recognize file types and use appropriate indenting
filetype plugin indent on
augroup vimrcEx
autocmd FileType text setlocal textwidth=78
augroup END
else
" set autoindent
endif " has("autocmd")
" 20080416 MCM New additions
set backspace=eol,indent,start " Make backspacing a little easier
set display=lastline " Show partial lines when in wrap mode
" Doesn't work?
set fillchars=stl:=,stlnc:=
" Autowrap text with comment leader as appropriate, automatically exte
+nd com
" t - autoformat text, c - autoformat comments, r - automatically cont
+inue
" comment on next line, o - automatically continue column on o/O comma
+nd, q -
" allow comment formatting with gq command, l - don't break long lines
+ if they
" started long, b - autowrap only if you hit a blank before the wrap m
+argin.
set formatoptions=tcroqlb
" 20080617 MCM Reopen file at last-edited position (see :help
" last-position-jump)
au BufReadPost * if line("'\"") > 0 && line("'\"") <= line("$") | exe
+"normal g'\"" | endif
[download]
...roboticus. :-(
filetype indent on
[download]
autocmd FileType perl set softtabstop=3
autocmd FileType perl set shiftwidth=3
autocmd FileType perl set tabstop=3
autocmd FileType perl set expandtab
?
Deep frier
Frying pan on the stove
Oven
Microwave
Halogen oven
Solar cooker
Campfire
Air fryer
Other
None
Results (322 votes). Check out past polls.
|
http://www.perlmonks.org/?node_id=817406
|
CC-MAIN-2016-26
|
refinedweb
| 612
| 57.61
|
Opened 4 years ago
Closed 4 years ago
#16776 closed Bug (fixed)
jQuery.noConflict(false) in jquery.init.js leaks the admin jQuery into the global namespace
Description
jQuery.noConflict(true) should be used instead.
Now that django's jQuery object is namespaced to django.jQuery (#12882), it doesn't need to appear anywhere else in the global namespace. Most jQuery plugins overload the jQuery object (documented here: ), and putting the admin's object here makes it harder to use a newer version. django apps like django-selectable, which requires a recent jQuery and jQuery UI, are affected. [16415] should be reverted.
Attachments (2)
Change History (17)
comment:1 Changed 4 years ago by anonymous
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
comment:2 Changed 4 years ago by jezdez
- Triage Stage changed from Unreviewed to Design decision needed
The problem of using jQuery.noConflict(true) (and which is what was changed to jQuery.noConflict() in r16415) is that it removes any jQuery from the global namespace, even if it's the jQuery shipped with a 3rd party app.
So, with the current state of jQuery.noConflict() you should be able to put another jQuery after Django's jQuery and it should just work because it's overwriting the jQuery object in the global namespace. Unless I misunderstand something the django.jQuery object should then still be the same Django-jQuery.
comment:3 Changed 4 years ago by anonymous
jQuery.noConflict(true) actually restores the previous jQuery (from _jQuery). The admin <script> tags include jquery.min.js immediately followed by jquery.init.js . With noConflict(true), the admin has no effect on the global namespace; it will never remove an existing jQuery. I've checked the jQuery source, and the tests for this behavior appeared in (before jQuery 1.2.2).
By the way, extrahead customizations appear before the admin script tags.
Changed 4 years ago by robhudson
comment:4 Changed 4 years ago by julien
- Triage Stage changed from Design decision needed to Ready for checkin
I've talked with robhudson about this at the sprints. We could not find any specific case where the admin would not have played nicely with third-party plugins prior to [16415]. We do see, however, how leaving jQuery in the base namespace could potentially break plugins. jezdez did commit [16415] to solve a real problem but unfortunately cannot remember the exact details. For these reasons, we should revert the change as a cautionary measure and prevent potential regressions in 1.4. This is not to say that [16415] was necessary invalid -- if one can provide a specific case where this is an issue, please do yell!
comment:5 Changed 4 years ago by jezdez
- Triage Stage changed from Ready for checkin to Design decision needed
Thanks, but all I need to do is to actually search my chat logs for the specific issue since I wasn't imagining things.
comment:6 Changed 4 years ago by jezdez
- Owner changed from nobody to jezdez
comment:7 Changed 4 years ago by jezdez
Ah, another piece of the puzzle, this is what had in mind:
comment:8 Changed 4 years ago by jezdez
- Owner jezdez deleted
comment:9 Changed 4 years ago by jacob
- milestone 1.4 deleted
Milestone 1.4 deleted
comment:10 Changed 4 years ago by anonymous
- Owner set to julien
In the google groups post above, tyrion-mx suggests that the django-admin jQuery could overwrite the jQuery object as well.
This was asked for convenience, so that using jQuery plugins doesn't require a copy of jQuery. However that is a bad idea, because it ties the jQuery version to whatever Django ships (which is quite old due to release cycles, and already incompatible with django admin addons), and removes control from users of the django admin. It would break things if it appeared in a release.
Which is why I'll reiterate that django's jQuery should be self-contained, jQuery.noConflict(true) should be used, and the attached patch should be applied.
(There are some incorrect assumptions in tyrion-mx's post: {% block extrahead %} customisations, which appear before the admin jQuery, were working correctly before r16415, because noConflict(true) does not remove the jQuery object, but rather restores it.)
comment:11 Changed 4 years ago by julien
- Owner julien deleted
@anonymous: I tend to agree with you, however what we need right now is some concrete examples of how/why things would break with the current situation. Could you try to upload some code sample or maybe a sample project (in a zip file) concretely illustrating the problem that you're talking about?
Also, please do not assign tickets to other people unless they've specifically asked you to ;-)
Changed 4 years ago by anonymous
example project
comment:12 Changed 4 years ago by anonymous
Instructions for testing:
./manage.py syncdb ./manage.py runserver
Visit
In a js console, display: jQuery.fn.jquery
Try it with django 1.3.1, django 1.4pre, and with 16776.patch applied.
comment:13 Changed 4 years ago by anonymous
- Has patch set
comment:14 Changed 4 years ago by julien
- Easy pickings unset
- Triage Stage changed from Design decision needed to Accepted
Thanks for putting this sample project together. It appears quite clearly that currently the admin simply overrides any user-supplied jQuery with is own embedded one. I've talked through this with jezdez on IRC, and we'll proceed by reverting the change and adding some documentation.
comment:15 Changed 4 years ago by julien
- Owner set to julien
- Resolution set to fixed
- Status changed from new to closed
For context, noConflict(true) and the namespacing to django.jQuery appeared before releasing 1.2, and [16415] would appear in 1.4.
|
https://code.djangoproject.com/ticket/16776
|
CC-MAIN-2015-32
|
refinedweb
| 966
| 62.68
|
In an exercise in my book, I've come across an example that doesn't go too far into explaining a section of the code. I don't know what it's called so I'm having a tough time finding it. Here's a clip of it, what I've highlighted in bold and underlined is what's got me stumped...
Code :
public class Sales2 { public static void main( String[] args ) { Scanner input = new Scanner( System.in ); // sales array holds data on number of each product sold // by each salesperson double[][] sales = new double[ 5 ][ 4 ]; System.out.print( "Enter salesperson number (-1 to end): " ); int person = input.nextInt(); while ( person != -1 ) { System.out.print( "Enter product number: " ); // int product = input.nextInt(); System.out.print( "Enter sales amount: " ); double amount = input.nextDouble(); // error-check the input if ( person >= 1 && person < 5 && product >= 1 && product < 6 && amount >= 0 ) [B][U][SIZE="3"] sales[ product - 1 ][ person - 1 ] += amount;[/SIZE][/U][/B] else System.out.println( "Invalid input!" ); System.out.print( "Enter salesperson number (-1 to end): " ); person = input.nextInt(); }
Any idea what "sales[ product - 1 ][ person - 1 ] += amount;" is doing? Because I don't, I'm stumped. Anyone know what it is called at the very least? :confused: [-O<
|
http://www.javaprogrammingforums.com/%20java-theory-questions/3417-anyone-know-what-code-doing-printingthethread.html
|
CC-MAIN-2013-48
|
refinedweb
| 209
| 67.96
|
Opened 7 years ago
Closed 7 years ago
Last modified 7 years ago
#10525 closed (invalid)
staff_member_required doesn't work for FormWizard / __call__()
Description
Hi,
The "staff_member_required" decorator doesn't work for FormWizard or in general for decorating methods as for example _ _call_ _(). That's because the decorator expects the first argument to be a request instance but with methods the first argument is self and the second argument is the request object.
The patch changes this by adding a check whether the object to be decorated is a function or a method. Then it decorates the appropriate way.
In order to decorate FormWizard's _ _call_ _() you have to do this:
from django.contrib.formtools.wizard import FormWizard from django.contrib.admin.views.decorators import staff_member_required class Wizard(FormWizard): # ... pass Wizard.__call__ = staff_member_required(Wizard.__call__)
I added my changes as a patch.
Alpha1650
Attachments (1)
Change History (5)
Changed 7 years ago by anonymous
comment:1 follow-up: ↓ 2 Changed 7 years ago by Alex
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
comment:2 in reply to: ↑ 1 Changed 7 years ago by anonymous
You've got an immense amount of code duplication here(plus this same issue will be true for any other decorator), so I think a cleaner solution is needed.
I totally agree with you. I couldn't find a better solution. Maybe anyone else with better Python knowledge can. Maybe there's a general way to apply "normal" decorators to methods.
comment:3 Changed 7 years ago by jacob
- Resolution set to invalid
- Status changed from new to closed
The trick isn't to apply the decorator to the method, but to the callable directly:
wizard = Wizard() protected_wizard = staff_member_required(wizard)
comment:4 Changed 7 years ago by ckd
for this to work add the following to your wizard class:
@property def __name__(self): return self.__class__.__name__
You've got an immense amount of code duplication here(plus this same issue will be true for any other decorator), so I think a cleaner solution is needed.
|
https://code.djangoproject.com/ticket/10525
|
CC-MAIN-2016-30
|
refinedweb
| 347
| 50.06
|
Content-type: text/html
getpass - Reads a password
Standard C Library (libc.so, libc.a)
#include <unistd.h>
char *getpass(
const char *prompt);
Interfaces documented on this reference page conform to industry standards as follows:
getpass(): XPG4, XPG4-UNIX
Refer to the standards(5) reference page for more information about industry standards and associated tags.
Points to the prompt string that is written to stderr.
The getpass() function opens the process' controlling terminal file, flushes output, disables echoing, and reads up to a newline character or an end-of-file (EOF) character. The terminal state is then restored and the controlling terminal is closed.
If the getpass() function is interrupted by the SIGINT signal, the terminal state is restored before the signal is delivered to the calling process.
[DIGITAL] The getpass() function is not threadsafe because it manipulates global signal state.
The getpass() function is scheduled to be withdrawn from a future version of the X/Open CAE Specification.
Upon successful completion, the getpass() function returns a pointer string of no more than PASS_MAX bytes plus a terminating null value. This return value points to data that is overwritten by successive calls. If the controlling terminal file cannot be opened, the terminal state is restored and a null pointer is returned.
The getpass() function sets errno to the specified values for the following conditions: [DIGITAL] Search permission is denied on a component of the pathname prefix; or the file exists and the permissions specified by the mode parameter are denied; or the file does not exist and write permission is denied for the parent directory of the file to be created. The function was interrupted by a signal that was caught. Too many file descriptors are currently open in the calling process (exceeding OPEN_MAX).
Functions: fopen(3).
Files: tty(7), termios(4).
Standards: standards(5) delim off
|
https://backdrift.org/man/tru64/man3/getpass.3.html
|
CC-MAIN-2017-39
|
refinedweb
| 307
| 54.02
|
#include <sys/stream.h> #include <sys/ddi.h> void qprocson(queue_t *q);
void qprocsoff(queue_t *q);
Architecture independent level 1 (DDI/DKI).
Pointer to the RD side of a streams queue pair.
The qprocson() enables the put and service routines of the driver or module whose read queue is pointed to by q. Threads cannot enter the module instance through the put and service routines while they are disabled.
The qprocson() function must be called by the open routine of a driver or module before returning, and after any initialization necessary for the proper functioning of the put and service routines.
The qprocson() function must be called before calling put(9F), putnext(9F), qbufcall(9F), qtimeout(9F), qwait(9F), or qwait_sig(9F).
The qprocsoff() function must be called by the close routine of a driver or module before returning, and before deallocating any resources necessary for the proper functioning of the put and service routines. It also removes the queue's service routines from the service queue, and blocks until any pending service processing completes.
The module or driver instance is guaranteed to be single-threaded before qprocson() is called and after qprocsoff() is called, except for threads executing asynchronous events such as interrupt handlers and callbacks, which must be handled separately.
These routines can be called from user, interrupt, or kernel context.
close(9E), open(9E), put(9E), srv(9E), put(9F), putnext(9F), qbufcall(9F), qtimeout(9F), qwait(9F), qwait_sig(9F)
Writing Device Drivers for Oracle Solaris 11.2
STREAMS Programming Guide
The caller may not have the stream frozen during either of these calls.
|
http://docs.oracle.com/cd/E36784_01/html/E36886/qprocson-9f.html
|
CC-MAIN-2014-42
|
refinedweb
| 267
| 52.7
|
; }
The... ...If your code is too slow, you must make it faster. If no better algorithm is available, you must trim cycles."
Often, well written Perl a leaner alternative.
the subroutine and class signatures within your C++ code and creates bindings to them. Like Inline::C, you will need a suitable compiler the first time you run the script.
If you're one of the fortunate majority, you will accept the defaults as you install Inline::CPP; the correct C++ compiler and standard libraries will be configured for you. If you're one of the unfortunate (and shrinking) minority, read on.
Here's the rule: use a. Hopefully this will be deduced by default at install time.. If you haven't done so already, you should stop reading right now and read the documentation for Inline::C, including the Inline::C-Cookbook.
This module uses a grammar to parse your C++ code, and binds to functions or classes which are recognized. If a function is recognized, it will be available from Perl space. If the function's signature is not recognized, it will not be available from Perl, but will be available from other functions or classes within the C++ code.
For more information about the grammar used to parse C++ code, see the section called "Grammar".
The following example shows how C++ snippets map to Perl:
Example 1:
use Inline CPP => <<'END'; using namespace std; int doodle() { } class Foo { public: Foo(); ~Foo(); int get_data() { return data; } void set_data(int a) { data = a; } private: int data; }; Foo::Foo() { cout << "creating a Foo()" << endl; } Foo::~Foo() { cout << "deleting a Foo()" << endl; } END
After running the code above, your Perl runtime.
The first time you run a program that uses Inline::CPP, the C++ code will be compiled into an
_Inline/ or
.Inline/ folder within the working directory. The first run will incur a startup time penalty associated with compiling C++ code. However, the compiled code is cached, and assuming it's not modified, subsequent runs will skip the C++ compilation, and startup time will be fast.).
Of course, modules can be shared by multiple scripts while only incurring that compilation startup penalty one time, ever..
Some extension authors choose to implement first in Inline::CPP, and then manually tweak, then copy and paste the resulting XS file into their own distribution, with similar effect (and possibly a little finer-grained control) to the CPP2XS approach. issue is that the C++ class, "
Foo" will be mapped to Perl below the
Some::Foo namespace, as
Some::Foo::Foo, and would need to be instantiated like this:
my $foo = Some::Foo::Foo->new(). This probably isn't what the user intended. Use the namespace configuration option to set your base namespace:
use Inline CPP => config => namespace => 'Some'; the MakeMaker or XS options of the same name. See ExtUtils::MakeMaker and perlxs.
All configuration options, including the word
config are case insensitive.
CPP, and
DATA are not configuration options, and are not insensitive to case.
Adds a new entry to the end of the list of alternative libraries to bind with. MakeMaker will search through this list and use the first entry where all the libraries are found.
use Inline CPP => CPP => config => auto_include => '#include "something.h"';
Specifies code to be run when your code is loaded. May not contain any blank lines. See perlxs for more information.
use Inline CPP => config => boot => 'foo();';
Specifies which compiler to use. In most cases the configuration default is adequate.
use Inline CPP => config => cc => '/usr/bin/g++-4.6';
Specifies extra compiler flags. Corresponds to the MakeMaker option.
use Inline CPP => config => ccflags => '-std=c++11';
use Inline CPP => config => classes => { 'CPPFoo' => 'PerlFoo', 'CPPBar' => 'PerlBar' }; use Inline CPP => config => namespace => 'Qux' => classes => { 'CPPFoo' => 'PerlFoo', 'CPPBar' => 'PerlBar' }; use Inline CPP => config => classes => sub { my $cpp_class = shift; ... return($perl_package); };
Override C++ class name.
Under default behavior, a C++ class naming conflict will arise by attempting to implement the C++ classes
Foo::Bar::MyClass and
Foo::Qux::MyClass which depend upon one another in some way, because C++ sees both classes as named only
MyClass. We are unable to solve this C++ conflict by using just the
namespace config option, because
namespace is only applied to the Perl package name, not the C++ class name.
In the future, this issue may be solved via Inline::CPP suport for the native C++
namespace operator and/or C++ class names which contain the
:: double-colon scope token.
For now, this issue is solved by using the
classes config option, which accepts either a hash reference or a code reference. When a hash reference is provided, each hash key is a C++ class name, and each hash value is a corresponding Perl class name. This hash reference serves as a C++-to-Perl class name mapping mechanism, and may be used in combination with the
namespace config option to exercise full control over class and package naming.
When a code reference is provided, it must accept as its sole argument the C++ class name, and return a single string value containing the generated Perl package name. When a code reference is provided for the
classes config option, the value of the
namespace config option is ignored.
The hash reference may be considered a manual mapping method, and the code reference an automatic mapping method.
Example file
/tmp/Foo__Bar__MyClass.c:
class MyClass { private: int a; public: MyClass() :a(10) {} int fetch () { return a; } };
Example file
/tmp/Foo__Qux__MyClass.c:
#include "/tmp/Foo__Bar__MyClass.c" class MyClass { private: int a; public: MyClass() :a(20) {} int fetch () { return a; } int other_fetch () { MyClass mybar; return mybar.fetch(); } };
We encounter the C++ class naming conflict when we
use Inline CPP => '/tmp/Foo__Qux__MyClass.c' => namespace => 'Foo::Qux';
The C++ compiler sees two
MyClass classes and gives a redefinition error:
_08conflict_encounter_t_9d68.xs:25:7: error: redefinition of ‘class MyClass’ class MyClass { ^ In file included from _08conflict_encounter_t_9d68.xs:24:0: /tmp/Foo__Bar__MyClass.c:1:7: error: previous definition of ‘class MyClass’ class MyClass { ^
The solution is to rename each
MyClass to utilize unique class names, such as
Foo__Bar__MyClass and
Foo__Qux__MyClass, and use the
classes config option.
Updated example file
/tmp/Foo__Bar__MyClass.c:
class Foo__Bar__MyClass { private: int a; public: Foo__Bar__MyClass() :a(10) {} int fetch () { return a; } };
Updated example file
/tmp/Foo__Qux__MyClass.c:
#include "/tmp/Foo__Bar__MyClass.c" class Foo__Qux__MyClass { private: int a; public: Foo__Qux__MyClass() :a(20) {} int fetch () { return a; } int other_fetch () { Foo__Bar__MyClass mybar; return mybar.fetch(); } };
First, consider the following updated call to Inline using the hash reference method to manually map the namespace and class names. This example does not give any C++ errors, and runs correctly in both C++ and Perl:
use Inline CPP => '/tmp/Foo__Qux__MyClass.c' => namespace => 'Foo' => classes => { 'Foo__Bar__MyClass' => 'Bar::MyClass', 'Foo__Qux__MyClass' => 'Qux::MyClass' };
Next, consider another updated call to Inline using the code reference method to automatically map the namespace and class names, which may be deployed across more complex codebases. This example automates the mapping of the '__' double- underscore to the '::' double-colon scope token.
use Inline CPP => config => classes => sub { join('::', split('__', shift)); };
For more information, please see the runnable examples:
t/classes/07conflict_avoid.t
t/classes/08auto.t
t/classes/09auto_mixed.t CPP => config => filters => [Strip_POD => \&myfilter]; use Inline CPP => config => filters => 'Preprocess'; # Inline::Filters
The filter may do anything. The code is passed as the first argument, and it returns the filtered code. For a set of prefabricated filters, consider using Inline::Filters.
Specifies extra include directories. Corresponds to the MakeMaker parameter.
use Inline CPP => CPP => config => libs => '-L/your/path -lyourlib';
Unlike the
libs configuration parameter used in Inline::C, successive calls to
libs append to the previous calls. For example,
use Inline CPP => config => libs => '-L/my/path', libs => '-lyourlib';
will work correctly, if correct is for both
libs to be in effect. CPP => config => myextlib => '/your/path/something.o';
use Inline CPP => config => namespace => 'Foo'; use Inline CPP => config => namespace => 'main'; use Inline CPP => config => namespace => q{};
Override default base namespace.
Under default behavior, a C++ class
Foo created by invoking Inline::CPP from
package Bar will result in the C++
Foo class being accessible from Perl as
Bar::Foo. While this default behavior may be desirable in some cases, it might be undesirable in others. An example would be creating a
Foo class while invoking Inline::CPP from package
Foo. The resulting class will bind to Perl as
Foo::Foo, which is probably not what was intended.
This default behavior can be overridden by specifying an alternate base
namespace. Examples are probably the best way to explain this:
package Foo; use Inline CPP => config => namespace => 'Bar'; use Inline CPP => <<'EOCPP'; class Baz { private: int a; public: Baz() :a(20) {} int fetch () { return a; } }; EOCPP package main; my $b = Bar::Baz->new(); print $b->fetch, "\n"; # 20.
As demonstrated here, the namespace in which "Baz" resides can now be made independent of the package from which Inline::CPP has been invoked. Consider instead the default behavior:
package Foo; use Inline CPP => <<'EOCPP'; class Foo { private: int a; public: Baz() :a(20) {} int fetch () { return a; } }; EOCPP package main; my $b = Foo::Foo->new(); print $b->fetch, "\n"; # 20.
It is probably, in this case, undesirable for the C++ class
Foo to reside in the Perl
Foo::Foo namespace. We can fix this by adding our own namespace configuration:
package Foo; use Inline CPP => config => namespace => q{}; # Disassociate from # calling package. use Inline CPP => <<'EOCPP'; class Baz { private: int a; public: Baz() :a(20) {} int fetch () { return a; } }; EOCPP package main; my $b = Foo->new(); print $b->fetch, "\n"; # 20.
Specifies a prefix that will automatically be stripped from C++ functions when they are bound to Perl. Less useful than in C, because C++ mangles its function names to facilitate function overloading.
use Inline CPP CPP config => preserve_ellipsis => 1; or use Inline CPP config => enable => 'preserve_ellipsis';
For an example of why
preserve_ellipsis is normally not needed, see the examples section, below.
By default, Inline::CPP includes the standard iostream header at the top of your code. Inline::CPP will try to make the proper selection between
iostream.h (for older compilers) and
iostream (for newer "Standard compliant" compilers).
This option assures that
iostream (with no
.h) is included, which is the ANSI-compliant version of the header. For most compilers the use of this configuration option should no longer be necessary, as detection is done at module install time. The configuration option is still included only to maintain backward compatibility with code that used to need it.
use Inline CPP => config => enable => 'std_iostream';
Specifies whether to bind C structs into Perl using Inline::Struct. NOTE: Support for this option is experimental. Inline::CPP already binds to structs defined in your code. In C++, structs and classes are treated the same, except that a struct's initial scope is public, not private. Inline::Struct provides autogenerated get/set methods, an overloaded constructor, and several other features not available in Inline::CPP.
You can invoke
structs in several ways:
use Inline CPP config => structs => 'Foo'; or use Inline CPP config => structs => ['Bar', 'Baz'];
Binds the named structs to Perl. Emits warnings if a struct was requested but could not be bound for some reason.
use Inline CPP config => enable => 'structs'; or use Inline CPP config => structs => 1;
Enables binding structs to Perl. All structs which can be bound, will. This parameter overrides all requests for particular structs.
use Inline CPP config => disable => 'structs'; or use Inline CPP CPP non-trivial data structures in either C++ or Perl, you should probably just pass them as an SV* and do the conversion yourself in your C++ function.
In C++, a struct is a class whose default scope is public, not private. Inline::CPP binds to structs with this in mind -- get/set methods are not yet auto-generated (although this feature may be added..__ using namespace std; /* to program:
use Inline CPP => 'DATA'; say multiadd( 1 ); # No dispatch; just return the value. say multiadd( 1, 2 ); # Dispatch add( int, int ). say multiadd( 1, 2, 3 ); # Dispatch add( int, int, int ). say multiadd( 1, 2, 3, 4 ); # No dispatch; throw an exception. __DATA__ __CPP__ #include <stdexcept> //. try{ switch ( items ) { case 1: return SvIV(ST(0)); case 2: return add( SvIV(ST(0)), SvIV(ST(1)) ); case 3: return add( SvIV(ST(0)), SvIV(ST(1)), SvIV(ST(2)) ); default: throw std::runtime_error( "multiadd() - Too many args in function call" ); } } catch ( std::runtime_error msg ) { croak( msg.what() ); // Perl.8.1 or later. Since Inline::CPP depends on Inline, Perl 5.8.1 is also required for Inline::CPP. It's hard to imagine anyone still using a Perl older than 5.8.1.8.1 Perl.
Is Inline::CPP is ready for the C++11 standard? The short answer to that question also and lambdas. Templates don't make sense to Inline::CPP anyway. And lambdas are still fine, because they take place inside of functions, so Inline::CPP doesn't see them anyway. For now, just don't use the late return type syntax in the header of functions that need to bind to Perl. This may get fixed in future revisions to the grammar.
Another issue is bugs in code this uncivilized. If you find one, please file a bug report. Patches are even better. Patches accompanied by tests are like the holy grail.
When reporting a bug, please do the following:
- If possible, create a brief stand-alone snippet of code that demonstrates the issue. - Use L<Github Issues|> to file your bug report. - Patches are always welcome, as are tests that tickle a newfound bug. - Pull requests should avoid touching irrelevant sections of code/POD, and tests are required before they can be considered for merge.
...or...
- Put "use Inline REPORTBUG;" at the top of your code, or use the command line option "perl -MInline=REPORTBUG ...". - Run your code. - Follow the printed instructions.
Get involved! Module development is being tracked on a github repository:.
The master branch should always be buildable and usable.
Official releases have version numbers in the following format: 'x.xx', and are usually tagged with the CPAN release number.
Various development branches will hold a combination of minor commits and CPAN "Developer" releases (these may have a version number formatted as: 'x.xx_xxx' to designate a developer-only CPAN release).
Most discussion relating to this module (user or developer) occurs on the Inline mailing list, inline.perl.org, and in
#inline on
irc discovered. This is Perl, C++, and XS all sealed into one can of worms. But it can be fun, which is a description never applicable GitHub repo is:
Ingy döt Net <INGY@cpan.org> is the author of
Inline, and
Inline::C.
Issues are tracked, and may be reported at the distribution's GitHub issue tracker.
Contributors may also fork the repo and issue a pull requests. Tests should accompany pull requests, and effort should be made to minimize the scope of any single pull request.
Pull requests should not add author names. Non-trivial contributions generally warrant attribution in the log maintained in the
Changes file, though the decision to do at the discretion of the maintainers.
Please refer to the Artistic 2.0 license, contained in the
LICENSE file, included with this distribution for further explanation.
Copyright (c) 2000 - 2003 Neil Watkiss. Copyright (c) 2011 - 2014 David Oswald.
All Rights Reserved. This module is free software, licensed under the Artistic license, version 2.0.
See
|
http://search.cpan.org/~davido/Inline-CPP/lib/Inline/CPP.pod
|
CC-MAIN-2016-40
|
refinedweb
| 2,582
| 64.51
|
Hi My name is C.D.,
I am currently taking C++ 1, I have an assignment that asks me to write a function that displays the prompt string and then reads a floating point number and then returns that number. The book gives an example of the code to use in the main. My problem is I have been trying for days to get the prompt part of the functon to show on the console and I can't figure out why it won't I have tried numerous ways. Here is my latest attempt that still does not work. the program accepts and returns the numbeer but I can not figure out how tho get the function to display the prompt. Please Help! Thank You, C.D. #include <iostream> #include <string> using namespace std ; double get_double(string Prompt) { string prompt ; cout << prompt ; double salary ; cin >> salary ; return salary ; } void main() { double salary = get_double("Please enter your salary $") ; double perc_raise = get_double("What percentage raise would you like? ") ; double new_salary = salary * (perc_raise / 100) + salary ; cout << "If I give you that much of a raise you would be making $ " << new_salary << ".\nYou better be worth it \n" ; system("PAUSE") ; }
|
https://www.daniweb.com/programming/software-development/threads/459927/function-w-a-string-prompt-doesn-t-work
|
CC-MAIN-2019-18
|
refinedweb
| 196
| 77.77
|
fwrite
From cppreference.com
Writes
count of objects from the given array
buffer to the output stream
stream. The objects are written as if by reinterpreting each object as an array of unsigned char and calling fputc
size times for each object to write those unsigned chars into
stream, in order. The file position indicator for the stream is advanced by the number of characters written.
[edit] Parameters
[edit] Return value
The number of objects written successfully, which may be less than
count if an error occurs.
If
size or
count is zero,
fwrite returns zero and performs no other action.
[edit] Example
Run this code
#include <stdio.h> #include <stdlib.h> #include <assert.h> enum { SIZE = 5 }; int main(void) { double a[SIZE] = {1, 2, 3, 4, 5}; FILE *f1 = fopen("file.bin", "wb"); assert(f1); int r1 = fwrite(a, sizeof a[0], SIZE, f1); printf("wrote %d elements out of %d requested\n", r1, SIZE); fclose(f1); double b[SIZE]; FILE *f2 = fopen("file.bin", "rb"); int r2 = fread(b, sizeof b[0], SIZE, f2); fclose(f2); printf("read back: "); for(int i = 0; i < r2; i++) printf("%f ", b[i]); }
Output:
wrote 5 elements out of 5 requested read back: 1.000000 2.000000 3.000000 4.000000 5.000000
|
http://en.cppreference.com/w/c/io/fwrite
|
CC-MAIN-2017-22
|
refinedweb
| 213
| 64.41
|
FSEEK(3S) FSEEK(3S)
NAME
fseek, ftell, rewind - reposition a stream
SYNOPSIS
#include <<stdio.h>>
fseek(stream, offset, ptrname)
FILE *stream;
long offset;
long ftell(stream)
FILE *stream;
rewind(stream)
FILE *stream;
DESCRIPTION
fseek() sets the position of the next input or output operation on the
stream. The new position is at the signed distance offset bytes from
the beginning, the current position, or the end of the file, according
as ptrname has the value 0, 1, or 2.
rewind(stream) is equivalent to fseek(stream, 0L, 0), except that no
value is returned.
fseek() and rewind() undo any effects of ungetc(3S).
After fseek() or rewind(), the next operation on a file opened for
update may be either input or output.
ftell() returns the offset of the current byte relative to the begin-
ning of the file associated with the named stream.
SEE ALSO
lseek(2V), fopen(3V), popen(3S), ungetc(3S)
DIAGNOSTICS
fseek() returns -1 for improper seeks, otherwise zero. An improper
seek can be, for example, an fseek() done on a file associated with a
non-seekable device, such as a tty or a pipe; in particular, fseek()
may not be used on a terminal, or on a file opened using popen(3S).
WARNING
Although on the UNIX system an offset returned by ftell() is measured
in bytes, and it is permissible to seek to positions relative to that
offset, portability to a (non-UNIX) system requires that an offset be
used by fseek() directly. Arithmetic may not meaningfully be performed
on such an offset, which is not necessarily measured in bytes.
6 October 1987 FSEEK(3S)
|
http://modman.unixdev.net/?sektion=3&page=ftell&manpath=SunOS-4.1.3
|
CC-MAIN-2017-30
|
refinedweb
| 270
| 58.52
|
Survey period: 11 Mar 2013 to 18 Mar 2013
Pay a one-time $50 charge or pay $5 a month - but only on the months you need it. Which model works best for you?
aankur81 wrote:if i am getting the same thing for free
Lazy<Dog>
Rob Grainger wrote:Free is better
Mycroft Holmes wrote:Office etc you need to buy and buy again when you need additional features
public class Naerling : Lazy<Person>{
public void DoWork(){ throw new NotImplementedException(); }
}
Naerling wrote:Unfortunately there aren't so many good products around nowadays (not that I'm interested in anyway).
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
|
http://www.codeproject.com/Surveys/1428/Do-you-prefer-to-buy-or-rent-software.aspx?PageFlow=FixedWidth
|
CC-MAIN-2015-27
|
refinedweb
| 129
| 51.21
|
Setup
from __future__ import absolute_import, division, print_function, unicode_literals import numpy as np import tensorflow as tf from tensorflow.keras import layers
Padding sequence data
When processing sequence data, it is very common for individual samples to have different lengths. Consider the following example (text tokenized as words):
[ ["The", "weather", "will", "be", "nice", "tomorrow"], ["How", "are", "you", "doing", "today"], ["Hello", "world", "!"] ]
After vocabulary lookup, the data might be vectorized as integers, e.g.:
[ [83, 91, 1, 645, 1253, 927], [73, 8, 3215, 55, 927], [71, 1331, 4231] ]
The data is a 2D list where individual samples have length 6, 5, and an API to easily truncate and pad sequences to a common length:
tf.keras.preprocessing.sequence.pad_sequences.
raw_inputs = [ [83, 91, 1, 645, 1253, 927], [73, 8, 3215, 55, 927], [711, 632, 71] ] #)
[[ 83 91 1 645 1253 927] [ 73 8 3215 55 927 0] [ 711 632 71 0 0 0]])
tf.Tensor( [[ True True True True True True] [ True True True True True False] [ True True True False False False]], shape=(3, 6), dtype=bool) True True True] [ True True True True True False] [ True True True False False False]],.
Note that in the
call method of a subclassed model or layer, masks aren't automatically propagated, so you will need to manually pass a
mask argument to any layer that needs one. See the section below for details.
For instance, in the following Sequential model, the
LSTM layer will automatically receive a mask, which means it will ignore padded values:
model = tf.keras.Sequential([ layers.Embedding(input_dim=5000, output_dim=16, mask_zero=True), layers.LSTM(32), ])
This is also the case for the following Functional API model:
inputs = tf.keras.Input(shape=(None,), dtype='int32') x = layers.Embedding(input_dim=5000, output_dim=16, mask_zero=True)(inputs) outputs = layers.LSTM(32)(x) model = tf do something: id=4730, shape=(32, 32), dtype=float32, numpy= array([[-0.00149354, -0.00657718, 0.0043684 , ..., 0.01915387, 0.00254279, 0.00201567], [-0.00874859, 0.00249364, 0.00269479, ..., -0.01414887, 0.00511035, -0.00541363], [-0.00457095, -0.0097013 , -0.00557693, ..., 0.00384533, 0.00664415, 0.00333986], ..., [-0.00762534, -0.00543655, 0.0005238 , ..., 0.01187737, 0.00214507, -0.00063268], [ 0.00428915, -0.00258686, 0.00012214, ..., 0.0064177 , 0.00800534, 0.00203928], [-0.01474019, -0.00349469, -0.00311312, ..., -0.0064069 , 0.00472621, 0.005593 ]],.
Most layers don't modify the time dimension, so don't need to worry about masking. The default behavior of
compute_mask() is just pass the current mask through in such cases.
Here is an example of a
TemporalSplit layer that needs to modify the current mask.
class TemporalSplit(tf( [[ True True True] [ True True False] [False False False]], shape=(3, 3), dtype=bool)
Here is another example of a
CustomEmbedding layer that is capable of generating a mask from input values:
class CustomEmbedding(tf False True True] [ True True True True True True True True True True] [False True False True True True False True False True]], shape=(3, 10), dtype=bool).
class MaskConsumer(tf.keras.layers.Layer): def call(self, inputs, mask=None): ...
Recap
That is all you need to know about writing subclassed models or when using layers in a standalone way, pass the
maskarguments to layers manually.
- You can easily write layers that modify the current mask, that generate a new mask, or that consume the mask associated with the inputs.
|
https://www.tensorflow.org/guide/keras/masking_and_padding?hl=ko
|
CC-MAIN-2019-47
|
refinedweb
| 559
| 58.11
|
Hello!
So here is the start for my C++ tutorials. The reason for making these posts are to empower what I have learned so I do not forget the codes that I worked hard to learn, to learn new things as I go on to more advanced areas in C++ and to learn to instruct others. My aim is to learn to be able to run a local program that can install, save and retrieve data.
Before I dive in to the first program, I will go some background information for the environment that needs to be installed. There are many different compilers all with their good and bad sides. Some of the compilers are free and in some you have to pay for the software monthly or one time fee depending on the compiler and the company/individual that provides them. There are many better compilers than what I use in my tutorials, but I will just do it for the sake of the familiar environment. You can choose any other compiler you want because C++ should run the same in any other platform as well.
I personally use bloodshed DEV C++ and here is the link to their website. You install it like any other program and start it by double clicking on it where the program should look like this. When you start the program, a tip bar will open up. You can either read it or just close it.
Go to the File –> New –> Source file from the top left of the program.
I think that you don not need to know about making a project folder so I will not go into that subject but the Source file should look something like this.
The learning material, that we are going to use for this tutorial is from the following pages.
Now I will jump in to some theory like history and development of C++, because I think it is very important for everyone to know some background information of their own area of study. C++ was developed by Bjourne Stroustrup and the language itself is combination of both High and low level language. Meaning that the language is made up of language know to us humans, that was made up to ease the job of the programmers by implementing basic rules/laws on how to build it in a way that the computer is able to understand it. The low level language instead is a language that is said to be closer to the hardware meaning that the code is bunch of numbers and alphabets. Its much more harder to be understood by ordinary people like you and me but the code is said to be more efficient, better and faster.
Without going to the whole history of different programming languages and the history of the computers I will skip ahead back to essentials of C++.
For more information please visit the link below or Google it. Wikipedia also has a good information base about C++.
Basically C++ is a good programming language with C and C# if you want to be able to have more control over the memory and be closer to hardware. C++ is also a very logical language where instead of learning abstract laws and rules of how to compile your program, in C++ the way of compiling a code is meant to be logical and algorithmic meaning that it’s very easy language to work your codes on if you have brains for some mathematical thinking. That is how I think of C++. It all depends on what do you want to achieve with your code. I recommend you to Google different companies that use C++ in their work and I guarantee you that you will be surprised of the amount of companies that work with it.
Different languages have different attributes that are better to work on in different fields. For business applications that work on the internet, the most popular language, I think is java and incorporation of different technologies with it. Then again, you will see that there is programs that work for example like in satellites that were written in Java.
Anyway, enough with the gibberish talk. I will add theory as we will move on with the tutorial as I will learn more (again) about the language that I have started to forget.
For our first program we will write a “Hello World” program like in every other coding language to see if our compiler and environment is installed properly.
In the first line of our first program we will write
#include <iostream> // A header that contains how cout (“ceeout”) work’s
iostream is basically a library and this library contains code to handle the I/O and you should always the the using namespace std in your program with this.
That according to a website means
"#include <iostream>Lines beginning with a hash.”
It means that you are able to print text on the screen in the C++ program and take input from the user in the form of
cin >> variableName;
Next we will have to add.”
and then we add
int main()
{
//The program code will be written here
.
Now the reason for the copy paste fest is the reason that, in these day’s there so much misinformation among people about the real functionality of the codes and what they really mean, that I thought that it would be good to just paste the description. I will later add the original manual description here for you to get a better idea of what is really happening. Please under no circumstances make examples with C++ functionality with real world object because, in my opinion it’s better for student to know what the codes really mean than to teach them with drawn pictures of colorful boxes with = signs and give a story for all this. It is a good way to teach the rules of the compiler but in the long run, it will just make students more confused when they will get into more complex programming tasks.
Statements like “It will shove the value 1 inside this box named i that can take values between x-y” do not help the students to understand what really happens in the machine level so that they would understand the meaning of the real objective of programming that is creating programs, that work efficiently as possible with good programming standards.
Anyway lets get back to our code. The next line will contain the functionality that will print “Hello World!” on the screen.
cout << “Hello World!” << endl;
Now what happened in the code above is that the C++ will print the code with the
C out function where the text between the “quotes” will be printed and note that you have to enclose the “Hello World!” between the << code line << to make it work because it means that it will start a new function with the cout. In the end we have endl meaning End Line that is equivalent of new line ( \n or println() in java ). Later we will learn how to do mathematical operations in this same line so it’s important for you to understand to be able to segment the code.
"cout is an object of class ostream that represents the standard output stream. It corresponds to the cstudiostream, among others (see ostream). “
For example
cout << “Hello World!” << ” You suck! ” << 1+1 << endl;
will print on the screen
Hello World! You suck! 2
Where the 1+1 is a mathematical operation when it’s not enclosed in the “quote” marks.
So you now should understand that the quote marks will turn the line into text based for example
cout << “1+1” << endl;
would print on the screen
1+1
After the text you want to print on the screen you have to write
system
(
"pause"
);
That will pause the function/code in somewhere of the code where you have to press a button for it to continue to function. We will use it in our code to pause the code so we can see it on the command line. Otherwise without the pause, the compiler will finish it in a millisecond and we wont be able to see the “Hello World!” on the screen. After Pause write
return 0;
Meaning
.”
After all this your code should look something similar like mine below
#include <iostream>
using namespace std;
int main(void)
{
cout << “Hello World!” << endl;
system(“pause”);
return 0;
}
If you were able to see the hello world text, you have successfully compiled your first program. Otherwise, you did something wrong in the process for example forgot semicolons or added too many semicolons or there is something extra in your code. The output should look something like below depending again on the values you gave.
As you can see there is something written in Finnish language “Jatka painamalla mitä tahansa näppäintä . . .” meaning, “Continue by pressing any key . . .”
The reason for that is the pause function that we added. Otherwise you would not have had the terminal open. Some might say that pause is a bad programming style and that you should never use it but for educational purposes, it do not think that there is any major reason why we should not use it. Always remember to save your work in different versions. The end of the C++ files is called .cpp.
Feel free to comment. I will update this section constantly with more theories and content.
|
https://kuroshfarsimadan.wordpress.com/2013/02/08/introduction-to-c/
|
CC-MAIN-2017-26
|
refinedweb
| 1,584
| 66.88
|
Pick of the Wikis: DokuwikiBy Harry Fuecks
Been slowly evaluating some of the wiki’s out there over the past few months and going to (dare to) recommend one or two of the PHP wiki’s out there.
The main reason for shopping around is the current WACT wiki, which uses PHPWiki.
While there’s nothing fundamentally wrong with PHPWiki, the more documents and versions of documents you have, the slower it seems to get. Times I’ve tried to research why it’s getting slow, I’ve found the code to be lacking in transparency – could be that’s just me but really not interested in spending a lot of time getting to know the code base. So right now PHPWiki amounts to a “beast” I don’t want to messing around with.
Also, as Jeff mentions;
the wiki markup style seems almost non-deterministic. I never know what the page is going to look at when I edit it.
Another problem (a complaint we’ve had) is the lack of some kind of index / site map. There’s a more than a few pages in WIKI which aren’t referenced anywhere and to only way to make them discoverable is by manually building pages of links (as we’ve done here).
Otherwise, with the PHPWiki code base being a “thing” I don’t think any of us want to touch, we can’t really take advantage of it elsewhere, such as truly integrating the generated API docs with the wiki (there’s a separate blog here about integrating generated API docs with dynamic content,for user comments etc. that I’ll get to another time) or generating some kind of downloadable “manual” from it.
Finally I feel uncomfortable about the content being stored in a database – it makes difficult to modify the WIKI via anything but the web interface among many other things.
Anyway, one or two of the other WIKI’s I’ve looked at (these are all PHP based but others like TinyWiki were very tempting);
– MediaWiki – now Wikipedia is powered by MediaWiki (as they mention here – the ultimate case for PHP and scaling?) which clearly makes it a very strong candidate. It has some great features like docbook export and the code base is generally a pleasant to explore. What I don’t like though is it uses a database again (although it does come with an excellent selection of supporting admin tools) and get the general feeling that it would become “the center of the universe” if we used it, making things like integration with the API docs tricky.
– Yawiki, which is work in progress from Paul Jones who you may know from Savant. In general like where it’s going, particularly the clean code base. It’s using a DB again though and really looking for something more evolved (0.17 last time I looked). Way well take advantage of Text_Wiki when it comes to migrating from PHPWiki though.
– PmWiki is a files based wiki and almost the outright “winner” for what I’m looking for. Get a good feeling about the sanity of the developers exploring the code in the sense that they seem to have used the simplest implementation possible in all cases and I suspect it would scale well, in terms of the volume of information it is managing. Not so good is that keyword ‘global’ which is all over the code. Also I have my doubts about the format content is stored in; it’s a kind of ini-file, which is going to need a specialised parser in addition to the parser for wiki markup. Also changes (diffs) are stored along with the content itself (in a single file) which is likely to result in some pretty big files as a page undergoes multiple edits (note is does store the most recent version of the page as a single entity, which is good – it’s not reconstructing the page from the diffs). Otherwise the markup is similar to PHPWiki’s and may well lead to the problems of determinism again.
– DokuWiki – the more I look at it, the more I like it (the code is here). I think Andreas Gohr, the author, has managed to get the fundamentals exactly right…
+ It’s files based and what get’s stored is exactly what you typed in. That helps a lot if you need to use standard filesystem tools for editing. For example DokuWiki uses the Unix find(1) and grep(1), by default, for searching.
+ It uses namespaces when creating pages. Namespaces relate to the URL. Each namespace is a directory so if my page ID is wact:tags:list it will correspond to a file / directory structure like ./wact/tags/list.txt – that makes it possible to build useful indexes of the WIKI.
+ The wiki syntax looks deterministic plus Dokuwiki comes with an editing toolbar to help with markup and also supports keyboard shortcuts.
+ Old revisions of documents are stored separately in zipped archives. Online diffs are supported.
+ Dokuwiki manages conflicts, when two people are editing the same document, in a similar way to CVS – the second person to save their document is forced to manage the change (with help from a diff).
+ It’s buzzword compliant (CSS, XHTML, RSS etc.).
On the downside, it doesn’t seem to handle i18n character sets yet (which may involve re-writing it’s wiki parser which currently relies on PCRE) but the code base is (surprisingly) small and generally easy to understand – there’s some room from improvement in the code (seen from my angle anyway) but nothing major and I imagine it would be very easy to make changes incrementally. Because the fundamentals are right (in particular the way files are stored) can see myself being able to integrate this with WACT’s API docs.
Whether it scales is also an unanswered question. The index generation, for example, may need some examination and some of the configuration files (like the wordblock file) may need breaking into smaller pieces as they grow. Again, because I think Dokuwiki does the right thing in storing files, tuning it for capacity shouldn’t be a major issue.
Anyway – hope that’s some useful research. Thanks to Andreas for Dokuwiki – any chance of getting it on Sourceforge?
Pingback: ..()
|
https://www.sitepoint.com/pick-of-the-wikis-dokuwiki/
|
CC-MAIN-2017-13
|
refinedweb
| 1,054
| 66.67
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.