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 |
|---|---|---|---|---|---|
Remote Debugging with PyCharm
Introduction
What to do, if the interpreter you are going to use, is located on the other computer? Say, you are going to debug an application on Windows, but your favorite interpreter is located on Mac... With PyCharm, it's not a problem.
Before you start
Make sure that you have an SSH access to Mac computer!
Creating a project
On Windows, create a pure Python project, as described in the section Creating Pure Python Project.
In this tutorial, the project name is
QuadraticEquation.
Preparing an example
Add a Python file to this project (Alt+Insert - Python File). Then, type the following code:
import math)
Using a remote interpreter
Configuring a remote interpreter on Windows
Note that any remote interpreter will do.
Click Ctrl+Alt+S to open the Settings dialog on the Windows machine (the whole process is described in the section Accessing Settings).
Next, click the Project Interpreter node. On this page, click the gear button (
):
Then choose the remote interpreter:
Next, in the Configure Remote Python Interpreter dialog box, click the Deployment Configuration radio-button:
Then click the browse button (
) next to the Deployment configuration field.
The Add server dialog box opens. There, enter the server name (let it be
MySFTPConnection) and choose the server type from the drop-down list. Select SFTP to tell PyCharm to transfer files over the SSH connection. Next, the deployment settings dialog opens for
MySFTPConnection. In the Connection tab, enter the following::
- In the field Name, type the connection name. Here it's MySFTPConnection.
- In the Type field, choose the connection type. Here it's SFTP.
- In the SFTP host field, enter the address of your Mac computer (for example, IP).
- Type user name on the Mac computer.
- As the authentication type is set to Password, choose this option and enter your Mac password.
In general, it's recommended to use the default settings. The only setting worth checking is the check box Save password.
Next, click the Mapping tab. The Local path field is set by default. You have to specify the path on the server
MySFTPConnection. To do that, click the browse button (
) next to the Deployment path on server 'MySFTPConnection' field. The dialog box that opens shows the contents of your Mac computer:
Now your remote interpreter is ready.
Deploying your application to a remote host
Next, your application must be deployed to the remote host. Let's do it. On themenu, point to node, and then choose :
File Transfer tool window appears, with the balloon showing the number of transferred files.
Debugging your application
Now you are ready for debugging! Right-click the editor background and choose the(here ).
Note that debugging actually takes place on the Mac computer!
Using the Python Remote Debug configuration
Let's do same not with the remote interpreter, as it has been done in the first part of this tutorial, but with the dedicated run/debug configuration, namely, Run/Debug Configuration: Python Remote Debug.
Creating run/debug configuration
On the main menu, choose Run/Debug Configurations Dialog opens. You have to click
on the toolbar, and from the list of available configurations, select Python Remote Debug.
Enter the name of this run/debug configuration - let it be MyRemoteMac. Specify the port number (here
12345), and in the field Local host name change
localhost to the IP address of the Windows computer.
Don't forget to specify the path mappings! You have to map the local path on Windows to the remote path on Mac:
Then look at the dialog box. You see the message:
Let's do what is suggested there and change the source code. First, let's copy the
pycharm-debug-py3k.egg file to the project root. Second, let's change the
quadratic_equation file as follows:
import math #==============this code added==================================================================================: import sys sys.path.append("pycharm-debug-py3k.egg") import pydevd pydevd.settrace('<address of the Windows machine>', port=12345, stdoutToServer=True, stderrToServer=True) #===============================================================================================================)
Creating a SFTP connection
First, create the folder on Mac, where the file
quadratic_equation.py should be uploaded. To do it, in the Terminal create the directory
QuadraticEquation__:
mkdir QuadraticEquation__
Now, considering that we should upload this code, let's create a connection profile. To do it, on the main menu, choose
, and in the Add Server dialog select the connection type (here SFTP) and enter its name (here
MySFTPConnection.)
In the Connection tab, specify the SFTP host (address of the Mac computer), user name and password (for Mac).
Note that the user should have an SSH access to Mac computer!
Next, click Mappings tab, and enter the deployment path in server. The server is
MySFTPConnection, so click the browse button and select the required folder. Note that the browse button shows the contents of Mac! Apply changes and close the dialog.
Deploying files to Mac
Next, you have to deploy the two files (copy of
pycharm-debug-py3k.egg and
quadratic_equation.py) from Windows to Mac.
Then on Windows, in the Project Tool Window, select the two files (
pycharm-debug-py3k.egg and
quadratic_equation.py), right-click the selection and choose Upload to MySFTPConnection. The files from Windows will be uploaded to Mac, which is reflected in the File Transfer tool window:
Launching the Debug Server
Choose the run/debug configuration created in the section Remote Debugging with PyCharm, and click
:
The Debug Tool Window shows the Waiting for process connection.. message, until you launch your script on Mac, and this script will connect to the Debug Server.
Launching file on Mac
Next, you have to launch the
quadratic_equation.py file on Mac. To do that, in the Terminal, enter the following command:
...$python3 quadratic_equation.py
Debugging on Windows
Now lo and behold! Your code on Windows shows the results of the inline debugging and hit breakpoint; the Debug tool window switches to the Debugger tab and shows the stepping toolbar, frames and variables with their values (entered on Mac):
Note that the code is actually executed on Mac, but debugged on Windows!
Summary
In order to debug with a remote interpreter, you have to start your program through PyCharm, which is not always possible. On the other hand, when using the Debug Server, you can connect to a running process.
Compare the two approaches.
In the first case, we
- configured a remote interpreter on Windows.
- deployed the script to Mac.
- debugged the script. Note that we've started the debugger session on Windows, but actual debugging takes place on the Mac computer.
In the second case, we
- created a debug configuration (Debug Server) on Windows.
- launched the Debug Server on Windows. The Debug Server waits for connection.
- executed the Python script on Mac. The script connects to the Debug Server.
- debugged the script on Windows.
It's up to you to choose the way you debug your scripts. | https://www.jetbrains.com/help/pycharm/2017.3/remote-debugging-with-pycharm.html | CC-MAIN-2018-26 | refinedweb | 1,141 | 58.28 |
After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast char to byte.
The byte takes 1 byte of memory and char takes 2 bytes of memory. Here, casting rules do not work as byte can take a negative value where as char is always positive (char is unsigned by default in every language). The type conversion from char to byte requires explicit casting. It should be noted that any data type conversion to char requires explicit casting (explicit type conversion takes care of negative value). Explicit casting truncates the mantissa (value after decimal point) part of float and double. "boolean" is incompatible to convert into char.
Either char to byte or byte to char requires explicit casting. Following program explains.
public class Conversions { public static void main(String args[]) { char ch = 'A'; // 2 bytes // byte b1 = ch; // error, 2 bytes to 1 byte byte b1 = (byte) ch; // explicit conversion from char to byte System.out.println("char value: " + ch); // prints A System.out.println("Converted byte value: " + b1); // prints 65 (ASCII value A) } }
Output screenshot of char to byte Java
byte b1 = ch;
The above statement raises a compilation error "possible loss of precision".
byte b1 = (byte) ch;
The char ch is explicitly type casted to byte b1. Observe the syntax of explicit casting. On both sides, it should be byte only. It is known as narrowing conversion.
1 thought on “char to byte Java”
please tell how to convert char to byte array? | https://way2java.com/casting-operations/java-char-to-byte/ | CC-MAIN-2022-33 | refinedweb | 252 | 65.32 |
Fix the paginator results
Bütçe .
Seçilen:
Hello, I've developed several Laravel projects for 2+ years. I'll take a look of the flow of your project. I'll check on your Eloquent queries (if any) to determine what's hindering the result of the criteria. I may Daha fazlası
27 freelancers are bidding on average $32 for this job
Any idea which version is being used? How will I get access to the code?..............................................
I have gone through all the requirements and I consider myself as a good fit for all the requirements, and I feel myself fully confident that I can make significant contributions to your project. I was hoping we could Daha fazlası
Hi There, We are a team of Laravel experts having combined experience of more than 7-8 years in Laravel and already completed more than 232 projects successfully. Please check out our profile here:- Daha fazlası
Hi, I am joomla, virtuemart expert having 5 years of experience. I have done highest projects here in Joomla. Recently i completed these projects [url removed, login to view]
I think I am a suitable candidate for this job because I have a very good experience and work hard. Could you interview me? Thank you for your time. Looking forward to hearing from you. Could you give me a chancelası
Hi, Can i talk to you..? I'm ready to do it,because i have 7 + years exp. in Laravel with all php frameworks and also expert in Javascript ,jQuery,angular js. This is my live Laravel Project Portfolio. http Daha fazlası
Benefits To Hire Us: Fast Turnaround Time Mon to Sat Working -> 4+ years of experience -> Affordable Pricing Plans -> 100% satisfaction assured -> Reliable - Friendly and Professional -> No need to release Daha fazlası
Hello, Greetings from web n soft solution Web N Soft Solution is a Mobile/Web app developer with over 5+ years experience of development, having a team of 10+ designers, developers, testers. We are experts in PHP
Hello, I must admit i do not have a lot experience with Laravel. Only did 2 small projects. But i have 3 years experience with OOP PHP, namespaces, and Ruby on Rails framework which has same MVC structure. I also bu Daha fazlası
Hi Hiring Manager, We at silverStone IT Solutions are ***CSS, PHP, WordPress, eCommerce, HTML, Shopping Carts, Website Design*** and other web technologies. our company is best to provide the software services to t | https://www.tr.freelancer.com/projects/php/Fix-the-paginator-results/ | CC-MAIN-2018-09 | refinedweb | 408 | 63.09 |
Posted 22 Jul 2011
Link to this post
Posted!
Public Class Test
Public Property Value As String
End Class
Posted 02 Aug 2011
Link to this post
Posted 05 Aug 2011
Link to this post
Posted 08 Aug 2011
Link to this post
Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get now >>
Posted 30 Oct 2012
Link to this post
Posted 14 Dec 2012
Link to this post
Posted 17 Dec 2012
Link to this post
Thanks for contacting us.
I think that you have different warning than the mentioned in this topic. I think that you receive : "Name does not match the naming convention. Suggested name Prj.Core.Setting" which is caused by the acronym that you are using PRJ. By default JustCode supports acronyms which are two letters long. If you want to add some other acronym with different length you should add it manually at JustCode's menu > Options > Code Style > specific language (e.g. C#) > Naming Conventions . There in the right side window you will notice Allowed Acronyms text box. Add there PRJ and the warning will disappear.
I hope this will help you.
Thanks.
Please, do not hesitate to contact us if you have any further questions or need of assistance.
Posted 19 Aug 2013
Link to this post
Posted 20 Aug 2013
Link to this post
Yes, JustCode provides a "Do Not Contribute to Namespace" property inside Visual Studio's Properties window. All you need to do is select the folder in Solution Explorer and set the property value to "True".
Here is a short video showing how to do that.
If you have other questions, please do not hesitate to contact us.
Regards,
Unfortunately I cannot reproduce your problem. Could you please open a support ticket and, if possible, attach a sample solution to help us pinpoint the problem?
Thanks!
Posted 21 Aug 2013
Link to this post
There is one more thing I'd like to know, just to be sure we're on the right track: what type of project do you use?
Posted 22 Aug 2013
Link to this post
Posted 23 Aug 2013
Link to this post
Thanks for the additional information, it helped us clarify the problem. The "Do Not Contribute to Namespace" property is not available in WebSites and currently it is not possible to configure this setting manually. I logged an item for that in our backlog, so stay tuned!
Posted 11 Sep 2013
Link to this post
Posted 13 Sep 2013
Link to this post
Hello Rodolfo,I think you should try following syntax for the problem : name = <namespace identifier> separator <local name> and get proper solution.Thanks for sharing the post. Great job.....
Posted 16 Sep 2013
Link to this post
Thanks for the screenshot.
The namespace should start with the current project name (e.g. Library) and then continue with the folder name (if there is any).
I am not sure what the warning says, but if you execute the "Fix Namespace" command from the Visual Aid > Fix menu your namespace should become 'Library', because this is your project name and the interface is not in a folder.
Thanks. | http://www.telerik.com/forums/the-namespace-of-this-type-doesn-t-match-the-project-default-namespace-directory | CC-MAIN-2017-22 | refinedweb | 531 | 70.73 |
GIF to say, Matlab is like iOS and Python is Android. For doing this in Matlab, all ingredients were in place, but in python, this isn’t the case.
So here are the 3 long steps in Python to get a GIF animation.
Step 1:
Download Figtodat and images2gif
Step 2:
Import Figtodat and writeGif
import Figtodat from images2gif import)
Don’t want to spend time finding the listed modules, download them directly from the link at the end of the post.
Here’s the complete code.
# -*- coding: utf-8 -*- """ @author: Sukhbinder Singh """ import Figtodat from images2gif import writeGif import matplotlib.pyplot as plt import numpy figure = plt.figure() plot = figure.add_subplot (111) plot.hold(False) # draw a cardinal sine plot images=[] y = numpy.random.randn(100,5) for i in range(y.shape[1]): plot.plot (numpy.sin(y[:,i])) plot.set_ylim(-3.0,3) plot.text(90,-2.5,str(i)) im = Figtodat.fig2img(figure) images.append(im) writeGif("images.gif",images,duration=0.3,dither=0)
27 thoughts on “GIF animation in Python in 3 Steps”
your code doesnot work:
File “…./Figtodat.py”, line 27, in fig2data
buf = numpy.fromstring ( fig.canvas.tostring_argb(), dtype=numpy.uint8 )
AttributeError: ‘FigureCanvasMac’ object has no attribute ‘tostring_argb’
Thanks luyi for bringing this to my notice….but It works on my system office and home.. Can you please let me the version of python, numpy… will investigate when i get some time….
Is it necessary the PIL liblary?
Yes PIL or pillow library are necessary thanks
Thank you! Now it works 🙂
Cheers!! Thanks for reading. 🙂
Having same troubles as Elena. Would love to know how it was solved
Hi Do you have PIL installed?
Hi,
Yes I have PIL installed. As a check, when I run –> python -c “import PIL.Image” <– I don't get any error
Ok. Then PIL is not the problem… Can you please give the specific error you are getting. I will check and see . Also what is the OS you are working on? Thanks
I am using OSX and here is the error lines:
buf = numpy.fromstring ( fig.canvas.tostring_argb(), dtype=numpy.uint8 )
AttributeError: ‘FigureCanvasMac’ object has no attribute ‘tostring_argb’
Ok.. Thats explains it. I have tested it in windows. Let me check on Mac. Will do so during weekend.
How to install Figtodat
Hi Raula, you can download the file and keep it in python path
Hi, i faced return ‘None’, thats the reason globalPalette is ‘None’.
PIL is installed, my python version is 2.7.10, and numpy version is 1.9.2
What would be the possible problem and solution?
Hi, i face returns ‘None’. Thats the reason that globalPalette is ‘None’.
My python version is 2.7.10, numpy version is 1.9.2, and PIL is installed.
So what would be the possible problem and solutions?
Regards,
Lee
Sorry for the delayed response… I will try this and post a reply.. Thanks for reading..
none of your scripts run; stop posting!
Perry,
I have seen this problem with this script. I would like to investigate it when I have some free time.
It used to work. Is there any other script that you are mentioning?
Thanks
I have the same problem as Lee can you explain why it does not work please ? Thank you for your work.
Hi there
Thanks for the comment. I am aware that now the code is not working. Because of some changes in matplotlib, something is broken.
I will try to find some time to dig into this issue this weekend.
Thanks
Thanks a lot for this post, however, I downloaded your zip file and run the code with the following error message. I tried update PIL and replaced `PIL.Image.fromString` to `PIL.Image.frombytes` but still the same error message as follows:
I am using Mac OsX and python 2.7 and other libraries are quite recent.
Could you help me to find out why? Thanks a lot
“`
TypeError Traceback (most recent call last)
in ()
18 images.append(im)
19
—> 20 writeGif(“images.gif”,images,duration=0.3,dither=0)
/Users/Natsume/Downloads/python_gif/images2gif.pyc in writeGif(filename, images, duration, repeat, dither, nq)
350 # Write
351 try:
–> 352 n = _writeGifToFile(fp, images2, duration, loops)
353 finally:
354 fp.close()
/Users/Natsume/Downloads/python_gif/images2gif.pyc in _writeGifToFile(fp, images, durations, loops)
221 # Write
222 fp.write(header)
–> 223 fp.write(globalPalette)
224 fp.write(appext)
225
TypeError: argument 1 must be string or buffer, not None
“`
Hi Daniel
Yes currently the code is not working. I have to sit and look into it.
It’s related to the PIL version..
I will try to find the solution and post back.
Thanks for reading
Have the same problem as Lee.
Hi
Thanks for this. I am working on it. It’s related to new PIL version.
Thanks
The images2gif author has given up maintaining that script, and now recommends a simpler approach using the newer imageio package:
Yes Tom. Thanks for the info. I haven’t tried imageio hope to give it a spin during weekend. Also try to make images2gif running again as not many will want to have a new library just for creating gif.
Thanks | https://sukhbinder.wordpress.com/2014/03/19/gif-animation-in-python-in-3-steps/ | CC-MAIN-2017-39 | refinedweb | 873 | 78.85 |
Deploying a Kubernetes Cluster With Amazon EKS
Deploying a Kubernetes Cluster With Amazon EKS
Take a look at how to deploy the most popular container orchestration service using the most popular cloud platform.
Join the DZone community and get the full member experience.Join For Free
There’s no denying it — Kubernetes has become the industry standard for container orchestration.
In 2018, AWS, Oracle, Microsoft, VMware and Pivotal all joined the CNCF as part of jumping on the Kubernetes bandwagon. This adoption by enterprise giants is coupled.
Leave the selected policies as-is, and proceed to the Review page.
Enter a name for the role (e.g. eksrole) and hit the Create role button at the bottom of the page to create the IAM role.
The IAM role is created.:- 09/amazon-eks-vpc-sample.yaml
Click Next.
Give the VPC a name, leave the default network configurations as-is, and click Next.
On the Options page, you can leave the default options untouched and then click Next.
On the Review page, simply hit the Create button to create the VPC.
CloudFormation will begin to create the VPC. Once done, be sure to note the various values created — SecurityGroups, VpcId and SubnetIds. You will need these in subsequent steps. You can see these under the Outputs tab of the CloudFormation stack:
Step 3: Creating the EKS Cluster
As mentioned above, we will use the AWS CLI to create the Kubernetes cluster. To do this, use the following command:
aws eks --region <region> create-cluster --name <clusterName> --role-arn <EKS-role-ARN> --resources-vpc-config subnetIds=<subnet-id-1>,<subnet-id-2>,<subnet-id-3>,securityGroupIds= <security-group-id>:
aws eks --region us-east-1 create-cluster --name demo --role-arn arn:aws:iam::011173820421:role/eksServiceRole --resources-vpc-config subnetIds=subnet-06d3631efa685f604,subnet-0f435cf42a1869282, subnet-03c954ee389d8f0fd,securityGroupIds=sg-0f45598b6f9aa110a
Executing this command, you should see the following output in your terminal:
{ "cluster": { "status": "CREATING", "name": "demo", "certificateAuthority": {}, "roleArn": "arn:aws:iam::011173820421:role/eksServiceRole", "resourcesVpcConfig": { "subnetIds": [ "subnet-06d3631efa685f604", "subnet-0f435cf42a1869282", "subnet-03c954ee389d8f0fd" ], "vpcId": "vpc-0d6a3265e074a929b", "securityGroupIds": [ "sg-0f45598b6f9aa110a" ] }, "version": "1.11", "arn": "arn:aws:eks:us-east-1:011173820421:cluster/demo", "platformVersion": "eks.1", "createdAt": 1550401288.382
It takes about 5 minutes before your cluster is created. You can ping the status of the command using this CLI command:
aws eks --region us-east-1 describe-cluster --name demo --query cluster.status
The output displayed will be:
"CREATING"
Or you can open the Clusters page in the EKS Console:):
aws eks --region us-east-1 update-kubeconfig --name demo
You should see the following output:
Added new context arn:aws:eks:us-east-1:011173820421:cluster/demo to /Users/Daniel/.kube/config
We can now test our configurations using the
kubectl get svc command:
kubectl get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE kubernetes ClusterIP 10.100.0.1 <none> 443/TCP 2m kubectl get svc
Click the cluster in the EKS Console to review configurations::- 09/amazon-eks-nodegroup.yaml
Clicking Next, name your stack, and in the EKS Cluster section enter the following details:
- ClusterName – The name of your Kubernetes cluster (e.g. demo)
- ClusterControlPlaneSecurityGroup – The same security group you used for creating the cluster in previous step.
- NodeGroupName – A name for your node group.
- NodeAutoScalingGroupMinSize – Leave as-is. The minimum number of nodes that your worker node Auto Scaling group can scale to.
- NodeAutoScalingGroupDesiredCapacity – Leave as-is. The desired number of nodes to scale to when your stack is created.
- NodeAutoScalingGroupMaxSize – Leave as-is. The maximum number of nodes that your worker node Auto Scaling group can scale out to.
- NodeInstanceType – Leave as-is. The instance type used for the worker nodes.
- NodeImageId – The Amazon EKS worker node AMI ID for the region you’re using. For us-east-1, for example: ami-0c5b63ec54dd3fc38
- KeyName – The name of an Amazon EC2 SSH key pair for connecting with the worker nodes once they launch.
- BootstrapArguments – Leave empty. This field can be used to pass optional arguments to the worker nodes bootstrap script.
- VpcId – Enter the ID of the VPC you created in Step 2 above.
- Subnets – Select the three subnets you created in Step 2 above.
Proceed to the Review page, select the check-box at the bottom of the page acknowledging that the stack might create IAM resources, and click Create.
CloudFormation creates the worker nodes with the VPC settings we entered — three new EC2 instances are created.
As before, once the stack is created, open Outputs tab:
Note the value for NodeInstanceRole as you will need it for the next step — allowing the worker nodes to join our Kubernetes cluster.
To do this, first download the AWS authenticator configuration map:
curl -O /aws-auth-cm.yaml
Open the file and replace the rolearn with the ARN of the NodeInstanceRole created above:
apiVersion: v1 kind: ConfigMap metadata: name: aws-auth namespace: kube-system data: mapRoles: | - rolearn: <ARN of instance role> username: system:node:{{EC2PrivateDNSName}} groups: - system:bootstrappers - system:nodes
Save the file and apply the configuration:
kubectl apply -f aws-auth-cm.yaml
You should see the following output:
configmap/aws-auth created
Use kubectl to check on the status of your worker nodes:
kubectl get nodes --watch NAME STATUS ROLES AGE VERSION ip-192-168-245-194.ec2.internal Ready <none> <invalid> v1.11.5 ip-192-168-99-231.ec2.internal Ready <none> <invalid> v1.11.5 ip-192-168-140-20.ec2.internal Ready <none> <invalid> v1.11.5:
kubectl apply -f kubectl apply -f kubectl apply -f kubectl apply -f kubectl apply -f kubectl apply -f
Use kubectl to see a list of your services:
kubectl get svc guestbook LoadBalancer 10.100.17.29 aeeb4ae3132ac11e99a8d12b26742fff-1272962453.us-east-1.elb.amazonaws.com 3000:31747/TCP 7m kubernetes ClusterIP 10.100.0.1 <none> 443/TCP 1h redis-master ClusterIP 10.100.224.82 <none> 6379/TCP 8m redis-slave ClusterIP 10.100.150.193 <none> 6379/TCP 8m
Open your browser and point to the guestbook’s external IP at port 3000:
).
Published at DZone with permission of Daniel Berman , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/deploying-a-kubernetes-cluster-with-amazon-eks | CC-MAIN-2020-05 | refinedweb | 1,047 | 56.55 |
Form Handling with Gatsby.js V2 and Netlify
Updated on: April 16, 2019
Having a working contact form is a basic requirement for many websites, but setting one up with a static site can be tricky. If you're hosting your website with Netlify (which you should be), you can utilize their awesome form handling feature for free. Setting this up is super fast and easy, you'll never want to jump through hoops or embed an ugly form again.
For this example, I'll be using a static site made with Gatsby.js. You can do this with pretty much any static site generator, just make sure you're hosting with Netlify.
Gatsby Site with Forms ( view source )
Assuming you have Gatsby.js installed on your machine, let's start off by cloning a Gatsby starter I've previously made.
# Create a new Gatsby site with the Forty starter gatsby new gatsby-forms # Go into the new directory cd gatsby-forms/ # Start the dev site, browse to gatsby develop
Your new Gatsby site should be up and running, scroll down to the bottom of the page to see the contact form. Since Gatsby is built using React.js, this form area is just simple React component. Open up the file in your text editor of choice,
src/components/Contact.js
Here's the initial JSX for the form:
<form method="post" action="#"> <div className="field half first"> <label htmlFor="name">Name</label> <input type="text" name="name" id="name" /> </div> <div className="field half"> <label htmlFor="email">Email</label> <input type="text" name="email" id="email" /> </div> <div className="field"> <label htmlFor="message">Message</label> <textarea name="message" id="message" rows="6" /> </div> <ul className="actions"> <li> <input type="submit" value="Send Message" className="special" /> </li> <li> <input type="reset" value="Clear" /> </li> </ul> </form>
All we need to do is add a few new attributes to the
<form> tag:
<form name="contact" method="post" data- <input type="hidden" name="bot-field" /> <input type="hidden" name="form-name" value="contact" /> ... </form>
That's it! This is the most minimal way to get form submissions working. Netlify's bots will automatically detect the attribute
data-netlify="true" when you deploy, and process the form for you. The
data-netlify-honeypot="bot-field" is optional, but it's for anti-spam and easy enough to include. If a spam bot fills out the hidden
bot-field input, then the form won't be submitted.
Now just create a new GitHub repository with these files and deploy to Netlify.
Go to your new site and submit the form. You should get directed to a generic success page and we can look into changing this a bit later. Netlify will have a Forms area in their back-end where you can see the submissions. You can also head into
Settings > Forms > Form notifications and receive an email alert anytime a new submission comes through. Pretty awesome!
Caveat for Normal React Apps
It's worth noting that if you're building a normal React app with something like Create React App, there are a few extra steps you'll need to follow. Netlify has a blog post you can follow for these situations. Since we're using Gatsby to create this example, we get the benefit of a static snapshot and can skip these extra steps.
Adding a Custom Success Page
Adding your own success page is pretty straightforward, we'll first need to create a new page in our Gatsby site. Make a new file at
src/pages/success.js with the following:
import React from 'react' import Helmet from 'react-helmet' import Layout from '../components/layout' import pic11 from '../assets/images/pic11.jpg' const Success = props => ( <Layout> <Helmet> <title>Success Page</title> <meta name="description" content="Success Page" /> </Helmet> <div id="main" className="alt"> <section id="one"> <div className="inner"> <header className="major"> <h1>Success/Thank You Page</h1> </header> <span className="image main"> <img src={pic11} </span> <p>Thank you for contacting us!</p> </div> </section> </div> </Layout> ) export default Success
Browse over to and confirm your new page. Next we need to add an
action to our contact form. Open up
src/components/Contact.js and replace the
<form> tag with this:
<form name="contact" method="post" action="/success" data-
The
action="/success" will tell Netlify to use our new page instead of their generic success page. Commit these changes and wait for the new deploy, then fill out your form again. You should be re-directed to the new success page!
Netlify currently allows for 100 free form submissions per month, which is pretty generous and a good starting point for our purposes. | https://codebushi.com/form-handling-gatsby-netlify/ | CC-MAIN-2019-22 | refinedweb | 784 | 61.77 |
we also have a Chinese version of this blog.
From this article on, I will research the principle to combine HANA with R. After the SAP D-code meeting, I figured out that so many related applications are using R, especially the application about analysis and prediction. So I want to study the details deeply. These articles need the experience of R, and you had better have used R in SAP HANA. You can find related documents on, and you can also read my another document on
These documents will show the bi-directional data flows that SAP HANA communicates with R. Then you can design more efficient procedure on SAP HANA with R and it also can help you to figure out the reason for your problem. You can check out logs for R, and you can even integrate R with your own applications in TCP/IP if you can support TCP/IP.
(1) Embedded R’s execution environment
Because R can support an embedded execution environment, so SAP HANA can integrate with R. It means that if you have installed some specified libraries, you can add R programs into C programs.
Under R’s installation directory (such as /user/local/lib64/R), there are some head files providing some functions’ prototype and a dynamic-link library file- libR.so. It can run R program with C with these files’ support. For example
#include <stdio.h> #include "Rembedded.h" //header file #include "Rdefines.h" int main(){ char *argv[] = { "REmbeddedPostgres", "--gui=none", "--silent" //arguments }; int argc = sizeof(argv)/sizeof(argv[0]); Rf_initEmbeddedR(argc, argv); SEXP e; SEXP fun; SEXP arg; int i;; }
This code mainly defines some functions and macro in R language kernel. Firstly, initialize an embedded execution environment through calling Rf_initEmbeddedR(argc, argv). SEXP represent a kind of pointer which point some internal data structures. (refer to R’s source code with R-2.15.0/src/main), then it defines an array arg values from 1 to 10. Lastly, execute the function print() with eval(e, R_GlobalEnv).
We can compile these codes with command:
gcc embed.c -I/usr/local/lib64/R/include -L/usr/local/lib64/R/lib –lR
-l: the path of head files;
-L: the path of dynamic-link library;
-IR: with this parameter, it can link to libR.so
As we can see, the result is similar to R.
Because of this, based on embedded R execution environment, we can create an R server as a TCP/IP server. It can accept request from TCP/IP client, execute the R program and return the result to the client. This is the primary reason for developing Rserve
Above all is the basis of combination of SAP HANA and R.
(2) Introduction for Rserve
Rserve was born on 10.2003, the newest version is Rserve 1.7-3 which was published on 2013. The writer is Simon Urbanek() who is doing some research work on AT&T labs. We can download Rserve server and client from, and we can get more details about Rserver on this website.
Server is implemented with C. It can accept request and data from client, then it will return the results to client after calculation. The client provides C++, java and PHP version. Speak of this, the C++ interface only provides basic functionality, with author’s own words, “This C++ interface is experimental and does not come in form of a library”. It is just experimental which only some basis data structures, like lists, vectors, and doubles. For some other types, you need to design it by yourself. Just as “Look at the sources to see how to implement other types if necessary”
However, in SAP HANA’s R client, it is implemented by C++. But it is more complicated than the original C++ interface. Actually in theory, you can implement any kind of clients with any language if you get TCP/IP’s support.
(3) Message-oriented communication protocol:QAP1
QAP1(quad attributes protocol v1) is applied for Rserve to communicate with clients. According to QAP1, the clients should send a message first, which contains specific actions and some related data, then it will wait for the response message from server. The response message should contain the response code and the result data. As the structure of the response message, it contains a header portion whose size is 16 byte and data portion. The structure of header is as follows:
Offset type meaning
[0] (int) the type to request and response
[4] (int) set the length of message(0 to 31bit)
[8] (int) set the offset of data part
[12] (int) set the length of message(32 to 63 bit)
The data portion of the message may contain some additional parameters, such as DT_INT, DT_STRING or other types of parameters. Specific reference Rsrv.h .
Here are some commands which Rserve support,
The most commonly used command is CMD_EVAL. It can receive an R code. After syntax parsing, it can execute the code and get the result, then sends back the response message.
Actually, we can run embedded R program directly in SAP HANA, and it is more simple and efficient. But we cannot do this because of the copyright issues of open source software.
That’s it for now, I will introduce the operating mechanism Rserve and its communication with Rserve in the following blogs. If you know the principles of the detail, I think this will help you write better R procedure. | https://blogs.sap.com/2014/05/02/in-depth-understanding-the-principles-of-sap-hana-integrating-with-r/ | CC-MAIN-2017-51 | refinedweb | 914 | 63.8 |
< Main Index JBoss AS Tools News >
Seam code completion and validation now also supports the Seam 2 notion of import's.
import
This allow the wizard to correctly identify where the needed datasource and driver libraries need to go.
Hibernate support is now enabled by default on war, ejb and test projects generated by the Seam Web Project wizard.
This enables all the HQL code completion and validation inside Java files. Code completion just requires the Hibernate Console configuration to be opened/created, validation requires the Session Factory to be opened/created.
When the Seam Wizards (New Entity, Action, etc.) completes, it now (if necessary) automatically touch the right descriptors to get the new artifacts redeployed on the server.
EL code completion now support more of the enhancements to EL available in Seam, e.g. size, values, keySet and more are now available in code completion for collections and will not be flagged during validation.
size
values
keySet | http://docs.jboss.org/tools/whatsnew/seam/seam-news-1.0.0.cr1.html | CC-MAIN-2016-07 | refinedweb | 158 | 55.84 |
Internal Revenue Service
Instructions for Form 4972
Tax on Lump-Sum Distributions
From Qualified Retirement Plans
Section references are to the Internal Revenue Code.
Paperwork Reduction Purpose of Form If you received a qualifying
distribution as a beneficiary after the
Act Notice Use Form 4972 to choose the 20% participant's death, the participant
capital gain election and/or the 5- or must have reached age 591/2 before
We ask for the information on this 10-year tax option. These are special his or her death (or been born before
form to carry out the Internal Revenue formulas used to figure a separate tax 1936) for you to use this form for that
laws of the United States. You are on a qualified lump-sum distribution distribution.
required to give us the information. ONLY for the year in which the
We need it to ensure that you are Distributions to Alternate
distribution is received.
complying with these laws and to Payees.— If you are the spouse or
You pay the tax only once. You do former spouse of a plan participant
allow us to figure and collect the right not pay the tax over the next 5 or 10
amount of tax. who reached age 591/2 by the date of
years. Once you choose your option the distribution (or was born before
You are not required to provide the and figure the tax, it is then added to 1936) and you received a qualified
information requested on a form that the regular tax figured on your other lump-sum distribution as an alternate
is subject to the Paperwork Reduction income. The use of either option may payee under a qualified domestic
Act unless the form displays a valid result in a smaller tax than you would relations order, you can use Form
OMB control number. Books or pay by including the taxable amount 4972 to figure the tax on that income.
records relating to a form or its of the distribution as ordinary income
instructions must be retained as long If the distribution is a qualified
in figuring your regular tax.
as their contents may become distribution and the participant was
material in the administration of any born before 1936, you can use Form
Related Publications 4972 to make the 20% capital gain
Internal Revenue law. Generally, tax
returns and return information are Pub. 575, Pension and Annuity election and choose either the 5- or
confidential, as required by section Income (Including Simplified General 10-year tax option to figure your tax
6103. Rule) on the distribution.
The time needed to complete this Pub. 721, Tax Guide to U.S. Civil If the participant was born after
form will vary depending on individual Service Retirement Benefits 1935 but was at least age 591/2 when
circumstances. The estimated Pub. 939, Pension General Rule the distribution was made, you can
average time is: Recordkeeping, 33 (Nonsimplified Method) choose the 5-year tax option to figure
min.; Learning about the law or the the tax on a qualified distribution.
form, 26 min.; Preparing the form, Who Can Use Form 4972 See How To Report the
1 hr., 19 min.; Copying, assembling, You can use Form 4972 if you Distribution on page 2.
and sending the form to the IRS, received a qualified lump-sum
35 min.
Distributions That Do Not
distribution in 1996. To see if your
distribution is a qualified lump sum,
Qualify for the 20% Capital Gain
If you have comments concerning
the accuracy of these time estimates see What Is a Qualified Lump-Sum Election or for the 5- or 10-Year
or suggestions for making this form Distribution? below. Tax Option
simpler, we would be happy to hear The following distributions are not
from you. See the instructions for the What Is a Qualified qualified lump-sum distributions and
tax return with which this form is filed. Lump-Sum Distribution? do not qualify for the 20% capital
gain election or the 5- or 10-year tax
It is the distribution or payment in 1 option:
General Instructions tax year of a plan participant's entire
1. Any distribution that is partially
balance from all of the employer's
qualified plans of one kind (i.e., rolled over to another qualified plan,
Tax Law Change including an IRA.
pension, profit-sharing, or stock
The $5,000 exclusion for bonus plans), in which the participant 2. Any distribution if an earlier
employer-provided death benefits has had funds. The participant's entire election to use either the 5- or
been repealed for plan participants balance does not include deductible 10-year tax option had been made
dying after August 20, 1996. If you voluntary employee contributions or after 1986 for the same plan
received death benefits from an certain forfeited amounts. participant.
employer as a beneficiary of a In addition, the distribution must 3. U.S. Retirement Bonds
participant who died after August 20, have been made after the participant distributed with the lump sum.
1996, you cannot take any death reached age 591/2. 4. Any distribution made before the
benefit exclusion. participant had been in the plan for 5
tax years before the tax year of the
Cat. No. 13188F
distribution, unless it was paid If the plan participant was born after If you make an election as a
because the participant died. 1935 but the distribution was made beneficiary of a deceased participant,
5. The current actuarial value of on or after the date the participant it does not affect any election you can
any annuity contract included in the reached age 591/2, you can choose make for qualified lump-sum
lump sum (the payer's statement the 5-year tax option to figure your tax distributions from your own plan. You
should show this amount, which you on the lump-sum distribution. You can also make an election as the
use only to figure tax on the ordinary cannot use either the 10-year tax beneficiary of more than one
income part of the distribution). option or the 20% capital gain qualifying person.
6. Any distribution to a 5% owner election. Example. Your mother and father
that is subject to penalties under Where To Report.— Depending on died and each was born before 1936.
section 72(m)(5)(A). which parts of Form 4972 you choose Each had a qualified plan of which
7. A distribution from an IRA. to use, report amounts from your you are the beneficiary. You also
Form 1099-R either directly on your received a qualified lump-sum
8. A distribution from a
tax return (Form 1040 or Form 1041) distribution from your own plan and
tax-sheltered annuity (section 403(b)
or on Form 4972. you were born before 1936. You may
plan).
● If you choose not to use any part make an election for each of the
9. Redemption proceeds of bonds distributions; one for yourself, one as
of Form 4972, report the entire
rolled over tax free to a qualified your mother's beneficiary, and one as
amount from Form 1099-R, box 1
pension plan, etc., from a qualified your father's. It does not matter if the
(Gross distribution), on Form 1040,
bond purchase plan. distributions all occur in the same
line 16a and the taxable amount on
10. A distribution from a qualified line 16b (or on Form 1041, line 8). If year or in different years. File a
pension or annuity plan when the your pension or annuity is fully separate Form 4972 for each
participant or his or her surviving taxable, enter the amount from Form participant's distribution.
spouse received an eligible rollover 1099-R, box 2a (Taxable amount), on Note: An earlier election on Form
distribution from the same plan (or Form 1040, line 16b; do not make an 4972 or Form 5544 for a distribution
another plan of the employer required entry on line 16a. before 1987 does not prevent you
to be aggregated for the lump-sum ● If you choose not to use Part III of from making an election for a
distribution rules), and the proceeds distribution after 1986 for the same
Form 4972, but you do use Part II,
of the previous distribution were rolled plan participant, provided the
report only the ordinary income part
over tax free to an eligible retirement participant was under age 591/2 at the
of the distribution on Form 1040, lines
plan (including an IRA). time of the pre-1987 distribution.
16a and 16b (or on Form 1041, line
11. A corrective distribution of 8). The ordinary income part of the
excess deferrals, excess distribution is the amount shown in
When You Can Choose
contributions, or excess aggregate Form 1099-R, box 2a, minus the You can file Form 4972 with either an
contributions. amount shown in box 3 of that form. original or an amended return.
12. A lump-sum credit or payment ● If you choose to use Part III of Form Generally, you have 3 years from the
from the Federal Civil Service 4972, do not include any part of the later of the due date of your tax return
Retirement System (or the Federal distribution on Form 1040, lines 16a or the date you filed your return to
Employees Retirement System). and 16b (or on Form 1041, line 8). choose to use any part of Form 4972.
How To Report the Distribution The entries in other boxes on Form Capital Gain Election
1099-R may also apply in completing
If you qualify to use Form 4972, Form 4972: If the plan participant was born before
attach it to Form 1040 (individuals) 1936 and the distribution includes a
● Box 6, Net unrealized appreciation
or Form 1041 (estates or trusts). The capital gain, you can either (a) make
payer should have given you a Form in employer's securities. See Net the 20% capital gain election in Part
1099-R or other statement that shows Unrealized Appreciation (NUA) on II of Form 4972, or (b) treat the
the separate amounts to use in page 3 for details on how to treat this capital gain as ordinary income.
completing the form. The following amount.
Only the taxable amount of
● Box 8, Other, current actuarial
choices are available. distributions resulting from pre-1974
20% Capital Gain Election.— If the value of an annuity. participation qualifies for capital gain
plan participant was born before 1936 If applicable, get the amount of treatment. The capital gain amount
and there is an amount shown in Federal estate tax paid attributable to should be shown in Form 1099-R,
Form 1099-R, box 3, you can use the taxable part of the lump-sum box 3. If there is an amount from
Part II of Form 4972. You are electing distribution from the administrator of Form 1099-R, box 6 (net unrealized
to apply a 20% tax rate to the capital the deceased's estate. appreciation (NUA)), part of it may
gain portion. See Capital Gain also qualify for capital gain treatment.
Election on this page.
How Often You Can Choose
Use the NUA Worksheet on page 3
5- or 10-Year Tax Option.— If the After 1986, you may choose to use to figure the capital gain part of NUA
plan participant was born before Form 4972 only once for each plan if you make the election to include
1936, you can use Part III to choose participant. If you receive more than NUA in your taxable income.
the 5- or 10-year tax option to figure one lump-sum distribution for the You may elect to report the
your tax on the lump-sum distribution. same plan participant in 1 tax year, remaining balance of the distribution
You can choose either option whether you must treat all those distributions as ordinary income on Form 1040,
or not you make the 20% capital gain in the same way. Combine them on line 16b (or Form 1041, line 8), or you
election described earlier. a single Form 4972. may elect to figure the tax using the
5- or 10-year tax option. The
Page 2
remaining balance is the difference
between Form 1099-R, box 3, and NUA Worksheet (keep for your records)
Form 1099-R, box 2a. Complete only if you make the capital gain election.
Net Unrealized Appreciation
A. Enter the amount from Form 1099-R, box 3 A.
(NUA).— Normally, the NUA in
B. Enter the amount from Form 1099-R, box 2a B.
employer securities received as part
C. Divide line A by line B and enter the result as a decimal C.
of a lump-sum distribution is not
D. Enter the amount from Form 1099-R, box 6 D.
taxable until the securities are sold.
E. Multiply line C by line D (NUA subject to capital gain treatment) E.
However, you can elect to include
F. Subtract line E from line D (NUA that is ordinary income) F.
NUA in taxable income in the year
G. Add lines A and E (total part of distribution that can receive capital gain
received. treatment). Enter the total here and on Form 4972, line 6 G.
The total amount to report as NUA On the dotted line next to line 6, write “ NUA ” and the amount from
should be shown in Form 1099-R, line E above.
box 6. Part of the amount in box 6
will qualify for capital gain treatment Death Benefit Worksheet (keep for your records)
if there is an amount in Form 1099-R, Complete only if the participant died before August 21, 1996.
box 3, and you elect to include the
NUA in current income. A. Enter the capital gain amount from Form 1099-R, box 3. If you elected
To figure the total amount subject to include NUA in taxable income, enter the amount from line G of the
NUA Worksheet A.
to capital gain treatment including the
B. Enter the taxable amount from Form 1099-R, box 2a. If you elected to
NUA, complete the NUA Worksheet include NUA in taxable income, add the amount from Form 1099-R,
on this page. box 6, to the amount from Form 1099-R, box 2a, and enter the total
here B.
C. Divide line A by line B and enter the result as a decimal C.
Specific Instructions D. Enter your share of the death benefit exclusion* D.
E. Multiply line D by line C E.
Name of Recipient of Distribution
F. Subtract line E from line A. Enter the result here and on Form 4972,
and Identifying Number.— At the line 6 F.
top of Form 4972, fill in the name and
*If there are multiple recipients of the distribution, the $5,000 maximum death benefit exclusion must be
identifying number of the recipient of allocated among the recipients in the same proportion that they share the distribution.
the distribution.
If you received more than one income, see Net Unrealized 6. Divide the result by your
qualified distribution in 1996 for the Appreciation (NUA) on this page to percentage of distribution shown in
same plan participant, add them and determine the amount of NUA that box 9a. Enter the result on Form
figure the tax on the total amount. If qualifies for capital gain treatment. 4972, line 8.
you received qualified distributions in Step 2.— Use this step only if you 2. If you make the capital gain
1996 for more than one participant, do not elect to include NUA in your election, subtract the amount in box
file a separate Form 4972 for the taxable income or if you do not have 3 from the amount in box 2a. Add to
distributions of each participant. NUA. If you elect to include NUA in the result the amount from line F of
If you and your spouse are filing a taxable income, skip Step 2 and go your NUA Worksheet. Then divide the
joint return and each has received a to Step 3. (Box numbers used below total by your percentage of
lump-sum distribution, complete and are all from Form 1099-R.) distribution shown in box 9a. Enter
file a separate Form 4972 for each 1. If you do not make the capital the result on Form 4972, line 8.
spouse's election, combine the tax, gain election, divide the amount 3. Divide the amount shown in box
and include in the total on Form 1040, shown in box 2a by your percentage 8 by the percentage shown in box 8.
line 38. of distribution shown in box 9a. Enter Enter the result on Form 4972, line
If you are filing for a trust that this amount on Form 4972, line 8. 11.
shared the distribution only with other 2. If you make the capital gain Step 4.— Complete Form 4972
trusts, figure the tax on the total lump election, subtract the amount in box through line 36.
sum first. The trusts then share the 3 from the amount in box 2a. Divide Step 5.— Complete the following
tax in the same proportion that they the result by your percentage of worksheet to figure the entry for line
shared the distribution. distribution shown in box 9a. Enter 37:
Multiple Recipients of a Lump-Sum the result on Form 4972, line 8.
Distribution.— If you shared a lump- 3. Divide the amount shown in box
sum distribution from a qualified A. Compare lines 29 and 36 of
8 by the percentage shown in box 8. Form 4972. Enter the smaller
retirement plan when not all recipients Enter the result on Form 4972, line amount here.............................
were trusts (a percentage will be 11. B. Enter your percentage of
shown in Form 1099-R, boxes 8 distribution from Form 1099-R,
Step 3.— Use this step only if you box 9a ......................................
and/or 9a), figure your tax on Form elect to include NUA in your taxable C. Multiply line A by the
4972 as follows: income. percentage on line B. Enter the
Step 1.— Complete Form 4972, result here and on Form 4972,
1. If you do not make the capital line 37. Also, write “MRD” on
Parts I and II. If you make the 20% gain election, add the amount shown the dotted line next to the entry
capital gain election in Part II and also in box 2a to the amount shown in box space........................................
elect to include NUA in taxable
Page 3
Part II For details on how to do this, see distribution by any Federal estate tax
Pub. 575. paid on the lump-sum distribution.
See Capital Gain Election on page The reduction is made by entering on
If you made the 20% capital gain
2 before completing Part II. line 18 the Federal estate tax
election, enter only the ordinary
Line 6.— Leave this line blank if your income from Form 1099-R on this attributable to the lump-sum
distribution does not include a capital line. To figure this amount, subtract distribution. Also see the instructions
gain amount, or you do not make the Form 1099-R, box 3, from Form for line 6.
20% capital gain election. Go to Part 1099-R, box 2a. Enter the result on Line 20.— Decimals should be
III. line 8. Add to that result the amount carried to five places and rounded to
To make the 20% capital gain from line F of the NUA Worksheet if four places. Drop amounts 4 and
election but not take a death benefit you included NUA capital gain in the under (.44454 becomes .4445).
exclusion (see instructions for line 20% capital gain election. Round amounts 5 and over up to the
9), enter on line 6 the entire capital If you did not make the 20% next number (.44456 becomes
gain amount from Form 1099-R, box capital gain election and did not .4446).
3. However, if you elect to include elect to include NUA in taxable Lines 24 and 27.— Use the following
NUA in your taxable income, use the income, enter the amount from Form tax rate schedule to complete lines
NUA Worksheet on page 3 to figure 1099-R, box 2a. If you did not make 24 and 27.
the amount to enter. the 20% capital gain election but did
To make the 20% capital gain elect to include NUA in your taxable Tax Rate Schedule
election when you are taking a death income, add the amount from Form for the 5-Year Tax Option
benefit exclusion, use the Death 1099-R, box 2a, to the amount from Lines 24 and 27
Benefit Worksheet on page 3 to figure Form 1099-R, box 6. Enter the total
the amount to enter on line 6. on line 8. On the dotted line next to If the amount on Enter on line
The remaining allowable death line 8, write “NUA” and the amount line 23 or 26 is: 24 or 27:
benefit exclusion should be entered of NUA included. Of the
But not amount
on line 9, if you choose the 5- or Note: Community property laws do Over— over— over—
10-year tax option. not apply in figuring tax on the $–0– $24,000 - - - - - 15% $–0–
If any Federal estate tax was paid 24,000 58,150 $3,600.00 + 28% 24,000
amount you report on line 8. 58,150 121,300 13,162.00 + 31% 58,150
on the lump-sum distribution, you Line 9.— If you received the 121,300 263,750 32,738.50 + 36% 121,300
must decrease the capital gain 263,750 ----- 84,020.50 + 39.6% 263,750
distribution because of the plan
amount by the amount of estate tax participant's death, and the Lines 31 and 34.— Use the following
applicable to it. To figure the amount, participant died before August 21, tax rate schedule to complete lines
multiply the total Federal estate tax 1996, you may be able to exclude up 31 and 34.
paid on the lump-sum distribution by to $5,000 of the lump sum from your
the decimal from line C of the Death gross income. If there are multiple Tax Rate Schedule
Benefit Worksheet. The result is the recipients of the distribution not all of for the 10-Year Tax Option
portion of the Federal estate tax whom are trusts, enter on line 9 the Lines 31 and 34
applicable to the capital gain amount. full remaining allowable death benefit
Then use that result to reduce the exclusion (after the amount taken If the amount on Enter on line
amount in Form 1099-R, box 3, if you against the capital gain portion of the line 30 or 33 is: 31 or 34:
don't take the death benefit exclusion, distribution by all recipients—see the Of the
But not amount
or reduce line F of the Death Benefit instructions for line 6) without Over— over— over—
Worksheet if you do. Enter the allocation among the recipients. (The $–0– $1,190 ----- 11% $–0–
remaining capital gain on line 6. If you exclusion is in effect allocated among 1,190 2,270 $130.90 + 12% 1,190
elected to include NUA in taxable 2,270 4,530 260.50 + 14% 2,270
the recipients through the 4,530 6,690 576.90 + 15% 4,530
income, subtract the portion of computation described on page 3 6,690 9,170 900.90 + 16% 6,690
Federal estate tax applicable to the under Multiple Recipients of a 9,170 11,440 1,297.70 + 18% 9,170
11,440 13,710 1,706.30 + 20% 11,440
capital gain amount from the amount Lump-Sum Distribution.) This 13,710 17,160 2,160.30 + 23% 13,710
on line G of the NUA Worksheet. exclusion applies to the beneficiaries 17,160 22,880 2,953.80 + 26% 17,160
22,880 28,600 4,441.00 + 30% 22,880
Enter the result on line 6. Enter the or estates of common-law employees, 28,600 34,320 6,157.00 + 34% 28,600
remainder of the Federal estate tax self-employed individuals, and 34,320 42,300 8,101.80 + 38% 34,320
42,300 57,190 11,134.20 + 42% 42,300
on line 18. shareholder-employees who owned 57,190 85,790 17,388.00 + 48% 57,190
Note: If you take the death benefit more than 2% of the stock of an S 85,790 ----- 31,116.00 + 50% 85,790
exclusion and Federal estate tax was corporation. Pub. 575 gives more Line 37.— By entering the smaller of
paid on the capital gain amount, the information about the death benefit the amounts on lines 29 and 36, you
capital gain amount must be reduced exclusion. elect either the 5-year or the 10-year
by both the above procedures to Enter the death benefit exclusion tax option, whichever results in the
figure the correct entry for line 6. on line 9. But see the instructions for lower Federal tax. However, you may
line 6 if you made a capital gain wish to elect the option that results in
Part III election. the higher Federal tax if that would
Line 8.— If the payer of the Line 18.— A beneficiary who be advantageous for combined
distribution left box 2a (Taxable receives a lump-sum distribution Federal and state tax purposes. To
amount) of Form 1099-R blank, you because of a plan participant's death do this, write “Higher tax option
must first figure the taxable amount. must reduce the taxable part of the elected” on the dotted line to the left
of the line 37 entry space.
Page 4 | https://www.scribd.com/document/544624/US-Internal-Revenue-Service-i4972-1996 | CC-MAIN-2019-09 | refinedweb | 4,301 | 71.65 |
Phase 4 - Managing software licensing
After the data is reconciled and the production dataset is up to date, the Software License Management (SWLM) process is ready to manage software licenses. The process includes setting Software Contracts, Certificates, setting up and running license jobs, and managing compliance. The information about the products to be managed and the licensing purchased for each of them is available, as these were identified in the Planning phase.
Setting software contracts and certificates
Identify the key attributes required for the licensing models relevant to the products to be managed. This is necessary so that CIs and the related Certificates to match. The following table lists the attributes needed for the license models.
- Create Software License Contracts
A Software Contract represents a broad agreement with a software vendor. Each Software contract can have one or more child Software License Certificates.
Set up the Software License Contract(s) using the Contract Management console. Create a Software License Contract for each Supplier and Manufacturer. Verify if multiple contracts need to be created for the same manufacturer. This would be necessary if the supplier terms for the products by the same manufacturer are different .
For example, create Software License Contracts for the Microsoft Products and the Adobe products. At least the following information must be available to create the contract:
- Contract ID
- Summary
- Company
- Term
- Term Conditions
- Supplier
- Cost Center
- Contract Managed By
Expiration/ Notification date
Software license contract
Important.
Create License Certificates.
A License Certificate is a child record of a Software Contract, and is used to represent an entitlement owned by the organization, to use a certain amount of one or more specific software titles. A Software Contract consists of a License Certificate. The License Certificate represents ownership of the organization to use a specific software. You can attach one or more Software License Certificates to a Software Contract.
Set up the License Certificates for various products. On the Contract console, open the contract created for Microsoft. On the License Details tab, add a license certificate for each product. Typically, a certificate is setup for a product. If the software license purchased has downgrade rights, specify the new and the lower market version on the same certificate.
At least the following information must be available to create the certificate; other attributes can be filled as necessary.
It is assumed that Calbro has used different purchase orders for each of the following licenses:
Tab 1 — License Certificate Creation for Microsoft Project Standard Edition
Tab 2 — Addition of Product info on the Certificate (2010 and 2007 are both added on the certificate, as the certificate has downgrade rights to version 2007)
Tab 4 – Entering Compliance Details
Tab 3 - The Connection details tab and is displayed only if additional connection questions are configured for the license model.
- Create certificates for the other products. When creating the certificates ensure that:
- all the certificates are in Executed state so that they can be used by the SWLM engine.
the value of the Engine Connection field on the Certificate is set to Yes, so that the Software License Engine is able to connect to certificate.
By default, when the status of the certificate is set to Executed, the Engine Connection value is set to Yes.
- Since the Adobe licenses were purchased in multiple purchase orders, create a certificate for each purchase described in the table in step 3 of this procedure. Individual Software License records can be used to represent a history of multiple purchases of the same software, or purchases of the same software from different suppliers, even under separate Software Contract parent records.
When creating the certificate subsequent to the first certificate for a product, the system prompts you to group the certificates if they have the same Company, License Model, and Product Categorization. This is termed as Grouping of Certificates.
Calbro purchased additional Microsoft Project Standard Edition licenses in two separate purchases:
- Create the two new certificates for Project, and then group them with the original one.
While creating the certificates, on the second tab of the Certificate Creation dialog box, you are prompted to group the certificates.
Click Manage Grouping to group the new certificate with the existing one.
Then group the two new certificates for Microsoft Project in the above table.
Managing license jobs
Set up the license jobs for the manufacturers and products to be managed for SWLM.
Creating the license jobs
From the Software Asset Management (SAM) console, click the Manage License Job link to create the SWLM License Job. License Jobs should be created for the manufacturer or product.
Create a job for the Microsoft products. Since there are a large number of products for Microsoft in the CMDB, qualify the Job by Products to be managed as follows:
Running and monitoring license jobs
After creating the license jobs, on the Manage Jobs dialog box, select the Adobe Job and click Run to execute the job on on demand.
Monitor the completion of the job in the History tab in the bottom section of the dialog box.
Similarly, run the Microsoft Job on demand.
Running reconciliation based jobs
Recommendation
For optimum performance run the SWLM job based on Reconciliation Job after the first run. This can be done under the Schedules option on the Reconciliation tab.
Relate the SWLM job to the Reconciliation Job for both Adobe and Microsoft. This ensures that related SWLM jobs are run every time a Reconciliation job is run.
Each license job returns four results which can be viewed by selecting the job run in the Job History window.
- After running the license jobs, monitor the license compliance. Using the Software Asset Management (SAM) console, select and view each certificate for Microsoft and the one for Adobe products created earlier.
Important
To summarize, the license engine performs the following procedures:
- Checks the Product Catalog for any software titles that match the criteria set in the job details, and that have "Requires Contract" = Yes.
- Searches the CMDB for any instances of the software titles found in these software titles.
- Attempts to connect the software titles to certificates which match them
- Calculates the overall consumption on any certificates to which it has just connected software CIs.
Monitoring license compliance
Use the Software Asset Management (SAM) console to review the Compliance Status and the Rolled up Deployed count. Also open the appropriate certificates for the products from the SAM console to review the the Number Deployed per product which is reflected in the Related Product Categorization table.
Optionally, click the Compliance Details link on the navigation bar to view the compliance numbers.
Notice that the Adobe license certificate for version 9 is out of compliance. The Number deployed is 5 and the Number purchased is 2. Request the purchasing manager to procure additional licenses for Adobe version 9.
From the Purchasing Console create a Purchase Requisition (PR) with a line item for Adobe Acrobat version 9, to purchase 5 licenses.
- Enter the details in the Line Item Information for purchasing Adobe licenses.
On the License Certificate tab of the Purchase Line Item, update the Purchase Type, Software Contract ID, and License Type values. This information is used to create the license certificate automatically.
- The PR then goes through the purchasing lifecycle:
- After saving the Line Item and the PR, submit it for approval.
When the required approver(s), approve the PR, a Purchase Order (PO) is created
Submit the purchase order.
Based on the out of the box configuration settings in the Rules form, License certificates are automatically created once the order is submitted. As a result, the item does not need to be explicitly received.
The new certificate is now created for 5 additional licenses of Adobe. However, on creation the certificate is in the Draft status.
- Update the status of the certificate from Draft to Executed to enable the certificate.
Then group the new certificate with the original.
From the SAM console open the existing certificate and click the Manage Grouping link on the navigation bar to add the new certificate and the existing one into a group.
A master certificate is created, where the two certificates for Adobe Acrobat, version 9 are part of the Group. From the SAM console only the master certificate is seen because the master certificate is the container for the children certificates, and provides a rolled up view of the compliance for Adobe Acrobat, version 9.
Important
In case of grouped certificates, SWLM engine only connects to the Master Certificate.
- Rerun the License Job for Adobe.
After the license job is complete, review the compliance status of Adobe Acrobat, version 9. The certificate is now in compliance. The Number deployed is 5 and the Number purchased is 7.
Managing software usage
Notices that currently, though the Adobe Acrobat version 7 certificate is in compliance, it is approaching out of compliance status. Instead of buying new licenses, locate users who are not using the software, so they can uninstall the software from their systems and their licenses can be reused.
Some discovery vendors collect the usage information about the applications and store it in their database. Out of the box, Remedy Asset Management is integrated with the BMC BladeLogic Client Automation (BBCA) Software Usage.
Perform the following steps:
- Open the AST:ConfigUsageProvider form, where you can set up the provider for usage.
BCAC is the namespace for the BBCA discovery and BCAC_Software_Usage is the federated class.
Verify that the Namespace and the ClassName are setup with BBCA and BCAC_Software_Usage respectively for the usage information from BBCA.
Important
For any other discovery source create the appropriate integration using the CMBD federation. For more information, see Configuring your system to work with any third-party software usage provider.
On the SAM console, select the Adobe Acrobat 7 certificate and click View Usage to open the Software Usage form.
The Software Usage form provides usage details of all Adobe 7 product instances, the computers where the software is installed, and the related users.
Analyze the data using various predefined queries available from the navigation bar.
- Select the By Usage > Not used past 180 days predefined query.
Users x and y have not used the product in last 180 days.
- Submits a ticket to uninstall the software from these desktops.
Re-running the job then shows two extra licenses. This procedure allowed harvesting of the two licenses. | https://docs.bmc.com/docs/asset91/phase-4-managing-software-licensing-609066994.html | CC-MAIN-2021-17 | refinedweb | 1,726 | 53.61 |
QSysInfo::machineUniqueId() empty on Windows
Hi
Since Qt 5.11 there is function QSysInfo::machineUniqueId() which should return unique ID per machine (eg. processor number, mainboard number), on Linux it works, on Windows 10 it returns empty string (tested on Win 10 and Qt 5.11.1).
Is this as it should be ? Can't get this machineUniqueId on Windows, or is this some bug?
Best Regards
Marek
@Marek
I suspect this is because from docs:
QByteArray QSysInfo::machineUniqueId()
See also machineHostName() and bootUniqueId().
and
QByteArray QSysInfo::bootUniqueId()
This function is currently only implemented for Linux and Apple operating systems.
See also machineUniqueId().
EDIT: Hmm, maybe not. From I see:
#elif defined(Q_OS_WIN) && !defined(Q_OS_WINRT) // Let's poke at the registry HKEY key = NULL; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Cryptography", 0, KEY_READ, &key) == ERROR_SUCCESS) { wchar_t buffer[UuidStringLen + 1]; DWORD size = sizeof(buffer); bool ok = (RegQueryValueEx(key, L"MachineGuid", NULL, NULL, (LPBYTE)buffer, &size) == ERROR_SUCCESS); RegCloseKey(key); if (ok) return QStringView(buffer, (size - 1) / 2).toLatin1(); } #endif return QByteArray();
So, assuming not
Q_OS_WINRT(whatever that is for), do you have that registry value defined, and readable to your app?
@JonB I will try this now, but since RegOpenKeyEx is from Win api not Qt which lib should I link to and include headers?
Thanks,
Marek
@Marek
Not sure what you mean, but I did not mean compile anything! I meant: look at that code, and go look in your registry to see whether you even have that entry sitting there or not, because that is the code Qt will be executing for you. I can see that key value under my Win 8 (so I would expect the Qt call to work), maybe it isn't there on your machine in Win 10, or (unlikely?) your Qt app process has no permission to read it from the registry?
@JonB I have compiled this into app and it returns empty string, I think because I can see Q_OS_WINRT is set
This windows is a bit slow...
@Marek:
Defined for Windows Runtime (Windows Store apps) on Windows 8, Windows RT, and Windows Phone 8.
Is your Qt compiled for Win 10 "Windows Store app" ??
- Recheck your claim "I think because I can see Q_OS_WINRT is set", because that doesn't sound likely to me?
- Look in your registry to see what you have for the key entry referenced in the code?
@JonB REGEDIT inside Win ? Sorry I don't work usally on Windows. I have downloaded some regmagik and I can see that Microsoft\Cryptography hasn't any keys only some branches.
@Marek
Yeah, everybody knows that Windows comes with
REGEDITfor examining the Registry! :)
If you don't have
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\MachineGuid(I do), that function is not going to return anything on your machine. That's all I know.
@JonB anyway thanks for help, I really have Q_OS_WINRT set thats why this code returned empty string first time I have compiled
@Marek
Well actually that sounds more reasonable as an explanation, because I think the registry entry really is there under all Windows.
Now your question becomes: "why does the Qt I am using seem to have been compiled with
Q_OS_WINRTdefined, because I would have thought it should not?".
I am not a Qt expert: you would need someone like @SGaist to see this, look through my understanding of what must be going on, and explain.
@JonB does this matter if on my win 10 there is o MachineGuid key ?
I'm checking something, I'm using MinGW 32 bit, try to compile with msvc2017 64bit
@JonB OK, success, Thanks for your help ;)
so windows can provide "virtual" registry for 32 bit applications and this registry does not have MachineGuid. I have compiled with msvc2017 64Bit and it works. I can call it a day ;)
Best,
Marek
@Marek
Yes it can. It's all to do with the
Wow6432Nodekey:
Yes, for 32-bit software 64-bit OS will substitute
HKLM\SOFTWARE\path with
HKLM\SOFTWARE\Wow6432Node\. So you were trying to read
HKLM\SOFTWARE\Wow6432Node\Microsoft\Cryptography\MachineGuidwhich doesn't exist.
You did not say in your question that any 32-bitted-ness was involved at your side, I assumed all 64-bit, else I would have said about needing to change where you look in the registry :)
- CoreyAnderson Banned
This post is deleted!
@JonB I did not supposed it matters, frankly I prefer to use MinGW (old habits maybe) and I didn't see Qt 5.11 for MinGW 64bit.
@CoreyAnderson how this HP printer support is related to Qt or even Windows 10, I don't get it, you mean bug in Windows that it does not provide key for 32bit apps ?
Ignore @CoreyAnderson 's post, he is just advertising his hyperlink! It's a scam.
You can use a 64-bit compiler with no issue. If you want to use a 32-bit compiler, you will have to do some work.
@Marek
I don't know what to say other than you have the choice of what compiler and bitted-ness are used to compile Qt, and you decide which target platforms you wish to support. In this case you have found a situation where there is a 32-bit/64-bit Windows Registry issue if you mix bitted-nesses.
- JKSH Moderators
I sense a bit of miscommunication in the last few messages; @Marek and @JonB are talking about slightly different things.
@Marek's observation is correct: The Maintenance Tool does not provide a pre-built 64-bit version of Qt for MinGW.
@JonB's point is also correct: We can choose from a variety of 32-bit and 64-bit versions. (But if we want 64-bit MinGW, then we need to build Qt ourselves -- we can't just download it through the MaintenanceTool)
@JKSH
Ah, I don't even know what that "Maintenance Tool" is! I actually thought it might be for building Qt yourself, now I understand it gives pre-compiled versions. And you're saying it does not offer 64-bit for MinGW.
@Marek
You still have two choices for your issue:
If you use a 64-bit Qt there is no problem. That could be pre-compiled or compiled by you, and it could be MinGW, MSVC or whatever. I do not know whether you find using either a pre-supplied MSVC 64-bit (does Maint Tool have that?) or compiling for yourself a 64-bit MinGW acceptable or a pain in the ass.
If you use a 32-bit Qt --- perhaps the conveniently pre-compiled MinGW one --- there is a problem, because of where that looks in the Registry. You can probably address this by doing something in your app code, but we haven't investigated this yet as you haven't said which Qt 32/64-bit route you wish to pursue.
@JonB Thanks for your help.
MSVC 64Bit is provided by Maintenance Tool.
Compiling Qt on Windows with 64-Bit MinGW might be a pain ;) I'm doing this quite often on embedded platforms but then I need much less modules. What is more, I'm writing code that someone else will use in his projects, so it needs to be compatible with commercial Qt license.
I will stick to MSVC 64Bit.
Thanks,
Marek
@Marek
So it sounds like you will use 64-bit, this problem will go away and we don't need to investigate any further.
I presume all your targets will be 64-bit, none 32-bit(?).
Now that we know how
QSysInfo::machineUniqueId()relies on finding that
"MachineGuid"in the correct place in the Registry where it looks, and there's some possibility it may not find it, you might be best documenting this somewhere for both developers & end-users, and/or providing a "fallback" mechanism if it returns an empty string.
@JonB I'm reading mac addresses of network cards when machineUniqueId returns empty string. This can be problematic especially when someone uses detachable usb->wifi adapter but I don't see other option with Qt.
@Marek
Well Qt is only a library providing "abstracted, convenience" functions where possible, it's not magic, so yes sometimes you have to supply your own alternatives as best you can. If you can't find anything, chances are nor can Qt. | https://forum.qt.io/topic/91882/qsysinfo-machineuniqueid-empty-on-windows | CC-MAIN-2019-30 | refinedweb | 1,385 | 70.13 |
ave,
I've placed betas up online at:
If you could give that a go and let me know if the problem arises,
that'd be great.
Thanks!
steven
On Mon, Dec 17, 2012 at 9:30 PM, Dave Seidel <dave.seidel@...> wrote:
> Will do, Steven, thanks.
>
>
> On Mon, Dec 17, 2012 at 4:21 PM, Steven Yi <stevenyi@...> wrote:
>>
>> Hi Dave,
>>
>> I think I may have a fix. I'll place a beta zip up online tomorrow. If you
>> could test and help verify that'd be great.
>>
>> Thanks!
>> Steven
>>
>> On Dec 17, 2012 6:15 PM, "Dave Seidel" <dave.seidel@...> wrote:
>>>
>>> Thanks, Steven!
>>>
>>>
>>> On Mon, Dec 17, 2012 at 1:11 PM, Steven Yi <stevenyi@...> wrote:
>>>>
>>>> Hi Dave,
>>>>
>>>> Thanks for filing that bug. I'm going to take a look at this tonight
>>>> and fix one other but that was reported and will plan to do another
>>>> bugfix release (tomorrow if tonight goes well).
>>>>
>>>> As for the PythonProcessor, yes it operates like the python objects in
>>>> that the interpreter is maintained between runs. It's a feature of
>>>> blue really. I myself code my projects much in the same way you
>>>> described and in presentations have likened it to modern score
>>>> notation (composer defines new symbols in the preface of a score, then
>>>> uses them in the score). There shouldn't be any problems to define in
>>>> a python object then just call it in the noteProcessor.
>>>>
>>>> Thanks!
>>>> steven
>>>>
>>>> On Sun, Dec 16, 2012 at 6:14 PM, Dave Seidel <dave.seidel@...>
>>>> wrote:
>>>> > I started with standard Ubuntu, but then switched to Xubuntu pretty
>>>> > quickly
>>>> > -- din't really like the Unity desktop, and xfce is just fine with me.
>>>> > Finally bit the bullet with Jack last night (ditched pulseeaudio), and
>>>> > as of
>>>> > a little while ago, even got it going in realtime mode. So I'm pretty
>>>> > happy
>>>> > with the environment at this point. It helps that I started playing
>>>> > with Red
>>>> > Hat in 2000, used Fedora and CentOS full-time at my last job, and
>>>> > continue
>>>> > to deploy to CentOS in my current job, so I didn't have to go
>>>> > cold-turkey in
>>>> > a completely unfamiliar OS.
>>>> >
>>>> > I hadn't considered using a PythonProcessor with PianoRoll; in fact
>>>> > I've
>>>> > never used PythonProcessor. I guess I don't tend to use note
>>>> > processors very
>>>> > much. I've found that I tend to forget about them after they're set
>>>> > because
>>>> > there's no visual indication of their presence except in the
>>>> > SoundObject
>>>> > Properties dialog, which I don't usually have visible. So yeah, I like
>>>> > to
>>>> > idea of pulling the NoteProcessors up into a less hidden part of the
>>>> > UI. I
>>>> > don't have any specific ideas on how that might work, but if I come up
>>>> > with
>>>> > some I'll certainly share them.
>>>> >
>>>> > Anyway, using a PythonProcessor makes perfect sense in with a
>>>> > PianoRoll, it
>>>> > just had never occurred to me. Thanks for the info and the sample
>>>> > code! I
>>>> > still like the idea of being able to access the pfields as named
>>>> > tokens as
>>>> > in BSB code (e.g.: <p1>), but it's probably not worth the development
>>>> > effort
>>>> > since PythonProcessor should work really well. Can I assume the the
>>>> > code in
>>>> > the processors will execute in the same instance/namespace as
>>>> > PythonObjects
>>>> > on the timeline? I rely on this when I define constants and functions
>>>> > on one
>>>> > PythonObject which I then reference in other PythonObjects.
>>>> >
>>>> > Thanks for the tip on switching between projects as a workaround
>>>> > instead on
>>>> > closing/reopening the project. I'll see if that helps the next time I
>>>> > experience the issue (assuming it isn't magically fixed in 2.3.2). And
>>>> > I
>>>> > will write up a bug for it. It's not just the buttons (mute, solo,
>>>> > ...) --
>>>> > when the project gets into this state, it blocks other functionality
>>>> > in the
>>>> > label/control areas of the layers. For example, right-click menu is
>>>> > gone,
>>>> > and so is the ability to double-click to name the layer.
>>>> >
>>>> > - Dave
>>>> >
>>>> >
>>>> >
>>>> > On Sun, Dec 16, 2012 at 12:23 PM, Steven Yi <stevenyi@...>
>>>> > wrote:
>>>> >>
>>>> >> Hi Dave!
>>>> >>
>>>> >> Glad you like the new editor, and glad you're enjoying Ubuntu as
>>>> >> well!
>>>> >> I've been meaning to make my Macbook dualboot to Xubuntu some time
>>>> >> but haven't gotten around to setting that up. I'm using Xubuntu now
>>>> >> in
>>>> >> a VM for testing.
>>>> >>
>>>> >> For the mute/solo problems, I have had this happen in 2.3.0 but I
>>>> >> thought I had fixed it in 2.3.1 with offloading onLoad of python
>>>> >> scripts to a separate thread. It looks like this wasn't the root
>>>> >> cause of the problem. My trouble with this is that the bug has been
>>>> >> intermittent and very difficult to consistently reproduce. I've
>>>> >> found
>>>> >> that I didn't have to close the project, but could just switch to
>>>> >> another one and come back for it to sort itself out. I'll see if I
>>>> >> can do some more bug hunting on this one; if you would file a bug
>>>> >> though, that would help me out very much.
>>>> >>
>>>> >> For the PianoRoll, have you considered using a Python NoteProcessor?
>>>> >> You should be able to use that to transform the generated notes from
>>>> >> the PianoRoll and essentially use it just as input data to your
>>>> >> functions. (I've attached an example that uses the PianoRoll as a
>>>> >> source of pitch data and then generates random notes.)
>>>> >>
>>>> >> Using the Python NoteProcessor code editor can be a bit of a pain to
>>>> >> keep going into the editor and back out to test. I had been meaning
>>>> >> to modify NoteProcessors for some time to no longer use the property
>>>> >> editor but instead have their own user interfaces and make a
>>>> >> rack-like
>>>> >> interface for them. Perhaps this would be something worth planning
>>>> >> out for a new release. Even then, I'm not sure what the code editor
>>>> >> part should look like. Would love to hear ideas at this point. :)
>>>> >> (Also, I had planned to make NoteProcessors have something like
>>>> >> BlueSynthBuilder, but where users can design their own processors,
>>>> >> does this sound of interest to anyone?)
>>>> >>
>>>> >> Let me know what you think, and thanks as always for your music!
>>>> >>
>>>> >> steven
>>>> >>
>>>> >> p.s. - I hope you don't mind, I modified Palimpsest to fix a code
>>>> >> issue with newer Csounds and the # not being allowed for comments (it
>>>> >> was in the global score with the tempo statement).
>>>> >>
>>>> >>
>>>> >> On Sat, Dec 15, 2012 at 9:18 PM, Dave Seidel <dave.seidel@...>
>>>> >> wrote:
>>>> >> > Hi Steven,
>>>> >> >
>>>> >> > I've been using blue on Ubuntu for a couple of months now (Windows
>>>> >> > laptop
>>>> >> > died, a good excuse to switch). I'm using Quantal Quetzal (12.10).
>>>> >> >
>>>> >> > It's generally working really well. I *really* like the new editor!
>>>> >> > It's
>>>> >> > a
>>>> >> > great improvement.
>>>> >> >
>>>> >> > An issue: I've had a number of times when I change the settings of
>>>> >> > solo/mute
>>>> >> > buttons in the timeline layers and they won't "take": i.e., no
>>>> >> > change to
>>>> >> > the
>>>> >> > CSD output generated either to screen or disk. When that happens, I
>>>> >> > have
>>>> >> > to
>>>> >> > close and reopen the project, then it's fine for a while. I don't
>>>> >> > have a
>>>> >> > particular set of actions that provokes it. It's happened in more
>>>> >> > than
>>>> >> > one
>>>> >> > project.
>>>> >> >
>>>> >> > And a feature request: I would love to be have a version of the
>>>> >> > PianoRoll
>>>> >> > that generates a line of Python code instead of a line of orchestra
>>>> >> > code
>>>> >> > (using the same templating you already have). The Python code would
>>>> >> > then
>>>> >> > be
>>>> >> > rendered just like a PythonObject. My process these days almost
>>>> >> > invariably
>>>> >> > involves writing a series of Python functions in one PythonObject
>>>> >> > that
>>>> >> > are
>>>> >> > called by other PythonObjects to generate orchestra code. It would
>>>> >> > be
>>>> >> > fantastic to be able to call those functions from with a PianoRoll.
>>>> >> >
>>>> >> > As always, thanks for all of your work and dedication.
>>>> >> >
>>>> >> > - | https://sourceforge.net/p/bluemusic/mailman/message/30246323/ | CC-MAIN-2017-13 | refinedweb | 1,309 | 72.16 |
To borrow a line, SOAP celebrates diversity. This document describes the integration between a popular scripting platform and a Java based implementation of SOAP, both in what is possible today and what could be done to improve the user's experience in the future.
Calling a
Radio
service using JAX
RPC and
Axis
import javax.xml.rpc.Call; import javax.xml.rpc.ParameterMode; import javax.xml.rpc.namespace.QName; import org.apache.axis.client.Service; import org.apache.axis.encoding.XMLType; import org.apache.axis.transport.http.HTTPConstants;</xmp><xmp>public class HelloDave { public static void main(String args[]) throws Exception { Call call = (new Service()).createCall(); call.setTargetEndpointAddress(new java.net.URL((""))); call.setOperationName(new QName("", "helloWorld") ); call.addParameter("Name", XMLType.XSD_STRING, ParameterMode.PARAM_MODE_IN); call.setProperty(HTTPConstants.MC_HTTP_SOAPACTION, "/radio"); System.out.println(call.invoke(new Object[] {"Dave from Axis"})); } }</xmp>
Calling a
Axis service
using
soap.rpc.client
on getQuote (name) {</xmp><xmp> local (quote, params={"symbol": name});</xmp><xmp> quote = soap.rpc.client ( actionURI: "/axis/servlet/AxisServlet", methodName: "getQuote", adrParams: @params, rpcServer: "nagoya.apache.org", rpcPort: 5049, username: "user1", password: "pass1", methodNamespace: "xdq", methodNamespaceURI: "urn:xmltoday-delayed-quotes" );</xmp><xmp> return ("Stock quote for " + name + " is " + quote)</xmp><xmp>}</xmp>
You can see the results here: [Macro error: Poorly formed XML text, string constant is improperly formatted. (At character #421.)]
Taking stock of where we are
OK, that proves it can be done. Now should look to make things simpler. Particularly for the script developer.
Take a closer look at these examples. They are dominated by administrivia - soap action, namespaces, uri's, parameter names, etc. Wouldn't it be nice if all of this could be removed from sight? If you are a Radio script developer today, you already know can create a macro for your use by putting a few lines in a Macros folder. Move that same file to a WebServices folder and you have exposed a web service. That's great for serving, but what if you wanted to consume? Wouldn't it be nice if there was a standard XML based format which contains all of this information that you can simply drop into a folder which would define all of this stuff for you?
Well there is such a format. I won't lie to you and tell you that it is sleek, elegant, or perfect. But it does have a few things going for it. It exists. It is fairly widely adopted. It is extensible. And it gets the job done.Gentle introduction to WSDL
Procedures are called operations. Operations have an input message and and output message. A port is a collection of operations, and is described in two parts. The abstract part is called the portType. The concrete association to a protocol is called a binding. That's enough to get started!
Now lets see how all of this works in practice, starting with the Apache Axis base interop WSDL. At the present point in time, we are only really interested in four pieces of data from this file. The soap:address contains the rpcServer, rpcPort, and actionURI in the traditional URL syntax. You will also see a port and a binding. These will be used in a minute. Finally there is an import statement. That's where the rest of the WSDL can be found. The reason this is structured this way is that we have dozens of vendors implementing the same set of operations, where the only difference is where you can find the endpoint and what bindings are supported.
Next lets look at the binding in the imported WSDL. While there is no limit to the number of different protocols you could support, at the moment let's simply ensure that there is one present which specifies RPC style SOAP over HTTP. The way this is encoded in WSDL is with the following attributes: style="rpc" and transport="". Since the binding is for SOAP over HTTP, you can also find the soapAction for each operation in the binding.
Finally, lets look at the portType itself. It contains a list of operations which contain a list of messages. These messages contain various parts which each describe the name and type of each operand. For now, don't worry about type, that's the subject of another essay.
That's pretty much it. You may notice the WSDL contains other information. For example, it specifies that the 2001 schema is what is expected. Simple rule: support as much as you can, ignore the rest, and hope for the best. Just remember, the worst thing that can happen is that your request will fail. In this case, Radio sends the 1999 version of the schema, but at least in the Apache implementations, this is accepted.
How this hypothetically would
work
Drag or SaveAs this WSDL to a folder. Give the file a name, say AxisInterop.wsdl. Then enter the following:
What could be simpler? OK, so this example may not be all that exciting. But you might find more exciting services here.What could be simpler? OK, so this example may not be all that exciting. But you might find more exciting services here.
<% AxisInterop.echoString("Hi Sam!") %>
Interoperability between diverse platforms isn't a distant future thought, it is a reality today. But as SOAPBuilders, we shouldn't stop here. Instead, we should work together and continuously strive to make things ever more simpler. While WSDL is certainly far from perfect and has many other potential usages, this essay focused on one way in which it could be applied to make life easier for the script developer. | http://www.intertwingly.net/stories/2002/02/08/axisradioInteropActualAndPotential.xhtml | crawl-003 | refinedweb | 937 | 59.5 |
Please can i be able to convert my simple program which is executing in cmd interface to simple graphical user interface program.
2 Replies - 800 Views - Last Post: 29 November 2009 - 10:22 AM
#1
Jframe
Posted 29 November 2009 - 12:28 AM
Replies To: Jframe
#2
Re: Jframe
Posted 29 November 2009 - 12:44 AM
Well sure. You just have to import the javax.swing package into your project. From there, you create your class to then extend "JFrame".
You can then run this from the command line as usual.... javac MySwingClass.java
import javax.swing.*; // Import javax.swing public class MySwingClass extends JFrame { public MySwingClass() { // Code here which puts GUI elements on the JFrame } public static void main(String args[]) { // Create an instance of our class which is of type JFrame MySwingClass myprogram = new MySwingClass(); // Set the size, title, how to close and finally show it. myprogram.setSize(300,300); myprogram.setTitle("My JFrame Project"); myprogram.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myprogram.setVisible(true); } }
You can then run this from the command line as usual.... javac MySwingClass.java
#3
Re: Jframe
Posted 29 November 2009 - 10:22 AM
Yes, there are several Swing tutorials in the Java tutorials section. Swing allows for an awesome GUI. (Graphical User Interface)
-- Cheers!
-- Cheers!
Page 1 of 1 | http://www.dreamincode.net/forums/topic/142116-jframe/ | CC-MAIN-2016-07 | refinedweb | 214 | 65.83 |
do you think I should have a go at it anyway?
Do you know why you're using that library to access EEPROM at all?
I can only store the values of 26 letters in the way shown and if I make the array bigger then that, things crash.
I need persistent storage of an int array
The question is why do you need to store the data in EEPROM, instead of, say an SD card?
You have 2048 bytes of RAM.I'm confused as to why you can't store 26 letters in that space.
It would be a good idea for you to describe the data you're trying to persist more clearly.Is it all predefined and constant, or will it be modified at runtime? How much data is there? What is the structure? How is it accessed? How will it be modified?
I guess the gotcha to this whole thing is that the data needs to be modified during run time. The main body of code "guesses" what letter the user is trying to type and assigns it. It needs to interpret the chord, make the "educational guess" and the assign the chord with in at least a 50ms time window to be responsive (as far as I understand, might be more or less wiggle room)
I have no idea how you're doing that - are you using some sort of lookup table, or something?Assume I have no idea what your sketch does - what's the structure of your data, how is it accessed and which parts of it are modified at runtime?
So it sounds like you have a 'letter' identifying the chord which is assigned by choosing the first unassigned letter when the chord is first encountered, and a 'chordValue' which somehow specifies the chord. What data type is 'chordValue'?
char checkAlt(int chordValue, int modifier)//untested{ int startAddress; int endAddress; if (modifier==96) //lower case letters { startAddress=1; endAddress=27; } if (modifier==38) //Capital letters { startAddress=27; endAddress=53; } //add more modifier definitions here, for symbols for(int i=startAddress;i>endAddress;i++) { int address=i*2-1; //this should assure a unique address for an int, given values are correct //probably could have incremented by 2, but the same vars would still need definitions int tempChord=EEPROM.readInt(address); if(tempChord==chordValue) { lastLetter=char(i+modifier); return lastLetter; } }}
If you are running out of RAM, there are techniques, such as putting string literals into PROGMEM. That can save quite a bit.
Serial.print ("Debugging point foo");
Serial.print (F("Debugging point foo"));
Code: [Select]Serial.print (F("Debugging point foo"));
#include <avr/pgmspace.h>
I'm assume this is necessary also right?
will I be able to modify the library in the same way?
Please enter a valid email to subscribe
We need to confirm your email address.
To complete the subscription, please click the link in the
Thank you for subscribing!
Arduino
via Egeo 16
Torino, 10131
Italy | http://forum.arduino.cc/index.php?topic=145477.msg1094399 | CC-MAIN-2015-06 | refinedweb | 499 | 63.9 |
Using Scheme from R via Guile and Rcpp
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Introduction
GNU Guile is a programming language “designed to help programmers create flexible applications that can be extended by users or other programmers with plug-ins, modules, or scripts”. It is an extension language platform, and contains an efficient compiler and virtual machine allowing both out of the box use for programs in Scheme, as well as integration with C and C++ programs.
Matías Guzmán Naranjo posed an almost-complete question on StackOverflow about how to combine Guile with R via Rcpp. It turns out that the code by Matías came from this gist showing both a Guile Scheme script, and a C use case example.
The Guile Scheme Script
script.scm
This file is posted in this gist.
(define simple-func (lambda () (display "Script called, now I can change this") (newline))) (define quick-test (lambda () (display "Adding another function, can modify without recompilation") (newline) (adding-without-recompilation))) (define adding-without-recompilation (lambda () (display "Called this, without recompiling the C code") (newline)))
The C wrapper
testguile.c
This file is also posted in this gist. We used (as
shown below) simpler link instructions which (on Ubuntu) can be ontained via
guile-config link and
are just
-lguile-3.0 -lgc on our Ubuntu 20.04 machine.
/* * Compile using: * gcc testguile.c \ * -I/usr/local/Cellar/guile/1.8.8/include \ * -D_THREAD_SAFE -L/usr/local/Cellar/guile/1.8.8/lib -lguile -lltdl -lgmp -lm -lltdl -o testguile */ #include
#include int main(int argc, char** argv) { SCM func, func2; scm_init_guile(); scm_c_primitive_load("script.scm"); func = scm_variable_ref(scm_c_lookup("simple-func")); func2 = scm_variable_ref(scm_c_lookup("quick-test")); scm_call_0(func); scm_call_0(func2); return 0; }
The Rcpp Caller
This is an edited and updated version of Matías’ initial file.
#include
#include #include using namespace Rcpp; // [[Rcpp::export]] int test_guile(std::string file) { SCM func, func2; scm_init_guile(); scm_c_primitive_load(file.c_str()); func = scm_variable_ref(scm_c_lookup("simple-func")); func2 = scm_variable_ref(scm_c_lookup("quick-test")); scm_call_0(func); scm_call_0(func2); return 0; }
The System Integration
On our Ubuntu 20.04 box, Guile 3.0 is well supported and is easy installable. Header files are in a
public location, as are the library files. The configuration helper
guile-config (also
guile-config-3.0 to permit continued use of 2.2 and 2.0) provides the required compiler and linker
flags which we simply hardwired into
src/Makevars. A proper package would need to discover these
from a script, typically
configure, or
Makefile invocations. We leave this for another time; if
anybody reading this is interested in taking this further please get in touch.
PKG_CXXFLAGS = -I"/usr/include/guile/3.0" PKG_LIBS = -lguile-3.0 -lgc
Package
The rest of package was created via one call
Rcpp.package.skeleton("RcppGuile") after which we
- simply copied in the C++ file above into
src/guile.cpp;
- added the
src/Makevarssnippet above; and
- copied in the example Scheme scripts as
inst/guile/script.scm
and that’s it! Then any of the usual steps with R will build and install a working package.
The complete package is available in this directory.
Guile Demo
The package can be used as follows, retrieving the Scheme script from within the package and clearly running it:
> library(RcppGuile) > test_guile(system.file("guile", "script.scm", package="RcppGuile")) Script called, now I can change this Adding another function, can modify without recompilation Called this, without recompiling the C code [1] 0 >
GNU Guile is made for building extensions. This short note showed how easy it is to connect R with Guile via a simple Rcpp. | https://www.r-bloggers.com/2020/12/using-scheme-from-r-via-guile-and-rcpp/ | CC-MAIN-2021-10 | refinedweb | 610 | 57.16 |
Add components for zip packing. This is the changes to add packing feature in zip unpacker. Design doc (now writing) can be found in the following link. BUG=359837 TEST=manually tested(test components will be added later.) Change-Id: Ia0ad78050a58053aa09e268f25ac6f064cbb9aac
This is the ZIP Unpacker extension used in Chrome OS to support reading and unpacking of zip archives.
Since the code is built with NaCl, you'll need its toolchain.
$ cd third-party $ make nacl_sdk
We'll use libraries from webports.
$ cd third-party $ make depot_tools $ make webports
First install npm using your normal packaging system. On Debian, you'll want something like:
$ sudo apt-get install npm
Then install the npm modules that we require. Do this in the root of the unpacker repo.
$ npm install bower 'vulcanize@<0.8'
Once done, install the libarchive-fork/ from third-party/ of the unpacker project. Note that you cannot use libarchive nor libarchive-dev packages from webports at this moment, as not all patches in the fork are upstreamed.
$ cd third-party $ make libarchive-fork
Polymer is used for UI. In order to fetch it, in the same directory type:
$ make polymer
Build the PNaCl module.
$ cd unpacker $ make [debug]
The package can be found in the release or debug directory. You can run it directly from there using Chrome's “Load unpacked extension” feature, or you can zip it up for posting to the Chrome Web Store.
$ zip -r release.zip release/
Once it's loaded, you should be able to open ZIP archives in the Files app.
Paths that aren't linked below are dynamically created at build time.
Some high level points to remember: the JS side reacts to user events and is the only part that has access to actual data on disk. It uses the NaCl module to do all the data parsing (e.g. gzip & tar), but it has to both send a request to the module (“parse this archive”), and respond to requests from the module when the module needs to read actual bytes on disk.
When the extension loads, background.js registers everything and goes idle.
When the Files app wants to mount an archive, callbacks in app.js
unpacker.app are called to initialize the NaCl runtime. Creates an
unpacker.Volume object for each mounted archive.
Requests on the archive (directory listing, metadata lookups, reading files) are routed through app.js
unpacker.app and to volume.js
unpacker.Volume. Then they are sent to the low level decompressor.js
unpacker.Decompressor which talks to the NaCl module using the request.js
unpacker.request protocol. Responses are passed back up.
When the NaCl module is loaded, module.cc
NaclArchiveModule is instantiated. That instantiates
NaclArchiveInstance for initial JS message entry points. It instantiates
JavaScriptMessageSender for sending requests back to JS.
When JS requests come in, module.cc
NaclArchiveInstance will create volume.h
Volume objects on the fly, and pass requests down to them (using the protocol defined in request.h
request::*).
volume.h
Volume objects in turn use the volume_archive.h
VolumeArchive abstract interface to handle requests from the JS side (using the protocol defined in request.h
request:**). This way the lower levels don't have to deal with JS directly.
volume_archive_libarchive.cc
VolumeArchiveLibarchive implements the
VolumeArchive interface and uses libarchive as its backend to do all the decompression & archive format processing.
But NaCl code doesn't have access to any files or data itself. So the volume_reader.h
VolumeReader abstract interface is passed to it to provide the low level data read functions. The volume_reader_javascript_stream.cc
VolumeReaderJavaScriptStream implements that by passing requests back up to the JS side via the javascript_requestor_interface.h
JavaScriptRequestorInterface interface (which was passed down to it).
So requests (mount an archive, read a file, etc...) generally follow the path:
request::*
NaclArchiveModule->
NaclArchiveModule->
request::*
Volume
VolumeArchive
VolumeArchiveLibarchive
VolumeReader
VolumeReaderJavaScriptStream
JavaScriptRequestorInterface
JavaScriptRequestor
JavaScriptMessageSenderInterface
JavaScriptMessageSender->
request::*
Then once
VolumeArchive has processed the raw data stream, it can return results to the
Volume object which takes care of posting JS status messages back to the Chrome side.
Here‘s the JavaScript code that matters. A few files have very specific purposes and can be ignored at a high level, so they’re in a separate section.
unpacker.app
unpacker.Volumeobjects.
unpacker.Volume
unpacker.Volumeinstance.
unpacker.Decompressor
unpacker.Volumerequests.
unpacker.requestprotocol.
unpacker.request
unpacker.PassphraseManager
These are the boilerplate/simple JavaScript files you can generally ignore.
unpacker.types
unpacker
unpacker.*namespace.
Here's the NaCl layout.
JavaScriptMessageSenderInterfaceinterface so the rest of NaCl code can easily send messages back up.
JavaScriptRequestorInterfaceinterface for talking to JS side.
Volumeclass that encompasses a high level volume.
VolumeArchive.
JavaScriptRequestorInterfaceinterface.
VolumeArchiveinterface for handling specific archive formats.
VolumeArchiveusing the libarchive project.
VolumeReaderinterface for low level reading of data.
VolumeReader.
JavaScriptRequestorInterfaceto get data from the JS side.
To see debug messages open chrome from a terminal and check the output. For output redirection see.
Install Karma for tests runner, Mocha for asynchronous testings, Chai for assertions, and Sinon for spies and stubs.
$ npm install --save-dev \ karma karma-chrome-launcher karma-cli \ mocha karma-mocha karma-chai chai karma-sinon sinon # Run tests: $ cd unpacker-test $ ./run_js_tests.sh # JavaScript tests. $ ./run_cpp_tests.sh # C++ tests. # Check JavaScript code using the Closure JS Compiler. # See $ cd unpacker $ npm install google-closure-compiler $ bash check_js_for_errors.sh | https://chromium.googlesource.com/apps/unpacker/+/cb7e2354a03636e4e893e84b58d7532887788c88 | CC-MAIN-2018-43 | refinedweb | 883 | 51.65 |
Satheesh Bandaram wrote:
> I almost submitted a patch using option 1, like I said I would. I have
> added a SynonymAliasInfo to hold target of a synonym, which is
> schemaName.tableName. I think this schemaName needs to be stored as a
> name, instead of an ID so that the synonym stays valid even after
> droping and recreating the target schema.
That seems like correct behaviour.
> Yes, the namespace for SYNONYM is the same for tables and views. You
> can't create a synonym if a table of that name already exists.
An explanation of how this is enforced would be good, another approach
would be to introduce a new table type in SYSTABLES, and then the
uniqueness would be handled by the existing code. Maybe you are doing
that already. I guess I should wait for the patch. :-)
Dan. | http://mail-archives.apache.org/mod_mbox/db-derby-dev/200506.mbox/%3C429E56F9.40105@debrunners.com%3E | CC-MAIN-2013-48 | refinedweb | 139 | 72.97 |
Convert Marc21 Classification records in MARC/XML to SKOS/RDF
Project Description
Python script for converting MARC 21 Classification and MARC 21 Authority records (serialized as MARCXML) to SKOS concepts.
Initially developed to support the project “Felles terminologi for klassifikasjon med Dewey”, for converting Dewey Decimal Classification (DDC) records. Issues and suggestions for generalizations and improvements are welcome!
See mapping schema for MARC21 Classification and for MARC21 Authority below.
Installation
Releases can be installed from the command line with pip:
$ pip install --upgrade mc2skos # with virtualenv or as root $ pip install --upgrade --user mc2skos # install to ~/.local
- Works with both Python 2.7 and 3.3+. See Travis for details on tested Python versions.
- If lxml fails to install on Windows, try the windows installer from from PyPI.
- If lxml fails to install on Unix, install system packages python-dev and libxml2-dev
- Make sure the Python scripts folder has been added to your PATH.
To directly use a version from source code repository:
$ git clone $ cd mc2skos $ pip install -e .
Usage
mc2skos infile.xml outfile.ttl # from file to file mc2skos infile.xml > outfile.ttl # from file to standard output
Run mc2skos --help or mc2skos -h for options.
URIs
URIs are generated automatically for known concept schemes, identified from 084 $a for classification records and from 008[11] / 040 $f for authority records. To list known concept schemes:
$ mc2skos -l
To add more vocabularies, you can edit vocabularies.yml. Pull requests for adding more vocabularies are very welcome!
URIs can be also be generated on the fly from an URI template specified with option --uri. The following template parameters are recognized:
- {control_number} is the control number from 001, 010 or 016. The current approach is to use 010 or 016 if defined, otherwise 001. If you find examples where this approach fails, please add them to [#42]().
- {collection} is “class”, “table” or “scheme”
- {object} is a member of the classification scheme (with spaces replaced by hyphens) and part of a {collection}, such as a specific class or table.
- {edition} is taken from 084 $c (with language code stripped)
To add skos:inScheme statements to all records, an URI template can be specified with option --scheme. Otherwise, it will be derived from a default template if the concept scheme is known.
To add an additional skos:inScheme statement to table records, an URI template can be specified with option --table_scheme. Otherwise, it will be derived from a default template if the concept scheme is known.
The following example is generated from a DDC table record:
<> a skos:Concept ; skos:inScheme <>, <> ; skos:notation "T6--982" ; skos:prefLabel "Chibchan and Paezan languages"@en .
Mapping schema for MARC21 Classification
Only a small part of the MARC21 Classification data model is converted, and the conversion follows a rather pragmatic approach, exemplified by the mapping of the 7XX fields to skos:altLabel.
Synthesized number components
Components of synthesized numbers explicitly described in 765 fields are
expressed using the
mads:componentList property, and to preserve the order of the
components, we use RDF lists. Example:
@prefix mads: <> . <> a skos:Concept ; mads:componentList ( <> <> <> ) ; skos:notation "001.30973" .
Retrieving list members in order is surprisingly hard with SPARQL. Retrieving ordered pairs is the best solution I’ve come up with so far:
PREFIX mads: <> PREFIX rdf: <> PREFIX skos: <> SELECT ?c1_notation ?c1_label ?c2_notation ?c2_label WHERE { GRAPH <> { <> mads:componentList ?l . ?l rdf:rest* ?sl . ?sl rdf:first ?e1 . ?sl rdf:rest ?sln . ?sln rdf:first ?e2 . ?e1 skos:notation ?c1_notation . ?e2 skos:notation ?c2_notation . OPTIONAL { ?e1 skos:prefLabel ?c1_label . } OPTIONAL { ?e2 skos:prefLabel ?c2_label . } }}
Additional conversion rules for WebDewey data
The script comes with a few extra rules for distinguishing between different types of notes in WebDewey records and extract entities from these. The entity extraction rules (marked with [*] below) utilizes a non-standard namespace and are not enabled by default. Specify the --webdewey flag to use them.
Notes that are currently not treated in any special way:
- 253 having $9 ess=nsx Do-not-use.
- 253 having $9 ess=nce Class-elsewhere
- 253 having $9 ess=ncw Class-elsewhere-manual
- 253 having $9 ess=nse See.
- 253 having $9 ess=nsw See-manual.
- 353 having $9 ess=nsa See-also
- 683 having $9 ess=nbu Preference note
- 683 having $9 ess=nop Options note
- 683 having $9 ess=non Options note
- 684 having $9 ess=nsm Manual note
- 685 having $9 ess=ndp Discontinued partial
- 685 having $9 ess=nrp Relocation
- 689 having $9 ess=nru Sist brukt i…
Release history Release notifications
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/mc2skos/ | CC-MAIN-2018-17 | refinedweb | 775 | 54.12 |
The Mixxx 2.3 beta was released in June, though I haven't been able to find an estimated release date for the final version. For porting, the major change is a transition to CMake for the build instead of SCons (see bug 247189).
I've opened this bug to document changes for building Mixxx 2.3 with CMake, currently with the latest git snapshot of the 2.3 branch. I think most changes for porting the (upcoming) new version will just be adaptations of the existing patches for the new build system.
Here's what I've done so far to try to make it build:
- add security/qtkeychain, sysutils/upower, comms/hidapi as dependencies. (Some of these are patched out in the current port.)
- portmidi: rather than patching this out, I think the best solution would be to add a new portmidi port. After downloading the sources, I tried the following changes to build:
- configure script using ccmake is interactive. I had to manually specify the JAVA_INCLUDE_PATH and JAVA_JVM_LIBRARY paths as described in `portmidi/trunk/pm_linux/README_LINUX.txt`. The paths depend on the installed JDK version. There must be a good way to do this automatically. In my case, these paths are: JAVA_INCLUDE_PATH=/usr/local/openjdk8/include and JAVA_JVM_LIBRARY=/usr/local/openjdk8/jre/lib/amd64/server/libjvm.so
- add `/usr/local/include` to `include_directories` on line 68 of portmidi/trunk/CMakeLists.txt
- set the env variable LIBRARY_PATH=/usr/local/lib in order to find asound library from alsa, may be better to instead patch in the `-L/usr/local/lib` flag throughout the source files
- patch two functions using deprecated `ftime` to use `gettimeofday` in `porttime/ptlinux.c` (c.f.).
For the default make target, I get this error around 93%:
make[2]: don't know how to make pm_java/jportmidi/JPortMidi.class. Stop
It is possible to patch out portmidi: keep existing patch to controllers/controllermanager.cpp, remove REQUIRED keyword in CMakeLists.txt for PortMidi, comment out `portmidicontroller.cpp` and `portmidienumerator.cpp` around line 2365 of CMakeLists.txt. However, this causes build failures later on that I haven't yet figured out.
- use system libusb. I'm not sure how to make this happen in CMakeLists.txt (see lines around 2260). I don't use a USB controller, and configure succeeds if the feature is disabled (cmake -DHID=off ...). It should be possible to pass the flags '-DLIBUSB_INCLUDE_DIR=/usr/include -DLIBUSB_LIBRARIES=/usr/lib/libusb.so' to the configure command, but this fails in logic around lib-hdiapi.
- add include directory for ogg.h in libshout. There may be a better way to do this, but I just added `/usr/local/include` to `include_directories` in `lib/libshout/CMakeLists.txt`.
- change `endian.h` to `sys/endian.h`, and `byteswap.h` to `infiniband/byteswap.h` in lib/kaitai/kaitaistream.cpp
With these changes (patching out portmidi since I haven't succeded in building it yet), mixxx 2.3 configures successfully and builds partially (12%), failing eventually with:
In file included from /home/david/Downloads/mixxx/cmake_build/mixxx-lib_autogen/T7JLZL2D4I/moc_portmidicontroller.cpp:10:
/home/david/Downloads/mixxx/cmake_build/mixxx-lib_autogen/T7JLZL2D4I/../../../src/controllers/midi/portmidicontroller.h:20:10: fatal error:
'portmidi.h' file not found
#include <portmidi.h>
^~~~~~~~~~~~
portmidi builds successfully with the above procedure if *gmake* is used instead of BSD make. I'll open a separate issue for a new portmidi port separately when I have a ports Makefile working. | https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=249348 | CC-MAIN-2021-21 | refinedweb | 571 | 51.85 |
Hi, I am running in to a little trouble here. I am getting this error: error CS0176: Static member `localVariables.test()' cannot be accessed with an instance reference, qualify it with a type name instead
void OnTriggerStay2D (Collider2D other){ int num = other.gameObject.GetComponent("localVariables").index;//something is wrong here <<< }
i have an object called a(Clone), clone objects. when it is colliding with a trigger2D box, I want to get that objects int index, which is inside it's own script called localVariables.
public class localVariables : MonoBehaviour { public static int index; }
Am I calling the object correctly? What is wrong here?
is there a function called test() in your code?
Answer by Noob_Vulcan
·
May 29, 2014 at 06:28 AM
Make it public int index . Remove static from index . Static members are called with Class Name not with class instance.
public int index
and change
other.gameObject.GetComponent<localVariables>().
Distribute terrain in zones
3
Answers
Multiple Cars not working
1
Answer
Collision sounds doubling up.
1
Answer
Detect Collisions from Script
1
Answer
Check a space before Instantiating into it
0
Answers | https://answers.unity.com/questions/717037/how-to-call-the-script-of-an-object-being-collided.html | CC-MAIN-2019-47 | refinedweb | 183 | 59.09 |
C Interface
#include <papi.h>
int PAPI_register_thread (void);
int PAPI_unregister_thread (void);
Fortran Interface
#include fpapi.h
PAPIF_register_thread(C_INT check )
PAPIF_unregister_thread(C_INT check )
PAPI_register_thread should be called when the user wants to force PAPI to initialize a thread that PAPI has not seen before. Usually this is not necessary as PAPI implicitly detects the thread when an eventset is created or other thread local PAPI functions are called. However, it can be useful for debugging and performance enhancements in the run-time systems of performance tools.
PAPI_unregister_thread should be called when the user wants to shutdown a particular thread and free the associated thread ID. THIS IS IMPORTANT IF YOUR THREAD LIBRARY REUSES THE SAME THREAD ID FOR A NEW KERNEL LWP. OpenMP does this. OpenMP parallel regions, if separated by a call to omp_set_num_threads() will often kill off the underlying kernel LWPs and then start new ones for the next region. However, omp_get_thread_id() does not reflect this, as the thread IDs for the new LWPs will be the same as the old LWPs. PAPI needs to know that the underlying LWP has changed so it can set up the counters for that new thread. This is accomplished by calling this function.
None.
PAPI_ENOMEM Space could not be allocated to store the new thread information.
PAPI_ESYS A system or C library call failed inside PAPI, see the errno variable.
PAPI_ESBSTR Hardware counters for this thread could not be initialized.
PAPI_thread_id(3), PAPI_thread_init(3) | http://icl.cs.utk.edu/projects/papi/wiki/PAPIC:PAPI_unregister_thread.3 | CC-MAIN-2017-17 | refinedweb | 242 | 55.54 |
mount_null - demonstrate the use of a null file system layer
mount_null [-o options] target mount_point
The mount_null command creates a null layer, duplicating a
sub-tree of
the file system namespace under another part of the global
file system
namespace. It is implemented using a stackable layers technique, and its
``null-nodes'' stack above all lower-layer vnodes (not just
above directory
vnodes).
The options are as follows:
-o options
Options are specified with a -o flag followed by a
comma separated
string of options. See the mount(8) man page for
possible options
and their meanings.
The null layer has two purposes. First, it serves as a
demonstration of
layering by proving a layer which does nothing. Second, the
null layer
can serve as a prototype layer. Since it provides all necessary layer
framework, new file system layers can be created very easily
be starting
with a null layer.
The remainder of this man page examines the null layer as a
basis for
constructing new layers.
New null layers are created with mount_null. mount_null
takes two arguments:
the pathname of the lower vfs (target-pn) and the
pathname where
the null layer will appear in the namespace (mount-pointpn). After the
null layer is put into place, the contents of target-pn subtree will be
aliased under mount-point-pn.
The null layer is the minimum file system layer, simply bypassing all
possible opening
sys. A vop_lookup would be done on the root null-node.
This operation
would bypass through to the lower layer which would return a vnode
representing the UFS sys. Null_bypass then builds a nullnode aliasing
the UFS sys and returns this to the caller. Later operations on the
null-node sys will repeat this process when constructing
other vnode
stacks.nodes arguments must be manually
mapped.
mount(2), mount(8), umount(8)
UCLA Technical Report CSD-910056, Stackable Layers: an
Architecture for
File System Development.
The mount_null utility first appeared in 4.4BSD.
OpenBSD 3.6 April 19, 1994 | http://nixdoc.net/man-pages/OpenBSD/man8/mount_null.8.html | CC-MAIN-2020-16 | refinedweb | 334 | 56.25 |
I’m a Ruby newbie. I’ve only been at the language for a little over a
week, but so far I’m impressed. My language of choice for the past
several years has been Python, so I’m trying to figure out how to do
all my familiar Python tricks in Ruby. Mostly, this has been easy, but
there is one thing that leaves me stumped: is it possible to start the
debugger from within an interactive session?
For example, say I’ve written the file called “test.rb” containing the
function “adder”.
def adder(x, y)
x+y
end
I can launch irb and try out the function.
irb(main):001:0> require “test”
=> true
irb(main):002:0> adder(3,4)
=> 7
What I’d like to do is start the debugger from within the interactive
session and step into the function. For a similar Python program you
could do the following
import test
import pdb
pdb.run(“test.adder(3,4)”)
(1)?()
(Pdb) s
–Call–
/Users/bill/temp/test.py(1)adder()
-> def adder(x,y):
(Pdb) n
/Users/bill/temp/test.py(2)adder()
-> return x+y
I haven’t been able to figure out if the Ruby debugging environment has
a similar feature. I’ve searched documentation, played with debug, and
glanced at the debug.rb source, to no avail.
Of course I could write a wrapper script that calls adder and run that
with “ruby -rdebug wrapper.rb”, but that loses the convenience of being
able to work entirely in the interactive mode, which I find very
useful, particularly in the early stages of development.
Thanks for your help. | https://www.ruby-forum.com/t/can-the-debugger-be-called-from-within-an-interactive-sessio/56348 | CC-MAIN-2019-39 | refinedweb | 276 | 74.39 |
Cliff 1.3.2 is not available
Bug Description
Latest python-
# dpkg --list |grep quantum
ii python-quantum 1:2013.
ii python-
ii quantum-common 1:2013.
ii quantum-dhcp-agent 1:2013.
ii quantum-l3-agent 1:2013.
ii quantum-
ii quantum-
ii quantum-
ii quantum-server 1:2013.
The ERROR:
# quantum net-list
Traceback (most recent call last):
File "/usr/bin/quantum", line 5, in <module>
from pkg_resources import load_entry_point
File "/usr/lib/
parse_
File "/usr/lib/
raise DistributionNot
pkg_resources.
Status changed to 'Confirmed' because the bug affects multiple users.
Hi,
to fixe this bug upgrade cliff to cliff 1.3.2 :
https:/
to install it : untar and python setup install
Thanks for the workaround Linus. Will give it a shot... Do we expect this package to make it into ubuntu soon? Or are there conflicts with other packages and we will have to wait a while?
Thanks Again.
OK - so the trunk testing packages for the openstack clients have now exceeded the dependencies that can be fulfilled from the distro; the release version for grizzly of quantumclient is 2.2.0 which requires 1.3.1 of cliff.
This should be fixed (but not in the grizzly trunk testing PPA) once S-series of Ubuntu and Havana PPA's open.
If this wont be fixed in Grizzly, then the offending python-
Aimon- Please use the grizzly pocket of the Ubuntu Cloud Archive instead of the trunk PPAs. The PPAs are unsupported. If this is a valid bug that warrants an update, it will be published to Ubuntu and the Cloud Archive, not the PPAs. I'm having trouble reproducing this with what we have packaged there, but if you can please reopen with details. Thanks
Ticket which introduced issue: https:/
/bugs.launchpad .net/python- quantumclient/ +bug/1165962 | https://bugs.launchpad.net/ubuntu/+source/python-quantumclient/+bug/1170849 | CC-MAIN-2017-04 | refinedweb | 300 | 76.01 |
Net::SIP::StatelessProxy - Simple implementation of a stateless proxy
..
This package implements a simple stateless SIP proxy. Basic idea is that the proxy has either a single or two legs and that the packets are exchanged between those legs, e.g. packets incoming on one leg will be forwarded through the other leg.
Because this is a stateless proxy no retransmits will be done by the proxy.
If the proxy should work as a registrar too it should be put after a Net::SIP::Registrar in a Net::SIP::ReceiveChain.
While forwarding the proxy will be insert itself into the packet, e.g. it will add Via and Record-Route header while forwarding requests.
Additionally it will rewrite the Contact header while forwarding packets (see below), e.g. if the Contact header points to some client it will rewrite it, so that it points to the proxy and if it already points to the proxy it will rewrite it back so that it again points to the client.
Creates a new stateless proxy. With %ARGS the behavior can be influenced:
The Net::SIP::Dispatcher object managing the proxy.
Callback which is used in rewriting Contact headers. If one puts user@host in it should rewrite it and if one puts something without '@' it should try to rewrite it back (and return () if it cannot rewrite it back). A working default implementation is provided.
Optional Net::SIP::NATHelper::* object. When given it will be used to do NAT, e.g. if the incoming and outgoing legs are different it will rewrite the SDP bodies to use local sockets and the nathelper will transfer the RTP data between the local and the original sockets.
Usually the contact header will only be rewritten, if the incoming and outgoing leg are different. With this option one can force the rewrite, even if they are the same.
PACKET is the incoming packet,
LEG is the Net::SIP::Leg where the packet arrived and FROM is the
"ip:port" of the sender.
Called from the dispatcher on incoming packets.
The packet will be rewritten (
Via and
Record-Route headers added,
Contact modified) and then the packet will be forwarded.
For requests it can determine the target of the forwarded packet by looking at the route or if no route it looks at the URI. For responses it looks at the next Via header.
This will be called from receive while forwarding data. If nathelper is defined it will be used to rewrite SDP bodies and update nathelpers internal states to forward RTP data.
Return values are like forward_outgoing in Net::SIP::Leg,
e.g.
it will return
[code,text] on error or
() on success,
where success can be that the packet was rewritten or that there was no need to touch it. | http://search.cpan.org/~sullr/Net-SIP-0.682/lib/Net/SIP/StatelessProxy.pod | CC-MAIN-2014-23 | refinedweb | 466 | 72.97 |
divan
persistant key-value store for node with CouchDB-style views
npm install divan
Fast in-process in-memory key-value store for node with snapshot and AOF persistance and CouchDB-style map-reduce views. Just make sure your data fits in memory, currently I wouldn't recommend divan for a dataset with more than 500K docs.
why? because!
- some tasks and workloads just don't deserve their own Couch but can benefit from a similar data-model.
- not a Couch - which among other things means it doesn't do MVCC, so delete and update as much as you want.
- super fast - when fully warmed up serves thousands of queries per second, and there's no network latency.
usage
npm install divan
index.js
// Make a divan with local compacted append-only and snapshot files, // namespace works in the same way it does for `dirty`: var divan = require ( 'divan' ), db = divan.cwd ( 'friends' ); // Save some docs, generating your own id-s: db.save ({ _id : 'don1', type : 'person', name : 'Don', gender : 'male' }); db.save ({ _id : 'samantha', type : 'person', name : 'Sam', gender : 'female' }); db.save ({ _id : 'i.v.a.n', type : 'person', name : 'Ivan', gender : 'male' }); // These will be flushed to the AOF and then later compacted as a db snapshot. // Now register a view: db.addView ( 'gender/count', divan.mr ( function ( doc, emit ) { if ( doc.type === 'person' ) emit ( doc.gender, 1 ); }, function ( k, v ) { var i, n = v.length, sum = 0; for ( i = 0; i < n; i ++ ) sum += v [ i ]; return sum; } ) ); // Query the view: db.view ( 'gender/count', { group : true }, function ( err, data ) { data.rows.forEach ( function ( row ) { console.log ( row.key, row.value ); }); }); // Outputs: // female 1 // male 2
You can add views via
db.addView
or by parsing a directory of
design files via
db.design(path).
The design-files can either be
.json files of couchdb-design-doc flavour,
or .js files that export objects
with
map and
reduce methods.
Note that when using .js docs,
map functions need to accept
the
emit function as the second parameter.
CouchDB view API coverage
Everything but
group_level and
include_docs.
lazy views and reduce caching.
what else
- You can iterate your entire db with
db.forEach(func)
- If you look at the sources, you'll see that there's an option to have your snapshots on Amazon S3.
- By using
db.addView("view-name", ["source-view", "other-source-view"], viewObj)you can perform chained map/reduce, although its not optimized and is really slow right now.
license
MIT | https://www.npmjs.org/package/divan | CC-MAIN-2014-10 | refinedweb | 417 | 68.77 |
.
#include <Origin.h> #include <GetNBox.h> //---------------------------------------------------------------------------- // CSpiral // The base class that does all the complicated stuff. // By itself it will do an Index spiral. // All other spirals should be derived from CSpiral. //---------------------------------------------------------------------------- class CSpiral { public: CSpiral() { } ~CSpiral() { } // Creates the CSpiral class to be called on by Prime and other related functions. int Run() { if( AttachActive() ) run(); return 0; } virtual int Equation() { m_M[m_row][m_col] = m_index; return 0; } // This takes the product of the rows and columns of the matrix and creates integers based on them protected: Matrix<double> m_M; int m_numRows, m_numCols; int m_index, m_row, m_col; BOOL AttachActive() { MatrixLayer ml = Project.ActiveLayer(); if( !ml.IsValid() ) return FALSE; return m_M.Attach(ml); } // This confirms that a matrix is present in which these values may be placed int run() { int left, right, top, bottom; run_init(); left = right = m_col; top = bottom = m_row; while( true ) { while( m_col <= right ) { Equation(); m_col++; m_index++; } if( m_col == m_numCols ) break; right++; while( m_row >= top ) { Equation(); m_row--; m_index++; } if( m_row < 0 ) break; top--; while( m_col >= left ) { Equation(); m_col--; m_index++; } if( m_col < 0 ) break; left--; while( m_row <= bottom ) { Equation(); m_row++; m_index++; } if( m_row == m_numRows ) break; bottom++; } return 0; } void run_init() { m_numRows = m_M.GetNumRows(); m_numCols = m_M.GetNumCols(); if( m_numRows != m_numCols ) { if( m_numRows < m_numCols ) m_numCols = m_numRows; else m_numRows = m_numCols; } m_row = m_numRows >> 1; m_col = m_numCols >> 1; if( (m_numCols & 1) == 0 ) m_col--; m_index = 1; } }; //This last section determines the placement of these values relative to aspect ratio of the matrix //if the matrix is not square then the spiral will form in the largest square that can be drawn //and will otherwise return the missing number sign (--).
This code generates the spiral, however we need a way to call this as a function from Origin’s script window. To do this, in Code Builder we’ll add the following lines to the end of our script-
//---------------------------------------------------------------------------- // UlamSpiral // The main function for calling the different types of spirals. //---------------------------------------------------------------------------- enum { UlamSpiral_Help = 0, UlamSpiral_Index, UlamSpiral_Unknown }; // This creates an index allowing you to call the UlamSpiral help with UlamSpiral(0), generate // the Ulam Spiral itself with UlamSpiral(1), or return a null "unknown" error for // any other other value. int UlamSpiral(int type = 0) { switch( type ) { case UlamSpiral_Help: printf("%d = Help\n", UlamSpiral_Help); printf("%d = Index\n", UlamSpiral_Index); break; case UlamSpiral_Index: { CSpiral spiral; spiral.Run(); } break; } return 0; } // This section generates "help" for option 0, listing the 3 options, // runs the CSpiral function on our previous script for option 1, // and returns a text break for any other value representing an "unknown" function. | http://blog.originlab.com/ja/creating-ulam-spirals-with-originc-part-i | CC-MAIN-2022-33 | refinedweb | 414 | 54.97 |
Creating a Mobile Application with SQL Server Compact Edition
In this walkthrough, you will learn how to create an application in Microsoft Visual Studio 2005 that uses Microsoft SQL Server 2005 Compact Edition. The SQL Server Compact Edition database will be a Subscriber to a SQL Server 2005 Publication and will use merge replication to download information from a SQL Server 2005 database to the SQL Server Compact Edition database.
In this walkthrough, you will follow these steps:
- Configure a SQL Server 2005 publication.
- Configure Internet Information Services (IIS) for replication.
- Create a SQL Server Compact Edition subscription.
- Create an application.
- Deploy the application and test the subscription.
Prerequisites
To perform this walkthrough as it is written, you must have the following:
- A computer that has Windows XP and IIS installed.
- SQL Server 2005 Service Pack 2 (SP2) or a later version, installed on the same computer as Visual Studio.
SQL Server 2005 Tasks
Before you create the application, you must configure a publication in SQL Server 2005. In the following steps, you will create a sample database and then publish data from that database. You will create the database by using a prebuilt script file, and then create the publication with the New Publication Wizard
Create a database and populate with data
Open SQL Server Management Studio.
When you are prompted to connect to a server, type (local) for the Server Name, and then click Connect.
Open a new query window. Create a SQL Server Compact Edition database and populate the database with data.
USE master; GO IF EXISTS (SELECT * FROM sys.sysdatabases WHERE name = 'SQLMobile') BEGIN DROP Database SQLMobile; END GO CREATE DATABASE SQLMobile; GO USE SQLMobile; GO CREATE TABLE MembershipData (MemberID INTEGER IDENTITY (1,1) CONSTRAINT pkMemberID PRIMARY KEY, MemberName NVarChar (50)); CREATE TABLE FlightData (MemberID INTEGER FOREIGN KEY REFERENCES MembershipData(MemberID), Destination NVarChar (50), FlightStatus NVarChar(50), ArrivalDate DATETIME, FlownMiles INTEGER); INSERT INTO MembershipData (MemberName) VALUES ('Mr Don Hall'); INSERT INTO MembershipData (MemberName) VALUES ('Mr Jon Morris'); INSERT INTO MembershipData (MemberName) VALUES ('Ms TiAnna Jones'); INSERT INTO FlightData (MemberID, Destination, FlightStatus, ArrivalDate, FlownMiles) VALUES (1, 'Seattle', 'Flight Delayed 1 hour', '8/25/00', '20000'); INSERT INTO FlightData (MemberID, Destination, FlightStatus, ArrivalDate, FlownMiles) VALUES (2, 'London', 'Flight on time', '9/12/00', '15000'); INSERT INTO FlightData (MemberID, Destination, FlightStatus, ArrivalDate, FlownMiles) VALUES (3, 'Sydney', 'Flight Gate Closing', '11/5/00', '30000'); INSERT INTO FlightData (MemberID, Destination, FlightStatus, ArrivalDate, FlownMiles) VALUES (1, 'Tokyo', 'Delayed Fog', '5/25/00', '25000'); INSERT INTO FlightData (MemberID, Destination, FlightStatus, ArrivalDate, FlownMiles) VALUES (2, 'Minneapolis', 'Flight on time', '5/1/00', '1000'); INSERT INTO FlightData (MemberID, Destination, FlightStatus, ArrivalDate, FlownMiles) VALUES (3, 'Memphis', 'Flight Gate Closing', '1/5/00', '1000'); GO
Click Execute (!) to run the script and create the database. The script runs and creates a new database named SQLMobile.
Note
You can also press F5 or choose Execute from the Query menu to run the query.
To confirm that the database was created, in Object Explorer, expand (local), expand Databases, and then expand SQLMobile. If the SQLMobile database is not listed, update the list of databases by right-clicking Databases and selecting Refresh
Prepare the Server for Publishing Data
Before you create a publication, you must prepare the server for publishing by creating a snapshot agent user account and creating a shared folder in which the snapshot files will be stored. When the snapshot folder is created, it is used for all publications on the server. If you have created publications previously on this server, you can skip these steps.
Create the snapshot user account
Open Computer Management from Administrative Tools in Control Panel.
In Computer Management, expand System Tools, expand Local Users and Groups, right-click Users, and then choose New User.
Type the following information in the New User dialog box, and then click Create:
Important
These settings should be used for testing only. In a production environment, make sure that your user account settings are in compliance with the network security requirements. Frequently, you will use a domain user account instead of a local user account for the snapshot agent.
Create the snapshot folder
In Windows Explorer, create a new folder named snapshot. For this walkthrough, you can create the folder in the root directory of drive C at c:\snapshot. Right-click the snapshot folder and select Sharing and Security.
On the Sharing tab, select Share this folder, and then click Permissions.
In Permissions for snapshot, click Add.
In Enter the object name to select, type computername\snapshot_agent where computername is the name of the local computer, click Check Names, and then click OK.
In Permissions for snapshot, select snapshot_agent, assign the Change and Read share permissions, and then click OK.
Select the Security tab.
Click Add.
In Enter the object name to select, type computername\snapshot_agent where computername is the name of the local computer, click Check Names, and then click OK.
Select snapshot_agent and add the Write permission to the list of enabled permissions. The snapshot_agent account will now be granted the following permissions:
- Read and Execute
- List Folder Contents
- Read
- Write
Click OK to close the snapshot Properties window.
Close Windows Explorer.
Create a publication
In Object Explorer in SQL Server Management Studio, expand the (local) node if it is not currently expanded, and then expand Replication.
Right-click the LocalPublications folder and select New Publication.
In the New Publication Wizard introduction screen, click Next.
If you have not created a publication on this computer before, you will be prompted to configure a Distributor. Select the first option to use the local computer as its own Distributor, and then click Next.
If you have not created a publication on this computer before, you will be prompted to specify a snapshot folder. Type the share path of the snapshot folder that you created in the previous procedure. Type the share path in the form \\servername\share**instead of the local path. In this walkthrough, we recommend that you type \\computer\snapshot, where computer is the name of your computer, and then click Next.
In the list of databases, select SQLMobile, and then click Next.
In the list of publication types, select Merge publication, and then click Next.
In the SubscribersTypes page, select Yes to enable support for SQL Server Compact Edition subscribers, and then click Next.
In the list of objects to publish, select the Tables check box. If you expand Tables, you will see that both tables in the SQLMobile database are selected. Click Next.
You are notified that unique identifiers will be added to the tables. All merge articles require a uniqueindentifier column. Click Next.
In the Filter Table Rows page, you can now add filters to the published data. For this walkthrough, you will not filter the data. Click Next.
On the Snapshot Agent page, you can configure when the snapshot will be created and how frequently the Snapshot Agent runs. Click Next to accept the default settings.
In the Agent Security dialog box, click Security Settings.
- In the Snapshot Agent Security dialog box, enter the logon information for the account you created in the previous procedure. The process account is computer_name\snapshot_agent (where computer_name is the name of your computer) and the password is p@ssw0rd.
- Click OK to save the settings.
- Click Next on the Agent Security page.
On the Wizard Actions screen, you can determine when the publication is created and whether you want a script file to be created. Clear Create a snapshot immediately, and then click Next.
On the Complete the Wizard screen, type SQLMobile for the name of the publication, and then click Finish.
The publication is created. When the wizard finishes, click Close.
Setting Permissions
You must grant permissions for the Snapshot Agent account and for the IIS anonymous user account. You must also add the IIS anonymous user account to the Publication Access List (PAL).
Set database permissions
In SQL Server Management Studio, in Object Explorer, expand Security, right-click Logins, and select New Login.
In the New Login dialog box, select Windows Authentication, click Search, type computername\snapshot_agent in the Enter the object name to select box, where computername is the name of your computer, click Check Names, and then click OK.,
In the Navigation Pane, choose the User Mapping pane.
In the list of databases, select distribution and the db_owner role, select SQLMobile and the db_owner role, and then click OK.
Right-click Logins, and select New Login.
In the New Login dialog box, select Windows Authentication, click Search, type computername\iusr_computername in the Enter the object name to select box, where computername is the name of your computer, click Check Names, and then click OK.,
In the Navigation Pane, select the User Mapping pane.
In the list of databases, select distribution and SQLMobile, and then click OK.
Granting publication access
In Object Explorer, expand Replication, expand Publications, right-click the [SQLMobile]:SQLMobile publication, and then click Properties.
In the Navigation Pane, select Publication Access List.
Click Add. In the Add Publication Access dialog box, the IUSR account is listed. Select it, and then click OK.
Make sure that the IUSR account is now in the PAL, and then click OK.
Creating the Publication Snapshot
Before you can initialize a subscription to the SQLMobile publication, you must create the publication snapshot.
Create the publication snapshot
In SQL Server Management Studio, in Object Explorer, expand the (local) computer node.
Expand the Local Publications folder, select the publication name, right-click SQLMobile, and then click View Snapshot Agent Status.
In the View Snapshot Agent Status dialog box, click Start.
Make sure that the snapshot job has succeeded before you continue.
Configuring IIS and SQL Server 2005 for Web Synchronization
Now that SQL Server has been configured with a publication, you must make that publication available over the network to SQL Server Compact Edition clients. SQL Server Compact Edition connects to SQL Server through IIS. Specifically, you create and configure a virtual directory that makes the SQL Server Compact Edition Server Agent available to the clients.
Install the SQL Server Compact Edition server components
In Windows Explorer, locate the following directory:
C:\Program Files\Microsoft SQL Server\90\Tools\Binn\VSShell\Common7\IDE
Double-click sqlce30setupen.msi to run the installation program.
On the introduction screen of the Setup wizard, click Next.
Read and accept the Microsoft Software License Terms, and then click Next.
On the System Configuration Check screen, make sure that all items pass. The last item on the list will be listed as a warning if you do not have SQL Server 2000 installed. Because you are using SQL Server 2005, this is not a problem. Click Next.
Click Next on the following screen, and then click Install to start installation.
Click Finish.
Configure the publication for Web synchronization
In SQL Server Management Studio, in Object Explorer, expand the (local) computer node.
Expand the Local Publications folder, select the publication name, right-click and then select Configure Web Synchronization.
On the introduction screen of the wizard, click Next.
On the Subscriber Type screen, choose SQL Server Compact Edition, and then click Next.
On the Web Server screen, type the name of your computer in the computer running IIS text box, if it is not already provided, and then click Create a new virtual directory.
In the tree that is displayed, expand the computer, expand Web Sites, and then select Default Web Site.
Click Next.
In the Alias text box of the Virtual Directory Information screen, type SQLMobile, and then click Next.
If you receive a warning dialog box, click Yes.
In the Secure Communications screen, select Do not require security channel (SSL).
Important In a production environment, you should enable SSL encryption to protect data exchanged over the Internet between the Subscriber and the Server Running IIS Client Authentication screen, select Clients will connect anonymously, and then click Next.
On the Anonymous Access screen, accept the default settings by clicking Next.
On the Snapshot Share Access screen, type \\computer\snapshot, where computer is the name of your computer, and then click Next.
If you receive a warning that the snapshot share is empty, click Yes.
Click Finish.
Click Close.
In Internet Explorer, enter the URL in Address and then click Go. This connects to the server in diagnostic mode. Make sure that the SQL Server Compact Edition Server Agent Diagnostics report shows success.
SQL Server Compact Edition Tasks
Before developing an application that will use SQL Server Compact Edition, it is frequently time-saving to pre-create the SQL Server Compact Edition database and subscription. SQL Server Management Studio lets you create and work with a SQL Server Compact Edition database on the local computer. You can then use this database when you develop your application.
Create a new SQL Server Compact Edition database
In SQL Server Management Studio, in Object Explorer, click Connect, and then choose SQL Server Compact Edition.
In the Database File field, choose <New Database…>.
In the file name text box, type c:\sqlmobile.sdf, and then click OK.
If you receive a warning about a blank password, click Yes. The database in this tutorial is not password protected or encrypted.
In the Connect to Server dialog box, click Connect.
A new node named SQL Server Compact Edition [My Computer\...\sqlmobile] is added to Object Explorer.
Create a new subscription
In Object Explorer, expand the SQL Server CompactEdition node, expand Replication, right-click Subscriptions, and then choose New Subscription.
On the introduction screen, click Next.
On the Choose Publication screen, in the Publisher drop down list, choose <Find SQL Server Publisher…>.
In the Connect to Server dialog box, type or choose the name of the local computer, and then click Connect.
On the Choose Publication screen, in the list of publications, expand SQLMobile, select the SQLMobile publication, and then click Next.
On the Identify Subscription screen, type SQLMobile for the subscription name, and then click Next.
On the Web Server Authentication screen, type the URL for the virtual directory you created in the previous procedure. In this walkthrough, you created a virtual directory with a URL of.
Click The Subscriber will connect anonymously, and then click Next.
On the SQL Server Authentication screen, click Next to accept the default settings.
On the final screen, the wizard displays sample code that you can use when you create a subscription in your application. Select the sample code (either Visual Basic or C#, depending on the language you will use to create the application) and copy the code. To do this, select the code and press CTRL+C. Start Notepad or another text editor and paste the sample code. You will use this code when you create the application in the following procedures.
After you have copied the sample code, click Finish.
Click Close.
Building an Application
Create a new Smart Device project
Open Visual Studio 2005.
On the File menu, select NewProject.
In the New Project dialog box, in the Project Types tree, expand your development language and then select Smart Device.
In the list of templates, select the type of project you want to create. For this walkthrough, select Pocket PC 2003 Application.
Provide a name and location for the project, and then click OK. For this walkthrough, name the project SQLMobile.
Visual Studio creates a new project and displays Form1 as it will appear on a smart device.
Add references
In Solution Explorer, right-click References and choose Add Reference.
Note
If the References folder is not listed in Solution Explorer, click Show All Files at the top of Solution Explorer.
In the list of .NET assemblies, select System.Data.SqlServerCe, and then click OK. If System.Data.SqlServerCe is not listed, follow these steps:
- Click the Browse tab.
- Locate the following directory:
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE
- Select System.Data.SqlServerCe.dll, and then click OK.
The list of references in Solution Explorer now includes System.Data.SqlServerCe, and your project can use this assembly.
In Solution Explorer, right-click Form1.cs or Form1.vb and choose View Code.
At the top of the code for the form, add a directive to use the System.Data.SqlServerCe namespace:
[C#]
using System.Data.SqlServerCe;
[VB]
Imports System.Data.SqlServerCe
Add a data connection
In the main window, switch back to the Design (default) view for Form1.
From the Data menu, click Add New Data Source.
Note If Add New Data Source is not displayed, select the Design view for Form1, and then see the Data menu again.
On the Choose a Data Source Type window, select Database, and then click Next.
In the Choose Your Data Connection dialog box, click New Connection.
If an Add Connection dialog box is displayed, click Change.
In the Choose Data Source dialog box, under Data Source, select Microsoft SQL Server Compact Edition (if there was an existing connection, this dialog box might be called Change Data Source). In the list of data providers, choose .NET Framework Data Provider for SQL Server Compact Edition. Click Continue or OK.
In the Add Connection dialog box, under Data Source, select My Computer.
In the Connection properties section, under Database, click Browse, and then browse for the database that you created in a previous procedure. If you have followed the steps, the database is located at c:\sqlmobile.sdf.
Click Test Connection, and then click OK to create the new data connection.
In the Choose Your Data Connection dialog box, click Next.
If a dialog box is displayed that asks you to copy your data file to the current project, click Yes.
In the Save Connection String window, click Next.
In the Choose Your Database Objects window, select Tables, and then click Finish
Choose the data to display
From the Data menu, choose Show Data Sources.
Drag the MembershipData table from the Data Sources window to the Form1 Design window. A datagrid is created on Form1 with the column names automatically provided.
Right-click the datagrid and then click Properties.
In the Properties window, change the Dock value to Top. You can do this by clicking the top bar of the graphical representation that appears, or by typing Top in the value field. The datagrid will be moved and resized to fill the top section of Form1.
In the upper-right corner of the datagrid, click the small arrow. From the menu that appears, choose Generate Data Forms.
Drag the FlightData table from the Data Sources window to the Form1 Design window. A datagrid is created on Form1 with the column names automatically provided.
You can use the Properties settings for this datagrid to set the Dock property to Bottom.
Adding code
On the code page for the application, you will add a string variable that holds the path and name of the database file, code to delete the database file if it already exists, and code to establish a connection to the SQL Server publication, synchronize the data, and create a new local database that contains the published data.
Add the code
From Solution Explorer, right-click Form1 and choose View Code.
In the code page, find the class definition for Form1. Add a string variable and assign it the path and file name for the .sdf file. The data source created by Visual Studio in previous steps expects the database file to reside in the \Program Files\ApplicationName folder, where ApplicationName is the name of the application. For example, if you named your new project SQLMobile, your string variable should be set to
"\Program Files\SQLMobile\sqlmobile.sdf".
The first few lines of your class definition should resemble the following code:
[C#]
public partial class Form1 : System.Windows.Forms.Form { private System.Windows.Forms.MainMenu mainMenu1; string filename = @"\Program Files\SQLMobile\sqlmobile.sdf"; public Form1() { InitializeComponent(); }
[Visual Basic]
Public Class Form1 Dim filename As New String _ ("\Program Files\SQLMobile\sqlmobile.sdf")
Create a new method that will delete the database file if it currently exists. This will make sure that the application loads the latest data every time that it runs. The method should be named DeleteDB. Your code should resemble the following:
[C#]
private void DeleteDB() { if (System.IO.File.Exists(filename)) { System.IO.File.Delete(filename); } }
[Visual Basic]
Sub DeleteDB() If System.IO.File.Exists(filename) Then System.IO.File.Delete(filename) End If End Sub
Create a new method named Sync that performs synchronization. To do this, you will use the code you copied from the New Publication Wizard in a previous step. When you paste the code, you must make two changes to the code:
Change the SubscriberConnectionString value so that it points to the correct path and file name, as specified in the file name variable.
Change the AddOption value from ExistingDatabase to CreateDatabase.
When complete, your Sync method should resemble the following:
[C#]
private void Sync() { SqlCeReplication repl = (SqlCeException e) { MessageBox.Show(e.ToString()); } }
[Visual Basic]
Sub Sync() Dim repl As err as SqlCeException MessageBox.Show(err.ToString) end tryEnd Sub
Finally, add code to the beginning of the Form1_Load event handler that calls the two methods that you recently created. Your Form1_Load event handler should resemble the following:
[C#]
private void Form1_Load(object sender, EventArgs e) { DeleteDB(); Sync(); // TODO: Delete this line of code. this.flightDataTableAdapter.Fill(this.sqlmobileDataSet.FlightData); // TODO: Delete this line of code. this.membershipDataTableAdapter.Fill(this.sqlmobileDataSet.MembershipData); }
[Visual Basic]
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load DeleteDB() Sync() 'TODO: Delete this line of code. Me.FlightDataTableAdapter.Fill(Me.SqlmobileDataSet.FlightData) 'TODO: Delete this line of code ... Me.MembershipDataTableAdapter.Fill(Me.SqlmobileDataSet.MembershipData) End Sub
Deploy and Test the Application
Deploy the application
From the Debug menu, choose Start Debugging.
If the Deploy dialog box is displayed, choose Pocket PC 2003 SE Emulator, and then click Deploy.
The emulator opens in a new window. The first time that you deploy the application to the emulator, the .NET Compact Framework and SQL Server Compact Edition are installed. This might take several minutes. When they are installed, your application is installed and runs.
Your application loads and displays the two datagrids. When you click a value in the MembershipData datagrid, the data in the FlightData datagrid updates automatically.
Close the application, and in Visual Studio, from the Debug menu, click Stop Debugging.
See Also
Concepts
Securing Databases (SQL Server Compact Edition)
Help and Information
Getting SQL Server Compact Edition Assistance | https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-2005/ms171908(v=sql.90) | CC-MAIN-2019-13 | refinedweb | 3,739 | 56.25 |
psoc 3 kit3 integrated with qt, to send data from psoc 3 to qt | Cypress Semiconductor
psoc 3 kit3 integrated with qt, to send data from psoc 3 to qt
Hello,
i m playing with psoc3 with qt integration. i m trying to send a data from psoc 3 to qt, but the problem where i m stuck is, in Qt while receiving data from usb using libusb_blucktransfer, i get a error code -5(error not found).
when i debugged it, found that endPoint IN i m setting in qt is 0x01, but when i cross check the endpoint details in linx machine using "lsusb -v" i see that the End point IN for usb is 0x81,
so changed the Endpoint IN while receiving data from psoc 3 to Qt via libusb_bluck_transfer, the application hangs
can some one please help me out with this,
code snippet for psoc 3 is as shown below
#include <device.h>
#define IN_EP (0x01u)
#define OUT_EP (0x02u)
#define BUF_SIZE (0x05u)
uint8 buffer[BUF_SIZE];
uint8 length;
/*******************************************************************************
* Function Name: main
********************************************************************************
*
* Summary:
* Wraps the OUT data coming from the host back to the host on a subsequent IN.
*
* Parameters:
* None.
*
* Return:
* None.
*
*******************************************************************************/
void main()
{
/* Enable Global Interrupts */
CyGlobalIntEnable;
/* Start USBFS Operation with 3V operation */
USBFS_1_Start(0u, USBFS_1_3V_OPERATION);
/* Wait for Device to enumerate */
while(USBFS_1_GetConfiguration() != 0u);
/* Enumeration is done, enable OUT endpoint for receive data from Host */
USBFS_1_EnableOutEP(OUT_EP);
while(1)
{
/* Check that configuration is changed */
if(USBFS_1_IsConfigurationChanged() != 0u)
{
/* Re-enable endpoint when device is configured */
if(USBFS_1_GetConfiguration() != 0u)
{
USBFS_1_EnableOutEP(OUT_EP);
}
}
/* Check for data received */
if(USBFS_1_GetEPState(IN_EP) == USBFS_1_IN_BUFFER_EMPTY)
{
buffer[0] = 'a', buffer[1] = 'b', buffer[2] = 'c', buffer[3] = 'd',buffer[4] = '\0';
/* Load the IN buffer */
USBFS_1_LoadInEP(IN_EP, buffer, length);
}
}
}
/* [] END OF FILE */
In QT, first i open the device using Libusb, get the handel of device and use lbusb_bulk_transfer as shown below
e = libusb_bulk_transfer(handle,0x01,my_string,length,&transferred,0);
if i use endpoint_IN as 0x01, i get an error code of -5 and if i change endpoint IN to 0x81, then the application hangs.
thanks in advance
Hello
I see that you are not assigning any value to 'length', can you try transferring known amount of data and check. Also please let us know if you are using the USBFS in DMA with Automatic memory management mode.
Thanks,
Hima
Hello HIMA, thanks for reply.
I had figure out that, there were few issues in the code, which are listed below
1. Length is empty, and now i m sending length of buffer which is sent
2. In qt application, once libusb bulk transfer is receiving data, need to delay the code for few seconds, i did it for 1 sec and now data is been received by host from psoc
still the issues not seems to be ending, few issues are as follows
1. while sending data from Psoc, IN_ENDPOINT is set to 0x01, mode of transfer from psoc to host is usb, i.e bulk transfer. But while receiving data form host, when i use the same IN_ENDPOINT then the data is not been received, once checked in linux machine found that psoc assigns the default endpoints which start from 0x81. and data seems to be receiving when i use 0x81 endpoint in host application
2. The data which is being received from psoc is jumbled up, totally mixed up
Eg: data sent from psoc to host is "abcdefghij", data received by host from psoc is "defijdbabcd"
Hope that the issue is due to endpoint mismatch
I m newbee to psoc, so please help me out. Also couldn't get you on "DMA with Automatic memory management mode."
what i did to run the project is, download example project form cypress site for usb, modified for my requirements and using it. Please let me know how do i check for Mode.
Thanks again | http://www.cypress.com/forum/psoc-3-known-problems-and-solutions/psoc-3-kit3-integrated-qt-send-data-psoc-3-qt | CC-MAIN-2017-30 | refinedweb | 639 | 51.72 |
Or the super secret language to use for your assignments
Anas Ambri
November 2014
Currently working at Guestful as mobile developer
Also, 6th year COEN student
(yes, it's been a while)
For these slides:
Can be learned in a holiday
Perfect for assignments
AI class
CS Games
Multi-purpose
Xkcd
import os os.system('"sudo make_sandwich"')
Interpreted
Dynamic
Cake and cherry on the cake
name = "Michael" #Most used male name in Canada in 1990 print "\n".join(map(lambda x: "Happy Birthday to " + ("you" if x != 2 else name),range(4)))
Write a program that prints the numbers from 1 to 100. But for multiples of 3 print “Fizz” instead of the number and for the multiples of 5 print “Buzz”. For numbers which are multiples of both 3 and 5 print “FizzBuzz”.
For the one guy who can cure Cancer with Python: do it without if-conditionals
Create a class named `Insultor` that has a method `insult` that returns an insult.
An insult is the concatenation of three strings, selected from a list that we pass when we construct the object
Improvements
input = raw_input("Enter another insult word. Otherwise press enter") while(input != "\n"): # Do something with input input = raw_input("Enter another insult word. Otherwise press enter") import random print random.randint(0,9)
Learn Python the hard way
Try the Python official tutorial
Attend SCS Intermediate Python
Tweet questions @AnasAmbri
(Or don't, ain't gonna tell ya what to do')
Or just go home | http://slides.com/anasambri/intro_python_concordia/embed | CC-MAIN-2021-39 | refinedweb | 248 | 60.45 |
Having clear and processed images or videos is very important in any computer vision task. There can be various kinds of unwanted effects and pixels present in images that affect the results of modelling with such images. Noise is also a kind of unwanted information that can harm the information present in the data, so we are required to deal with it. In this article, we are going to see how we can remove noise from the image data using an encoder-decoder model. We will go through two approaches of denoising with encoder-decoder, one with dense layers and one with convolutional layers. The major points to be covered in this article are listed below.
Table of Contents
THE BELAMY
Sign up for your weekly dose of what's up in emerging technology.
- What is Noise?
- Encoder decoder with Dense layers
- Data preparation
- Model preparation
- Model compiling and training
- Model Validation
- Encoder decoder with convolution layers
- Model preparation
- Model compiling and training
- Model Validation
Let us begin the discussion by understanding the noise in images.
What is Noise?
In image data or in a particular image noise can be defined as the pixel values that are in excess in the image and unnecessary. These pixel values are responsible for bad visualization of the image and in many of the tasks they can cause the loss of the information from the image. We can categorize the noise into two types:
- Impulse noise: When pixels of the images are completely different from the pixels which are present in the surrounding in a similar image we can say that the pixels are impulse noise. There can be two types of impulse noise
- Salt-and-pepper impulse noise (SPIN)
- Random valued impulse noise (RVIN)
- Additive White Gaussian Noise: This type of noise can be defined as the changes in the overall pixels of the image in a small amount.
From the above, we can say that the noise is the changes in the pixel values and when the changes occur it can be caused by the loss of information. In such a scenario it becomes very necessary to remove the noise from the images or more simply recover the image from the noise effects. In this article, we will see how we can do the denoising of the images using the neural network.
Denoising by Deep Artificial Neural Network
This type of neural network can be considered as the network for unsupervised learning which can be trained for copying from input to output. When working with the image data this type of network can be used to downsample the image in lower dimension and after downsampling, a similar model resamples the image to its original format. In this context, we can define the work of encoders and decoders in the following way:
- Encoder: In the network, the work of the encoder is to encode the data in its lower dimension of downsampling the data.
- Decoder: The work of the decoder in the network is to upsample the data or make the data of higher dimension from the lower dimension.
The below image is a representation of the work from the encoder-decoder network.
To start this project we are required to import some of the libraries so let’s start the implementation with importing libraries.
Importing libraries:
import numpy import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras import layers, models from PIL import ImageFont import visualkeras
Note: we are using visualkeras library which can be used for visualization of the models made by using Keras and Keras from TensorFlow. For more information about the visualization of neural networks, the reader can go through this article.
Data Preparation
In the procedure, we will be using the MNIST dataset which is mainly for classification and consists of 60000 images of size 28×28 of 10 digits. More information about the dataset can be read from this link.
(X_train, y_train), (X_test, y_test) = keras.datasets.mnist.load_data()
Since in the procedure we are dealing with the noise of the image so we don’t require the dependent variable of the dataset. Let’s visualize the dataset.
plt.figure(figsize=(20, 4)) print("Train images") for i in range(10,20,1): plt.subplot(2, 10, i+1) plt.imshow(X_train[i,:,:], cmap='gray') #plt.title("Test Images with Noise") plt.show()
Output:
Here we can see the image in the dataset has the digits on the image but we can say that the noise in the image is lower. So we are required to add some pixels to the images so that we can define them as noise.
Also to work with the network we are required to make the dimension of the image in the form of a 2-D array. Before this, we can check the dimension of the data that we are using.
print(X_train.shape) print(X_test.shape)
Output:
Here we can see that the shape of the dataset is in the form of the 3-D array where 28 x 28 is the image size. To make it a 2-d array we can multiply the second and third dimensions and replace the image size with the multiplication.
num_pixels = 28*28 X_train = X_train.reshape(60000, num_pixels).astype('float32') X_test = X_test.reshape(10000, num_pixels).astype('float32')
Let’s check for the shape again:
print("train set", X_train.shape) print("test set", X_test.shape)
Output:
As we have discussed that the noise level is lower so we can add noise to the images using the following lines of codes:
noise_level = 0.5 x_noisy_train = X_train + noise_level * numpy.random.normal(loc=0.0, scale=1.0, size=X_train.shape) x_noisy_test = X_test + noise_level * numpy.random.normal(loc=0.0, scale=1.0, size=X_test.shape) x_noisy_train = numpy.clip(x_noisy_train, 0., 1.) x_noisy_test = numpy.clip(x_noisy_test, 0., 1.)
Let’s check how the images will look like after adding the noise.
x_noisy_train_V = numpy.reshape(x_noisy_train, (-1,28,28)) *255 plt.figure(figsize=(20, 4)) print("Images with Noise") for i in range(10,20,1): plt.subplot(2, 10, i+1) plt.imshow(x_noisy_train[i,:,:], cmap='gray') plt.title("Image with Noise") plt.show()
Output:
Here we can see that we have added noise to the images.
Model Preparation
Now we have images with noise and we can start modelling an encoder-decoder model which can help us in reducing the noise of the images.
# create model from keras.models import Sequential from keras.layers import Dense enco_deco = Sequential() # Encoder enco_deco.add(Dense(500, input_dim=num_pixels, activation='relu')) enco_deco.add(Dense(300, activation='relu')) enco_deco.add(Dense(300, activation='relu')) enco_deco.add(Dense(100, activation='relu')) #decoder enco_deco.add(Dense(300, activation='relu')) enco_deco.add(Dense(500, activation='relu')) enco_deco.add(Dense(784, activation='sigmoid'))
Output:
Here in the visualization, we can see how the size of the layers is changing, and somewhere it is similar to the image which we have used in the introduction of the encoder-decoder model.
We can also check it in the summary of the model.
enco_deco.summary()
Output:
Here we can also see in the parameters that they are changing towards the lower side and again they have increased at the last. As we have discussed in the case of the image the encoder-decoder model first downsample the data and then up-samples the data to match the size of the input.
Model Compiling and Training
Now we can compile and train the models. Here in this example, I am using the adam optimizer and means squared error as the validation loss in the compilation of the model.
# Compile the enco_deco enco_deco.compile(loss='mean_squared_error', optimizer='adam')
After compiling we can train our model by fitting the data that we have prepared. We are using 5 epochs and a batch size of 200 for training the model.
# Training enco_deco enco_deco.fit(x_noisy_train, X_train, validation_data=(x_noisy_test, X_test), epochs=5, batch_size=200)
Output:
Model Validation
As we can see that we have trained the model in that section we will look at the workability of the model. By looking at the model training report we can say that losses in the model are lower so we can hope that the model will work fine.
Let’s predict with the test data.
predictions = enco_deco.predict(x_noisy_test) print("prediction set", predictions.shape)
Output:
Here we can see that the shape of the data is the same but we are required to check on the visualization of the images in the prediction set. We can perform this using the following lines of code.
X_test = numpy.reshape(X_test, (10000,28,28)) *255 plt.figure(figsize=(20, 4)) print("Train images") for i in range(5,10,1): plt.subplot(2, 10, i+1) plt.imshow(X_test[i,:,:], cmap='gray')() prediction = numpy.reshape(predictions, (10000,28,28)) *255 plt.figure(figsize=(20, 4)) for i in range(5,10,1): plt.subplot(2, 10, i+1) plt.imshow(prediction[i,:,:], cmap='gray') plt.title("recoverd Images") plt.show()
Output:
Here we can see all the images from their original to their recovered form. We can also make an encoder-decoder model with convolution and pooling layer lets try this also
Encoder-Decoder with Convolution Layers
convolutional layers provide various features to perform different tasks of image processing and using convolutional layers and pooling layers downsample the height and width of the input where transposed convolution layers can be used for upsampling or resampling the data. To know more about the convolutional layer, readers can follow this article. Let’s start with the implementation of the model consisting of convolution layers.
Importing the layers:
from tensorflow.keras.models import Model from keras.layers import Conv2D, Conv2DTranspose, MaxPooling2D
Model preparation
in_shape = layers.Input(shape=(28, 28, 1)) # Encoder layer = Conv2D(32, (3, 3), activation="relu", padding="same")(in_shape) layer = MaxPooling2D((2, 2), padding="same")(layer) layer = Conv2D(32, (3, 3), activation="relu", padding="same")(layer) layer = MaxPooling2D((2, 2), padding="same")(layer) # Decoder layer = Conv2DTranspose(32, (3, 3), strides=2, activation="relu", padding="same")(layer) layer = Conv2DTranspose(32, (3, 3), strides=2, activation="relu", padding="same")(layer) layer = Conv2D(1, (3, 3), activation="sigmoid", padding="same")(layer) # ecoder decoder autoencoder = Model(in_shape, layer)
Output:
Here we can see that using the models with convolutional layers we can use more variations in the dimensions. let’s fit the model in the data with noise.
Model Compiling and Training
convomodel.compile(optimizer="adam", loss="binary_crossentropy")
Training the model on noisy data.
convomodel.fit(x_noisy_train, X_train, validation_data=(x_noisy_test, X_test), epochs=5, batch_size=200)
Output:
Model Validation
predictions = convomodel.predict(x_noisy_test)
Checking the shape of the predictions.
print("prediction set", predictions.shape)
Output:
Now we can visualize both of the predictions or recovery images from this approach
X_test = numpy.reshape(X_test, (10000,28,28)) *255 plt.figure(figsize=(20, 4)) for i in range(5,10,1): plt.subplot(2, 10, i+1) plt.imshow(X_test[i,:,:], cmap='gray') plt.title("original")() predict = numpy.reshape(predictions, (10000,28,28)) *255 plt.figure(figsize=(20, 4)) for i in range(5,10,1): plt.subplot(2, 10, i+1) plt.imshow(predict[i,:,:], cmap='gray') plt.title("recoverd Images") plt.show()
Output:
Here we can see that we have a clearer image than the first used encoder-decoder layer where all the layers were flattened layers.
Final Words
In the article, we have seen an overview of noise along with denoising approaches. We could understand how we can remove noise from the image using the deep neural network, where we have applied two approaches of neural network using dense layers and using convolutional layers.
References: | https://analyticsindiamag.com/hands-on-guide-to-image-denoising-using-encoder-decoder-model/ | CC-MAIN-2022-40 | refinedweb | 1,945 | 57.37 |
So using the code below worked for me.
using System.Web.Hosting;
public List<string> GetGroupNames(string userName)
{
var result = new List<string>();
using (HostingEnvironment.Impersonate())
{
using (PrincipalContext pc = new
PrincipalContext(ContextType.Domain, "NPC"))
{
using (PrincipalSearchResult<Principal> src =
UserPrincipal.FindByIdentity(pc, userName).GetGroups(pc))
{
src.ToList().ForEach(sr =>
result.Add(sr.SamAccountName));
}
}
return result;
}
}
As far as I can understand the Thread.CurrentPrincipal contains the
information of conditions the thread has been started with, including the
WindowsIdentity. That's why Thread.CurrentPrincipal.Identity.Name returns
the name of User who started the thread.
To the contrary WindowsIdentity.GetCurrent() Returns a WindowsIdentity
object that represents the current Windows user, which has been changed via
Impersonation.
I'm not 100% sure about it, but that's how I think it works.
Why you care about user gets an access token? With that token, only data
belong to that user are exposed to the app.
For the case the user needs to be identified: now that a backend server is
already there, code flow can be used also. Both user and client are
identified.
For the case the user needn't to be identified: is a proxy in the client's
backend server acceptable? The access token can be hold only be the proxy,
and you can make sure it is a real client.
The only problem is the proxy need to check the origin of each HTTP request
to make sure it comes from the same domain. The JavaScript application can
add some custom headers when sends requests to proxy.
yes this is possible using C# alone.
user does not need to install outlook in client machine.
C# provides a namespace called System.Net.Mail. This has all the classes
required to send a mail from C#. It does not have any dependency with
OutLook.
Have a look below code snippet :
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("jeet@abc.come");
message.Subject = "This is the Subject line";
message.From = new System.Net.Mail.MailAddress("From@XYZ");
message.Body = "This is the message body";
System.Net.Mail.SmtpClient smtp = new
System.Net.Mail.SmtpClient("**yoursmtphost**");
smtp.Send(message);
In place of "yoursmtphost" you can configure the Ip address of machine as
well.
Hope this solves your query. Don't forget to mark
HRESULT: 0x800A03EC is an unknown (to VB.Net) COM error. This usually
happens when Excel throws some error because your input or parameters were
wrong or didn't work.
Also check the error detail carefully. In my case the Data section had an
Item that gave me clues about the exact error thrown by Excel.
@Erwin says: The IIS user account has to have permissions to write the
file. Search for 0x800A03EC in the following article, How to Create Excel
file in ASP.NET C#
I have a few suggestions to improve the performance. Singly they may not
have much impact, but together they should improve overall performance.
Hide Excel (if it isn't already) EXL.Visible = false;. Turn off
Calculation (Application.Calculation = xlCalculationManual, if it
isn't needed) and ScreenUpdating as well.
Use Excel.Workbooks.Worksheets rather than the Sheets collection.
Rather than looping through all the worksheets, try to reference the one
you want, using error-handling to determine if the sheet exists:
Excel.Worksheet worksheet =
(Excel.Worksheet)workbook.Worksheets["SheetName"];
Avoid Select, it is rarely necessary - and slow. Replace,
//Select all cells, and clear the contents
Microsoft.Office.Interop.Excel.Range myAllRange = worksheet.Cells;
myAllRange.Select();
myAl
Please note that I ended up solving the problem by manually copying the
data over into a new Excel file and importing that file--I'm still not sure
what exactly was wrong with the original Excel file. Thank you to everyone
for your suggestions.
(converted from comment to answer per request from another user)
When you got your client ID from the API console, did you pick "Installed
application" as the application type? The term NON_NATIVE is not appearing
in Chromium Code Search, which suggests it's a server error, which suggests
it's telling you that you created the client ID incorrectly.
JavaScript now has WebRTC where two clients can communicate peer-to-peer,
this would be a scenario where clients can generate and use their own
"secret".
There are some cases where client -> server could be usable as well. If
your server was "dynamically" serving the JavaScript then it could insert a
"secret" based on the clients current session/login. Assuming you are using
HTTPS (if not there could be a man in the middle slurping up the "secret")
then it's not unreasonable to assume that communication to the server
signed with that specific "secret" (even over unsecured HTTP) belongs to
only that client..
This is a known bug in Wine.
You can read more here:
You may want to look into a HiLo pattern, or just use Guid.NewGuid()
instead of incrementing.
See: HiLO for the Entity Framework
What's the Hi/Lo algorithm?.
When you enable 'Attribute Profile' at the service provider (SP)
registration time in Identity Server 4.5.0 (IS), a unique 'Consumer Index'
will be generated, and the subsequent SAML requests should contain that
value in order IS to send the user attributes in the responses.
However, if you want to get the attributes without sending that index
value, you can enable "Include Attributes in the Response Always" at SP
registration time. This option is available in IS 4.5.0 GA release..
There are 2 problems with your approach:
You are trying to impersonate a remote machine account on a local machine;
this won't work. The credentials of a machine account can only be
validated by that machine. In addition, that account has no rights on the
local machine, so it doesn't really make sense to impersonate it. You need
to impersonate a domain account. When you use a tool like putty, the
credentials are sent to the remote machine and not validated by the local
machine. This is why you can use a machine account of the remote machine.
You need to give proper paths for the files. Nowhere do you indicate that
these files are on the remote machine. Use something like
"\machinec$path ofile".
The details on what are going to work or not will depend on your network
and OS, whic
First, a word about responsibility. It's our responsibility as developers
to inform those that we develop for of potential pitfalls and ethical
issues they may be setting themselves up for. Simply giving them what they
ask for is not always the right thing to do. In this case, browsing the
site as another user can reveal sensitive information to others, and
violate user privacy. It can also violate federal law (or law in whatever
country you are in) in some cases (particularly when Health information is
involved).
That doesn't even get into the issues with auditing accuracy. How can you
be certain user X actually logged in at this given time if they can be
impersonated by another? What if there's a purchase on their credit card?
How can you legally guarantee it was them that did it
If it's failing here, FileInfo[] files = dir.GetFiles();, chances are the
account you impersonated doesn't have permission to the dir path on the
Win7 machine where this is running, make sure that this account has access
to the source path first, the impersonation code seems fine
You can check the IS documentation on how to connect to external LDAP
server .
If you have successfully connected to external store, then authentication
will happen against that usertore..
What is the issue you faced when you authenticate with the external LDAP
user store?
You can file a bug report..
If you want to use user name and password for impersonation you have to
store it somewhere.
But here is a list of things you can try:
Don't store credentials, but ask user to type them in. This will remove
maintenance headache from you (user left company, password expired etc)
Store credentials in web config using encryption
Use Windows impersonation where currently logged in user passes a security
descriptor automagically.
As this answer explained; the impersonation in the web.config overrides the
identity in the application pool.
In my opinion there is a fine explanation here which one to use:
impersonation or application pool
No, this is not possible. EXECUTE AS is mainly used with SP's, but you can
use them a bit more widely. From TechNet:
In SQL Server you can define the execution context of the following
user-defined modules: functions (except inline table-valued
functions), procedures, queues, and triggers.
...
Functions (except inline table-valued functions), Stored Procedures,
and DML Triggers { EXEC | EXECUTE } AS { CALLER | SELF | OWNER |
'user_name' }
DDL Triggers with Database Scope { EXEC | EXECUTE } AS { CALLER | SELF
| 'user_name' }
DDL Triggers with Server Scope and logon triggers { EXEC | EXECUTE }
AS { CALLER | SELF | 'login_name' }
Queues { EXEC | EXECUTE } AS { SELF | OWNER | 'user_name' }
However, you have some options here:
create GET-SP's that
Thanks to input from Harry Johnston (in comments attached to the question)
and Phil Harding (in separate communication) I was able to determine that
SQL Server connection pooling was the culprit here. Since pooling is
determined by uniqueness of the connection string, by slightly varying the
connection string (e.g. reversing order of parameters within, or even just
adding a space on the end) I then observed the behaviors I expected.
===== TEST WITH SAME CONN STRING: True
BEGIN impersonation
Local user: MyDomainmsorens
DB reports: MyDomain estuser
END impersonation
Local user: MyDomainmsorens
DB reports: MyDomain estuser <<<<< still impersonating !!
===== TEST WITH SAME CONN STRING: False
BEGIN impersonation
Local user: MyDomainmsorens
DB reports: MyDomain estuser
END imper
Try changing the way you reference your local server. If your application
settings are (local)instance_name update it to (127.0.0.1)instance_name.
I’ve had similar performance issue in the past and this fixed it. Note
that you’ll need to add this IP address as one of the listeners in SQL
Server Configuration manager under Network configuration -> TCP/IP
The answer, I am ashamed to say, was right in front of me all along. The
LogonUser API states:
This logon type allows the caller to clone its current token and specify
new credentials for outbound connections. The new logon session has the
same local identifier but uses different credentials for other network
connections. [emphasis mine]
But my database is on the same machine as my running program so by
definition it will not show the new credentials! I am confident the
impersonation will work correctly with LOGON32_LOGON_NEW_CREDENTIALS once I
move my database to a different box. Sigh.
Your problem come from the connection string. The "Network Library =
dbmssocn" in connection string will make client attempting to connect to
SQL server on the UDP port 1434 rather than the TCP port 1433. You remove
the "Network Library = dbmssocn" from the your application's connection
string the application will connect to SQL server successfully.
I never worked with services you have mentioned but I hope, following stuff
will help you in some way.
I used kernal32.dll and advapi32.dll to impersonate user as under:
Imports System.Security.Principal
Imports System.Runtime.InteropServices
Public Class UserImpersonation
<DllImport("advapi32.dll")> _
Public Shared Function LogonUserA
End Function
<DllImport("advapi32.dll", CharSet:=CharSet.Auto,
SetLastError:=True)> _
Public Shared Function DuplicateToken(ByVal hToken As IntPtr, ByVal
impersonationLevel As Integer, ByRef hNewToken As IntPtr) As Integer
End Function
<DllImport("
getHardwareAddress requires NetPermission("getNetworkInformation").
Therefore a applet jar needs to be signed.
I tried to fix 0.9.0 by:
1) Install python-dev (I noticed an error: missing python.h when building
thrift)
sudo apt-get install python-dev
2) Building thrift with:
./configure CPPFLAGS="-DHAVE_INTTYPES_H -DHAVE_NETINET_IN_H"
Still the same errors, so I decided to checkout, build and install the
latest thrift (HEAD version 6f2a5037105ccad05eb84ec0a60da3389c85eb3f in
git).
With the latest thrift, there were no errors building the cpp client.
However, running a.out returned an error:
./a.out: error while loading shared libraries: libthrift-1.0.0-dev.so:
cannot open
shared object file: No such file or directory
Setting LD_LIBRARY_PATH to the newly built thrift library fixed this:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$THRIFT_SRC/lib/cpp/.libs/
Use SET IDENTITY_INSERT
().
SET IDENTITY_INSERT TableName ON;
-- Insert Data.
SET IDENTITY_INSERT TableName OFF;
The first suggestion is that you do not have permissions to access the
network directory, or the file in question. These could be access
permissions or copy permissions (or both).
Check that you have permissions to both of these.
At this point in time, I've not been able to find information about
impersonation and how it interacts with win32 dlls/apis, however, I do know
the following:
1) if the entire process is running under a user with access to the remote
folder the ini file lives in, then GetPrivateProfileSectionNames works as
desired
2) if GetPrivateProfileSectionNames is called inside an impersonation
block, then it does not work as desired
3) if a file stream is opened, and the ini file is copied local, then
GetPrivateProfileSectionNames is used on the local ini file, then
GetPrivateProfileSectionNames works as desired, and the file stream is
allowed access to the remote file.
I speculate, based on results, that the win32 api call
GetPrivateProfileSectionNames is not getting passed the impersonation con
Your question is not that specific. Still I think you can keep a webservice
to download the server configuration details. and store it in Coredata.
Upon user signup you can download the configuration details.
Edit:
Try the method as Mark Weller said. Check Implementing an iOS Settings
Bundle in the doc.
If you want to minimize the user interaction, and want to automate the
build process. Please check cisimple
The simplest solution is for the launching application could make a copy of
its own security token and allow the child process to inherit the handle to
it. The handle value can be passed on the command line or via an
environment variable.
Note that this effectively gives User B unrestricted access to user A's
account..
Could it be the case that Google started expecting certificate from the
client? If yes, what should we do?
If i understand you right and google truly need certificates, you should
use cryptoprovider and make signatures by stunnel.
Maybe smth wrong with your code ? This settings are works for me
public HttpClient getNewHttpClient() {
try {
KeyStore trustStore =
KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
Yuo You seem to be asking two questions here
You are concerned about managing a collection in a thread safe manner
You are concerned about trying to send data over a socket when the other
party is disconnected.
To answer your concerns given the limited information
If you have multiple threads accessing your list then you need a thread
safe implementation. You can roll one yourself using lock etc or use one of
the new .NET ones.
Regarding you comments about "local" lists, the simple answer is do not
make local copies unless you want to run the risk of having stale data. Use
a thread safe list and also enumerate through it directly. If you use LINQ
expressions then you can make complex queries without needing to make any
copies of y | http://www.w3hello.com/questions/-Issue-with-ASP-NET-client-COM-Interop-and-Identity-impersonation- | CC-MAIN-2018-17 | refinedweb | 2,581 | 56.15 |
Greetings! In my mobile game, I connect to my game server to get a list of X characters and then once they are loaded, I instantiate them into my scene. Each of the characters has a radial menu of actions they can take that activates when you touch and hold. When you release, the menu goes away. While the menu is displaying, you can move your touch onto one of the menu options and release, which will choose that option. I have implemented the radial menu based on the following YouTube tutorial: -- the only thing I've added is code to take the selected action, which is not covered in the tutorial.
Everything works perfect in the Unity Editor. However, when I run it on my Android device, I run into a "small" problem. When I release on a menu item, the action never occurs. After thorough debugging, it looks like the issue is that the OnPointerExit handler which is used to deselect the button gets called when I lift my finger (remove the touch) and not just when I move my touch off of the button. So, basically, choosing a menu option is acting the same as deselecting it.
Here's the code:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using System.Collections;
public class RadialButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {
public Image circle;
public Image icon;
public string title;
public Interactable.InteractableAction action;
public RadialMenu myMenu;
public float speed = 8f;
Color defaultColor;
public void Anim() {
StartCoroutine (AnimateButtonIn ());
}
IEnumerator AnimateButtonIn() {
transform.localScale = Vector3.zero;
float timer = 0f;
while (timer < (1 / speed)) {
timer += Time.deltaTime;
transform.localScale = Vector3.one * timer * speed;
yield return null;
}
transform.localScale = Vector3.one;
}
public void OnPointerEnter (PointerEventData eventData)
{
myMenu.selected = this;
defaultColor = circle.color;
circle.color = Color.white;
}
public void OnPointerExit (PointerEventData eventData)
{
myMenu.selected = null;
circle.color = defaultColor;
}
}
I have tried to implemented a separate touch system using preprocessor directives, but that has been a colossal failure. Any elegant solution to this? Is it possible on touch ended to prevent the on pointer exit handler from processing temporarily or something cheeky?
$$anonymous$$aybe using IPointerUpHandler ins$$anonymous$$d of or in addition to IPointerExitHandler works.
Answer by justindz
·
Dec 11, 2016 at 09:17 AM
Unfortunately, IPointerUpHandler did nothing (quite literally). I think it requires a collider, possibly. The documentation is pretty sparse. I found an elegant solution, however:
public void OnPointerExit (PointerEventData eventData)
{
if (Input.touchSupported) {
if (Input.touches [0].phase == TouchPhase.Ended) {
myMenu.selected = this;
} else {
myMenu.selected = null;
}
} else {
myMenu.selected = null;
}
circle.color = defaultColor;
}
Basically, we check if we're on a touch system and if the finger has been lifted to set the action. If we exit for any reason other than the finger lifting, we deselect. On a non-touch system, we always deselect, because the exit handler only gets called when we mouse off and not when we release the mouse. In all cases, we reset the button destroy object by touch?
2
Answers
Avoid touch input when pressing the "Pause" button
1
Answer
[SOLVED] Touch Controls Not Responsive
1
Answer
Wp8 an Android
0
Answers
How to change Unity2D aspect ratio with scenes?
1
Answer
EnterpriseSocial Q&A | https://answers.unity.com/questions/1279096/onpointerexit-issue-w-radial-menu-on-android.html | CC-MAIN-2021-17 | refinedweb | 531 | 50.12 |
Local jed settings
19 April 2013
Linux, MacOSX
(if you're wondering what you're doing here, jed is a hardcore text based editor for programmers)
Thanks to fellow Jed user and hacker Ullrich Horlacher I can now have local settings per directory.
I personally prefer 2 spaces in my Javascript. And thankfully most projects I work on agrees with that standard. However, I have one Mozilla project I work on which uses 4 spaces for indentation. So, what I've had to get used to to is to edit my
~/.jedrc every time I switch to work on that particular project. I change:
variable C_INDENT = 2; to
variable C_INDENT = 4; and then back again when switching to another project.
No more of that. Now I just add a file into the project root like this:
$ cd dev/airmozilla $ cat .jed.sl variable C_INDENT = 4;
And whenever I work on any file in that tree it applies the local override setting.
Here's how you can do that too:
First, put this code into your
<your jed lib>/defaults.sl: (on my OSX, the jed lib is
/usr/local/Cellar/jed/0.99-19/jed/lib/)
% load .jed.sl from current or parent directories % but only if the user is the same define load_local_config() { variable dir = getcwd(); variable uid = getuid; variable jsl,st; while (dir != "/" and strlen(dir) > 1) { st = stat_file(dir); if (st == NULL) return; if (st.st_uid != uid) return; jsl = dir + "/.jed.sl"; st = stat_file(jsl); if (st != NULL) { if (st.st_uid == uid) { pop(evalfile(jsl)); return; } } dir = path_dirname(dir); } }
Then add this to the bottom of your
~/.jedrc:
define startup_hook() { load_local_config(); % .jed.sl }
Now, go into a directory where you want to make local settings, create a file called
.jed.sl and fill it to your hearts content!
Careful with your assertRaises() and inheritance of exceptions
10 April 2013
Python
This().
Recruit.
"Did you mean this domain?" Auto-correction for the browser's address bar
05 April 2013
Mozilla
People:
Never put external Javascript in the <head>
02 April 2013:
premailer now honours specificity
21 March 2013
Python
Thanks!
HTML whitespace "compression" - don't bother!
11 March 2013.
django-fancy-cache with or without stats
11 March 2013
Python, Django
If.
This site is now 100% inline CSS and no bytes are wasted
05 March 2013.
Welcome to the world django-fancy-cache!
01 March 2013
Python, Django
A Django cache_page on steroids
Django ships with an awesome view decorator called cache_page which is awesome. But a bit basic too.
What it does is that it stores the whole view response in memcache and the key to it is the URL it was called with including any query string. All you have to do is specify the length of the cache timeout and it just works.
Now, it's got some shortcomings which
django-fancy-cache upgrades. These "steroids" are:
- Ability to override the key prefix with a callable.
- Ability to remember every URL that was cached so you can do invalidation by a URL pattern.
- Ability to modify the response before it's stored in the cache.
- Ability to ignore certain query string parameters that don't actually affect the view but does yield a different cache key.
- Ability to serve from cache but always do one last modification to the response.
- Incrementing counter of every hit and miss to satisfy your statistical curiosity needs.
The documentation is here:
You can see it in a real world implementation by seeing how it's used on my blog here. You basically use it like this::
from fancy_cache import cache_page @cache_page(60 * 60) def myview(request): ... return render(request, 'template.html', stuff)
What I'm doing with it here on my blog is that I make the full use of caching on each blog post but as soon as a new comment is posted, I wipe the cache by basically creating a new key prefix. That means that pages are never cache stale but the views never have to generate the same content more than once.
I'm also using
django-fancy-cache to do some optimizations on the output before it's stored in cache. | http://www.peterbe.com/?page=3 | CC-MAIN-2014-10 | refinedweb | 698 | 65.62 |
I use code::blocks as an IDE but now i want to create a .dll file. I have followed this tutorial however it is for VC++.
TUTORIAL:
I am strugeling becuase I am used to creating .dlls in C#. They are so easy. You just create a new library project. Write your code eg:
// The .dll version using System; namespace SomeName { class Class1 { public int add(int x, int y) { return x + y; } } } // The real "runable" version using System; namespace AgainSomeName { class Class2 { public void Main(string[] args) { SomeName.Class1.add(5, 3); } } }
Thats it. All you have to do now is right click on your project in your IDE and then say add reference and add the .dll file. Easy usable. Isnt there a way to do it like as easy as that. Without having to use all those #ifdef, #endif, #else and static __declspec(dllexport) words. Easy like you do it in C#?
Oh and also, if i use Visual studio C++ exspress can i then only create programs for the .NET when i use that IDE? or whill the programs work for computers without the .NET alsong as i just dont include .NET header files?
Edited 4 Years Ago by MasterHacker110: Type error | https://www.daniweb.com/programming/software-development/threads/432352/how-to-create-a-dll-in-c | CC-MAIN-2017-04 | refinedweb | 206 | 86.2 |
The problem Combinations Leetcode Solution provides us with two integers, n, and k. We are told to generate all the sequences that have k elements picked out of n elements from 1 to n. We return these sequences as an array. Let us go through a few examples to get a better understanding of the problem.
n = 4, k = 2
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
Explanation: The output shows all the ways of picking k elements out of first n natural numbers. Here, the ordering of the numbers does not matter. Only the collection of numbers matters.
n = 1, k = 1
[[1]]
Explanation: Here, since we have a single element. We are also told to pick a single element. Thus the output is [[1]].
Approach for the Combinations Leetcode Solution
The problem Combinations Leetcode Solution asked us simply to generate all the sequences of picking k elements out of first n natural numbers. So, this is simply generating all the nCk combinations available to pick k elements. Generally, the tasks involving the generation of sequences are solved using recursion. So, we try a recursive approach to the problem. And keep track of a vector that aims to store such combinations.
So, we start with an empty vector. We push an element into it. Then recursively solve a subproblem of picking k-1 elements out of remaining n-1 elements. in this way we keep on reducing the problem until we reach the problem of picking 0 elements. When this happens, we push this temporary vector to our answer. In the end, this answer stores all the sequences of picking k elements out of n elements.
Code for Combinations Leetcode Solution
C++ Code
#include <bits/stdc++.h> using namespace std; void rec(int i, int k, int n, vector<int>& cur, vector<vector<int>>& res){ if(cur.size()==k) { res.push_back(cur); } else { for(int j=i;j<=n;j++) { cur.push_back(j); rec(j+1, k, n, cur, res); cur.pop_back(); } } } vector<vector<int>> combine(int n, int k) { vector<vector<int>> res; vector<int> cur; rec(1, k, n, cur, res); return res; } int main(){ vector<vector<int>> output = combine(4, 2); for(auto singleList: output){ for(auto element: singleList) cout<<element<<" "; cout<<endl; } }
1 2 1 3 1 4 2 3 2 4 3 4
Java Code
import java.util.*; import java.lang.*; import java.io.*; class Main { static List<List<Integer>> res = new ArrayList<List<Integer>>(); public static void rec(int i, int k, int n, ArrayList<Integer> cur){ if(cur.size()==k) { res.add(new ArrayList(cur)); } else { for(int j=i;j<=n;j++) { cur.add(j); rec(j+1, k, n, cur); cur.remove(cur.size()-1); } } } public static List<List<Integer>> combine(int n, int k) { ArrayList<Integer> cur = new ArrayList<Integer>(); rec(1, k, n, cur); return res; } public static void main (String[] args) throws java.lang.Exception{ List<List<Integer>> res = combine(4, 2); System.out.println(res); } }
[[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
Complexity Analysis
Time Complexity
O(k*nCk), here nCk means the binomial coefficient of picking k elements out of n elements.
Space Complexity
O(nCk), as stated above the nCk here refers to the binomial coefficient. | https://www.tutorialcup.com/leetcode-solutions/combinations-leetcode-solution.htm | CC-MAIN-2021-25 | refinedweb | 552 | 57.16 |
Coding Guidelines¶
Introduction¶
We write code for OpenStack charms. Mostly in Python. They say that code is read roughly 20 times more than writing it, and that’s just the process of writing code. Reviewing code and modifying it means that it will be read many, many times. Let’s make it as easy as possible. We’re lucky(!) with Python as the syntax ensures that it roughly always looks the same.
As OpenStack charms are for OpenStack it’s a good idea to adhere to the OpenStack Python coding standard. So first things first:
Read the OpenStack Coding standard.
Read PEP8 (again).
Topics¶
Multiple roots – symlinks¶
Multiple roots with symlinks create issues in charms. This is where, for example, charmhelpers is symlinked into both a hooks and actions subdirectory. This creates a situation where the same modules are loaded into the Python interpreter’s memory twice at two different module paths. This creates problems with testing as depending on the load time ordering it might not be clear which particular module path you’re trying to mock out and which one is first in the module path map.
So only every have ONE root for your python code in a charm. e.g. put it in
/lib and add that to path by
sys.path.append('lib').
Incidentally, if you are mocking out code in charmhelpers in you charms, it’s probably not a good idea. Only mock code in the target object file, rather than an included module.
Install-time vs Load-time vs Runtime code¶
The hooks in charms are effectively short-term running scripts. However, despite being short-lived, the code invoked is often complex with multiple modules being imported which also import other modules.
It’s important to be clear on what is load time code and _runtime_ code. Although there is no actual distinction in Python, it’s useful to think of runtime starting when the following code is reached:
if __name__ == '__main__': do_something()
I.e. the code execution of
do_something() is runtime, with everything
preceding being loadtime.
So why is the distinction useful? Put simply, it’s much harder to test load-time code in comparison to runtime code with respect to mocking. Consider these two fragments:
Bad:
import a.something OUR_CONFIG = { 'some_thing': a.something.config('a-value'), }
Good:
import a.something def get_our_config(): return { 'some_thing': a.something.config('a-value'), }
If performance is an issue (i.e. multiple calls to
config() are expensive)
then either use a
@caching type decorator, or just doing it manually. e.g.
_our_config = None def get_our_config(): if _our_config is None: _our_config = { 'some_thing': a.something.config('a-value'), } return _our_config
In the bad example, in order to mock out the config module we have to do something like:
with patch('a.something.config') as mock_config: import a.something.config
This also relies on this being the _first_ time that module has been imported. Otherwise, the module is already cached and config can’t be mocked out.
Compare this with the good example.
def test_out_config(self): with patch('module.a.something.config') as mock_config: mock_config.return_value = 'thing' x = model.get_out_config()
This brings us to:
CONSTANTS should be simple¶
In the bad example above, the constant
OUR_CONFIG is defined as load-time by
calling
a.something.config(). Thus, in reality, the constant is being
defined at load-time using a runtime function that returns a value - it’s
dynamic.
Don’t:
CONFIG = { 'some_key': config('something'), }
This is actually a function in disguise.
Prefer:
def get_config(): return { 'some_key': config('something'), }
Why?
So that you can mock out
get_config() or
config() at the test run time,
rather than before the module loads. This makes testing easier, more
predictable, and also makes it obvious that it’s not really a constant, but
actually a function which returns a structure that is dynamically generated
from configuration.
And definitely don’t do this at the top level in a file:
CONFIGS = register_configs()
You’ve just created a load time test problem _and_ created a CONSTANT that
isn’t really one. Just use
register_configs() directly in the code and write
register_configs() to be
@cached if performance is an issue.
Decorators¶
There shouldn’t be much need to write a decorator. They definitely should not be used instead of function application or instead of context managers. When they are used it’s preferable that they are orthogonal to the function they are decorating, and don’t change the nature of the function.
functools.wraps(f)¶
If they are used, then they should definitely make use of
functools.wraps to
preserve the function name of the original function and it’s docstring. This
makes stacktraces more readable. e.g.:
def my_decorator(f): functools.wraps(f): def decoration(*args, **kwargs): # do soemthing before the function call? r = f(*args, **kwargs) # do soemthing after the function call? return r return decoration
Mocking out decorators¶
If the decorator’s functionality is orthogonal to the function, then mocking out the decorator shouldn’t be necessary. However, if it isn’t then tweaking how the decorator is written can make it easier to mock out the decorator.
Consider the following code:
@a_decorator("Hello") def some_function(): pass def a_decorator(name): def outer(f): @functools.wraps(f) def inner(*args, **kwargs): # do something before the function r = f(*args, **kwargs) # do something after the function return r return inner return outer
It’s very difficult to test some_function without invoking the decorator, and
equally, it’s difficult to stop the decorator from being applied to the
function without mocking out
@a_decorator before importing the module under
test.
However, with a little tweaking of the decorator we can mock out the decorator without having to jump through hoops:
def a_decorator(name): def outer(f): @functools.wraps(f) def inner(*args, **kwargs): return _inner(name, args, kwargs) return inner return outer def _inner(name, args, kwargs): # do something before the function r = f(*args, **kwargs) # do something afterwards return r
Now, we can easily mock
_inner() after the module has been loaded, thus
changing the function of the decorator _after_ it has been applied.
Import ordering and style¶
Let’s be consistent and ensure that we have the same import ordering and style across all of the charms (and other code) that we release.
Use absolute imports¶
Use absolute imports. In Python 2 code this means also that we should force absolute imports:
from __future__ import absolute_import
We should use absolute imports so that we don’t run into module name clashes across our own modules, nor with system and 3rd party packages. See for more details.
Import ordering¶
Core Python system packages
Third party modules
Local modules
They should be alphabetical order, with a single space between them, and preferably in alphabetical order. If load order is important (and it shouldn’t be!) then that’s the only reason they shouldn’t be in alpha order.
Import Style¶
It’s preferable to import a module rather than an object, class, function or instance from a module.
Prefer:
import module module.function()
over:
from module import function function()
However, if there are good reasons to import from a module, and there is more than one item, then the style is:
from module import ( one_import_per_line, )
Why?
Using
import module; module.function() rather than
from module import
function is preferable because:
with multiple imports, more symbols are being brought into the importing modules namespace.
It’s clearer in the code when an external function is being used, as it is always prefixed by the external module name. This is useful as it makes it more obvious what is happening in the code.
Only patch mocks in the file/module under test¶
A unit test often needs to mock out functions, classes or instances in the file under test. The mocks should _only_ be applied to the file that contains the item that is being tested.
Don’t:
# object.py import something def function_under_test(x): return something.doing(x)
In the unit test file:
test_unit.py:
# test_unit.py def unit_test(): with patch('something.doing') as y: y.return_value = 5 assert function_under_test(3) == 5
Prefer:
# object.py import something def function_under_test(x): return something.doing(x)
In the unit test file:
test_unit.py:
# test_unit.py def unit_test(): with patch('object.something.doing') as y: y.return_value = 5 assert function_under_test(3) == 5
i.e. the thing that is patched is in object.py not in the library file ‘something.py’
Don’t use _underscore_methods outside of the class¶
Underscore methods are supposed to be, by convention, private to the enclosing scope, be that a module or a class. They are used to signal that the method is _private_ even though the privacy can’t be enforced.
Thus don’t do this:
class A(): def _private_method(): pass x = A() x._private_method()
Simply rename the method without the underscore. Otherwise you break the convention and people will not understand how you are using private methods.
Equally, don’t use them in derived classes _either_. A private method is supposed to be private to the class, and not used in derived classes.
Only use list comprehensions when you want the list¶
Don’t:
[do_something_with(thing) for thing in mylist]
Prefer:
for thing in mylist: do_something_with(thing)
Why?
You just created a list and then threw it away. And it’s actually less clear what you are doing. Do use list comprehensions when you actually want a list to do something with.
Avoid C-style dictionary access in loops¶
Don’t:
for key in dictionary: do_something_with(key, dictionary[key])
Prefer:
for key, value in dictionary.items(): do_something_with(key, value)
Why?
Using a list of keys to access a dictionary is less efficient and less obvious
as to what’s happening.
key, value could actually be
config_name and
config_item which means the code is more self-documenting.
Also remember that
dictionary.keys() &
dictionary.values() exist if you
want to explicitly iterate just over the keys or values of a dictionary. Also,
it’s preferable to iterate of
dictionary.keys() rather than
dictionary
because, whilst they do the same thing, it’s not as obvious what is happening.
If performance is an issue (Python2) then
iterkeys() and
itervalues() for
generators, which is the default on Python3.
Prefer tuples to lists¶
Tuples are non malleable lists, and should be used where the list isn’t going to change. They have (slight) performance advantages, but come with a guarantee that the list won’t change - note the objects within the tuple could change, just not their position or reference.
Thus don’t:
if x in ['hello', 'there']: do_something()
Prefer:
if x in ('hello', 'there'): do_something()
However, remember the caveat. A single item tuple literal has to have a trailing comma:
my_tuple = ('item', )
Prefer CONSTANTS to string literals or numbers¶
This is the “No magic numbers” rule. In a lot of the OS charms there is code like:
db = kv() previous_thing = db.get('thing_key', thing)
Prefer:
THING_KEY = 'thing_key' db = kv() previous_thing = db.get(THING_KEY, thing)
Why?
String literals introduce a vector for mistakes. We can’t use the language to help prevent spelling mistakes, nor our tools to do autocompletion, nor use lint to find ‘undefined’ variables. This also means that if you use the same number or string literal more than once in code you should create a constant for that value and use that in code. This includes fixed array accesses, offsets, etc.
Don’t abuse __call__()¶
__call__() is a method that is invoked when
() is invoked on an object –
() on a class invokes
__call__ on the metaclass for the class.
A good example of abuse of
__call__ is the class
HookData() which, to
access the context manager, is invoked as:
with HookData()() as hd: hd.kv.set(...)
The sequence
()() is almost certainly a code smell. There is hidden
behaviour that requires you to go to the class to see what is actually
happening. It would have been more obvious if that method was just called
cm() or
context():
with HookData().context() as hd: hd.kv.set(...)
Don’t use old style string interpolation¶
action_fail("Cannot remove service: %s" % service.host)
Prefer:
action_fail("Cannot remove service: {}".format(service.host))
Why?
It’s the new style, and the old style is deprecated; eventually it will be removed. Plus the new style is way more powerful: keywords, dictionary support, to name but a few.
Docstrings and comments¶
Docstrings and comments are there to inform a reader of the code additional, contextual, information that isn’t readily available by just reading the code. Docstrings can also be used to automatically generate useful documentation for programmers who are using those functions. This is particularly important in the case of a library, but is also very important simply from a maintenance perspective. Being able to look at the docstring for a function and quickly understand the types of the parameters and the return type helps to understand the code much more quickly than hunting through other code trying to understand what types of things might be sent to the function.
In futher, types in docstrings will become part of the linting of the code (as part of PEP8) and so, good practice now, will help with more maintainable code in the future.
Comments are important to help the reader of the code understand what is being implemented, rather than just repeating what the code does. A good comment is minimal and terse, yet still explains the purpose behind a segment of code.
Docstring formats are slightly complicated by whether we are doing Python 2 code, Python 3 code, or a shared library. For Python 2 and Python 2 AND 3 compatible code (e.g. charm-helpers) there is a preferred approach, and for Python 3 only code there is a separate preferred approach.
Python 2 code and Python 2/3 compatible code¶
Python 2 compatible code docstrings are constrained by not being able to have mypy annotations in the code. We don’t really want to add mypy annotations into comments, so we’ve adopted a docstring convention which informs as to what the types are, without being able to actually statically check it.
The main reason for not using mypy compatible comments is that they are fairly ugly. As we are not using, nor plan to use, mypy on Python 2 code, we can do something that is a little more aesthetically pleasing.
Every function exported by a module should have a docstring. Generally, this
means all functions mentioned in
__ALL__ or implicitly those that do not
start with an
_.
The preferred format for documenting parameters and return values is
ReStructuredText (reST) as described:
but with mypy type signatures. Classes will use the
:class:`ClassName`
type declaration so that sphinx can appropriately underline when using autodoc.
The field lists are described here:
An example of an acceptable function docstring is:
def mult(a, b): """Multiple a * b and return the result. :param a: Number :type: Union[int, float] :param b: Number :type: Union[int, float] :returns a * b :rtype: Union[int, float] :raises: ValueError, TypeError if the params are not numbers """ return a * b def some_function(a): """Do something with the FineObject a :param a: a fine object :type: :class:`FineObject` """ do_something_with(a)
Other comments should be used to support the code, but not just re-say what the code is doing.
Python 3 code¶
The situation is a little more complicated for Python 3 code. Ideally, we would just use Python 3.6 mypy annotations, but Xenial only has Python 3.5. This means that some types of annotations aren’t possible. As Xenial is supported until 2021, until that time, all Python 3 mypy annotations will need to be supported on Python 3.5.
This means that PEP-526 can’t be used (Syntax for variable annotations) and PEP-525 (Asynchronous generators) and PEP-530 (comprehensions) are also not possible.
So the minimal preferred docstring format for Python 3 code is the same as Python 2. However, ideally, mypy notations will be used:
def mult(a: Union[int, float], b: Union[int, float]) -> Union[int, float]: """Multiple a * b and return the result""" return a * b def some_function(a: FineObject): """Do something with a FineObject :param: a is used in the context of doing something. """ do_something_with(a)
Note
Because mypy annotations tell you what the types are and this type
information can be checked statically, it means that we don’t have to
specify what the function might raise as an exception, as that would be a
type error. e.g. if at runtime the function
mult(...) was supplied
with an object that had no
* implementation, then the code would raise
an exception. However, linting on fully typed code would prevent this.
Hence we don’t, for function
mult need to provide either a return type
in the docstring, nor a
:raises: line.
In the
some_function(...) we have optionally specified the
:param:
to provide additional information to the docstring for the user. The type
will be provided by
sphinx autodoc.
The end objective with the Python 3 code is to use mypy (or pyre) to statically check the code in the CI server prior to check-ins.
Ensure there’s a comma on the last item of a dictionary¶
This helps when the developer adds an item to a dictionary literal, in that they don’t have to edit the previous line to add a comma. It also means that the review doesn’t indicate that the previous line has changed (due to the addition of a comma).
Prefer:
a_dict = { 'one': 1, 'two': 2, }
over:
a_dict = { 'one': 1, 'two': 2 }
Avoid dynamic default arguments in functions¶
Don’t use a dynamic assignment to a default argument. e.g.
def a(b=[]): b.append('hello') print b In [2]: a() ['hello'] In [3]: a() ['hello', 'hello']
As you can see, the list is only assigned the first time, and thereafter it ‘remember’ the previous values.
Also avoid other default, dynamic, assignments:
def f(): return ['Hello'] def a(b=f()): b.append('there') print b In [3]: a() ['Hello', 'there'] In [4]: a() ['Hello', 'there', 'there']
Instead, prefer:
def a(b=None): if b is None: b = f() b.append('there') print b In [6]: a() ['Hello', 'there'] In [7]: a() ['Hello', 'there']
Why?
Although it can be a handy side-effect for allowing a function to remember previous values, due to a quirk in the interpreter in only assigning the reference once, it may be changed in the future and it hides the intention of the code.
Avoid side effects in Adapters and Contexts¶
Adapters (reactive charms) and Contexts should not alter the unit they are running, i.e. should not have unexpected side effects. Some environment altering side effects do exist in older contexts, however this should not be taken as an indicator that it is acceptable to add more.
Why?
Adapters and Contexts are regulary called via the update status hook to assess whether a charm is ready. If calling the Context or Adapter has unexpected side effects it could interrupt service. See Bug #1605184 for an example of this issue. | https://docs.openstack.org/charm-guide/latest/coding-guidelines.html | CC-MAIN-2019-39 | refinedweb | 3,192 | 63.49 |
Background
In the last post, we saw how we can create nested components in Angular -
We also saw a few other angular things - links creating a new App, using Angular CLI, understanding project structure etc. All the links are in the related links section at the bottom. In this post, I will show you how to pass data from parent component to child component and listen for data to be passed from child to parent.
I am going to continue using previous code example that we have built so far. So if you need additional guidance before we start with this code, look up the previous post that talks about building nested components.
Passing data between the nested component in Angular
At this point, you should have a parent component called NewEmployeeComponent and a child component called SubempComponent. Child component just has a static HTML saying that subcomponent works. And it gets rendered as part of the parent component. All of this works and we saw it in the last post. If you do have a question till here I would recommend to go back and read my previous post -
Now let's add some input and output properties in the child component. Your child component code should look like below -
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-subemp', templateUrl: './subemp.component.html', styleUrls: ['./subemp.component.css'] }) export class SubempComponent implements OnInit { @Input() department:string; @Input() designation:string; @Output() joined:EventEmitter<string>; constructor() { this.joined = new EventEmitter(); } ngOnInit() { console.log("SubempComponent initialized"); } onButtonClick = function(event) { console.log("Button clicked. Emitting now!") this.joined.emit("Joined department " + this.department + " with designation " + this.designation); } }
Notice here that department and designation are two parameters which are input and are of type string. So we would expect the parent component to send it to this child component. Next, we have an output parameter called joined which is an EventEmitter. Parent component which creates this child component can catch and handle this output and we will see how in a moment. Finally, we have a function onButtonClick that actually emits a string saying that the button was clicked with the particular designation and department. We will now see when this function will get called. But essentially once this function is called we emit the string which the parent component can intercept and handle.
Now let's see child components HTML code -
<h1>This is sub components heading</h1> <p> Yay! subemp works! Department : {{department}} <br/> Designation : {{designation}} <br/> <button (click)="onButtonClick($event)">Click to join!</button> </p>
From the previous version of the code, I have just added lines to print department, designation and a button on click of which we call function onButtonClick which we just saw above. This function will, in turn, emit the event that will be caught and handled in the parent. We will now see changes in parent component and once done we will execute our code and see it in action.
Make changes to parent component typescript file so that it looks like below -
Notice that the only new change here is a new function called childClickedButton that we will use to catch and handle the output of child component we say above.
Now make changes to the parent's HTML file so that it looks like below -
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-new-employee', templateUrl: './new-employee.component.html', styleUrls: ['./new-employee.component.css'] }) export class NewEmployeeComponent implements OnInit { name: string; age: number; constructor() { } ngOnInit() { this.name = "Aniket"; this.age = 27; } childClickedButton = function(event) { console.log("Child component clicked. event : " + event); } }
Notice that the only new change here is a new function called childClickedButton that we will use to catch and handle the output of child component we say above.
Now make changes to the parent's HTML file so that it looks like below -
<h1>Welcome to the Employee portal</h1> <h3>Name : {{name}}</h3> <h3>Age : {{age}}</h3> <app-subemp [department]="'IT'" [designation]="'Software developer'" (joined)="childClickedButton($event)" ></app-subemp> </pre>
We have changed some things in the way we add child component in the HTML file. This is how we send input to the child component and handle the output. It's called data binding. So we are essentially sending department and designation as inputs to the child component. We saw these as @input() variables in child component. Similarly, we are now catching joined which was a output and calling our user defined function childClickedButton function. So the string emitted by the child on the actual button clicked will be sent as the event to this function.
Now let's see this in action. Run the app with command -
- ng serve -o
You should see the following screen -
Make sure you go to the correct URL path to render the components. Now you can click the "click to join" button in the parent and see the console logs. You should see the following -
You can see the button click event happened which emitted the event from the child. Parent captured it and printed another console log. That's how you can configure inputs and outputs for nested angular components and pass data. | http://opensourceforgeeks.blogspot.com/2018_12_05_archive.html | CC-MAIN-2020-29 | refinedweb | 866 | 54.42 |
Re: [dev] print utility
This message
: [
Message body
] [ More options (
top
,
bottom
) ]
Related messages
: [
Next message
] [
Previous message
] [
In reply to
] [
Next in thread
] [
Replies
]
Contemporary messages sorted
: [
by date
] [
by thread
] [
by subject
] [
by author
] [
by messages with attachments
]
From
: Calvin Morrison <
mutantturkey_AT_gmail.com
>
Date
: Sat, 30 Mar 2013 22:53:50 -0400
On 30 March 2013 22:30, Robert Ransom <rransom.8774_AT_gmail.com> wrote:
> On 3/30/13, Calvin Morrison <mutantturkey_AT_gmail.com> wrote:
>> What do you guys think of the tool? Of the code? It does one thing and
>> one thing well.
>
> Or perhaps you're just learning C and wanted someone to review your code.
A bit of both really, a good code review is very nice for me to learn,
and it has a purpose, not some silly lesson from a text-book without a
real use. How many times can I say hello to the world?
> Style issues:
>
> * Error messages should be sent to stderr (s/printf(/fprintf(stderr, /
> on error-message lines). (If you're not using stdio.h, that's fd 2.)
I fixed this, thank.)
So would it be proper to handle it with a few if statements?
if argc is 2 try to read standard input
if argc is 3 read argv[2]
if argc is 3+ or 1, print to stderr a usage statement
if a switch appropriate? else if?
> * If you're writing a quick program with at most one input stream and
> at most one output stream, use stdin and stdout, and omit the
> filename-handling code. (That's certainly faster.)
I am having trouble with understanding this, do you mean something to
the effect of this?
cat print.c | print 2
#include <stdio.h>
> * You're using both exit() and return in main. This is noticeably inconsistent.
I fixed this
Which is preferable? I suppose in this example it does not matter
because returning is the same as exit from the main function?
> *.
Should I have a seperate declaration and then intialization later or
just combine the statements:
int line = atoi(argv[2]);
or
int line;
line = atoi(argv[2]);
> *.)
I will look at strtoul, though I don't know anything about error
checking. Can error checking be done with atoi?
> * Your program will silently print nothing if the line number is (a
> string which atoi parses to) a non-positive number. That's probably
> an error that you should print a message about.
I have added a check.
> *.
>
Forget this whole LINE_MAX thing, I am looking at your suggestion in
the other message.
Thank you for the thorough review,
Calvin
Received on
Sun Mar 31 2013 - 04:53:50 CEST
This message
: [
Message body
]
Next message
:
Carlos Torres: "Re: [dev] print utility"
Previous message
:
Robert Ransom: "Re: [dev] print utility"
In reply to
:
Robert Ransom: "Re: [dev] print utility"
Next in thread
:
Carlos Torres: "Re: [dev] print utility"
Reply
:
Carlos Torres: "Re: [dev] print utility"
Reply
:
Robert Ransom: "Re: [dev] print utility"
Reply
:
Martti Kühne: "Re: [dev] print utility"
Contemporary messages sorted
: [
by date
] [
by thread
] [
by subject
] [
by author
] [
by messages with attachments
]
This archive was generated by
hypermail 2.3.0
: Sun Mar 31 2013 - 05:00:06 CEST | https://lists.suckless.org/dev/1303/15079.html | CC-MAIN-2021-25 | refinedweb | 535 | 72.66 |
Way back in 1992 I was studying linear algebra at Waterloo. I just could not seem to wrap my head around dual spaces. Then one night I went to sleep after studying algebra for several hours, and I dreamed about dual spaces. When I awoke I had a clear and intuitive understanding of the concept. Apparently my brain had decided to sort it all out in my sleep. It was a bizarre experience that never happened again.[1. Unfortunately I no longer have an intuitive understanding of dual spaces, having not used anything more than the most basic linear algebra for two decades. I’m sure I could pick it up again if I needed to, but I suspect that the feeling of sudden clarity is not going to be regained.] History is full of examples of people who had sudden insights that solved tricky problems. The tragically short-lived mathematician Srinivasa Ramanujan claimed that he dreamed of vast scrolls of mathematics, most of which turned out to be both correct and strikingly original.
There is of course a difficulty with waiting for a solution to appear in a dream: you never know when that’s going to happen. Since insight is unreliable, we’ve developed a far more reliable technique for solving tough problems: recursive divide and conquer. We solve problems the same way that a recursive method solves problems:
Is the current problem trivial? If so, solve it. Otherwise, break the current problem down into one or more smaller problems. Recursively solve the smaller problems and then compose those solutions into a solution to the larger problem.
It’s “composition” that I want to talk about today. Composition is the act of combining two or more solutions to smaller problems into a single abstraction that solves a larger problem. We do this so often when writing computer programs, it’s like the air we breathe. It’s all around us but we don’t think about it that often. Here we have a composition of two properties with an operator; the result of the composition is a third property:
public double Area { get { return this.Length * this.Width; } }
And of course whatever
Rectangle type this is has probably composed two values of
Point type for the corners, which have in turn composed two
double values for the coordinates, and so on. All the mechanisms of a modern, pragmatic programming language are there to make it easy to compose solutions to smaller problems into solutions of larger problems.
Thus there are an enormous number of different kinds of composition available to C# programmers. Today I want to talk about a very specific kind of composition: composition of non-void functions of one parameter. This is one of the most basic of compositions.[1. Well, arguably the composition of two void functions of no parameters into a third is even more basic; you can’t get much simpler than
void M() { A(); B(); }.] As a silly illustrative example, if you have:
static long Cube(int x) { return (long)x * x * x; } static double Halve(long y) { return y / 2.0; }
then you can always make a third function that composes these two:
static double HalveTheCube(int x) { return Halve(Cube(x)); }
Typically when we write programs, the program text itself describes a whole pile of compositions, each rather more complex than these simple function-of-one-parameter compositions. But we can also perform function compositions dynamically if we want to, using delegates:
Func<int, long> cube = x => (long)x * x * x; Func<long, double> halve = y => y / 2.0; Func<int, double> both = z => halve(cube(z));
And in fact, we could even make a method that does it for us:
static Func<X, Z> Compose<X, Y, Z>( Func<X, Y> f, Func<Y, Z> g) { return x => g(f(x)); }
And then we could say:
Func<int, long> cube = x => (long)x * x * x; Func<long, double> halve = y => y / 2.0; Func<int, double> both = Compose(cube, halve);
Of course you would never actually do that, because function composition has such a lovely syntax already in C#. But logically, this is what you are doing every time you write a program where the result of one function is fed into the next: you are composing the two functions into a third.
Notice that of course in order to be composed, the return type of the “inner” function must be implicitly convertible to the parameter type of the “outer” function. Which brings us back to the topic at hand: the final rule of the monad pattern for types. We’ve been talking about “special” functions that return an instance of a monadic type. Suppose we have two such functions:
Func<int, Nullable<double>> log = x => x > 0 ? new Nullable<double>(Math.Log(x)) : new Nullable<double>(); Func<double, Nullable<decimal>> toDecimal = y => Math.Abs(y) < decimal.MaxValue : new Nullable<decimal>((decimal)y) : new Nullable<decimal>(); Func<int, Nullable<decimal>> both = Compose(log, toDecimal);
That doesn’t work.
toDecimal takes a
double, but
log returns a
Nullable<double>. What do we want to happen? Clearly we want to say that the result of the composed functions is null if
log returns null, and otherwise passes the underlying value along to
toDecimal. But we already have a function that does precisely that:
ApplySpecialFunction! And therefore we can build a monadic composition helper:
static Func<X, Nullable<Z>> ComposeSpecial<X, Y, Z>( Func<X, Nullable<Y>> f, Func<Y, Nullable<Z>> g) { return x => ApplySpecialFunction(f(x), g); }
Now we can say:
Func<int, Nullable<decimal>> both = ComposeSpecial(log, toDecimal);
The
ApplySpecialFunction helper method enables us to apply any function to a monadic type, which is awesome. But in doing so it also enables us to compose any two functions that return that type!
I said last time that we were finally going to get to the last rule of the monad pattern, and at long last we’ve arrived. The last rule is: the
ApplySpecialFunction helper must ensure that composition works. In code:
Func<X, M<Y>> f = whatever; Func<Y, M<Z>> g = whatever; M<X> mx = whatever; M<Y> my = ApplySpecialFunction(mx, f); M<Z> mz1 = ApplySpecialFunction(my, g); Func<X, M<Z>> h = ComposeSpecial(f, g); M<Z> mz2 = ApplySpecialFunction(mx, h);
We require that
mz1 and
mz2 be semantically the same. Applying
f to some value and then applying
g to the result must be logically the same as first composing
f with
g and then applying the composition to the value.[2. Again, we do not require referential identity, though that’s great if you can get it. But semantic identity is required.]
Finally we’ve got all the small details taken care of and we can correctly describe the monad pattern in C#:
A monad is a generic type
M<T> such that:
- There is some sort of construction mechanism that takes a
Tand returns an
M<T>. We’ve been characterizing this as a method with signature
static M<T> CreateSimpleM<T>(T t)
- Also there is some way of applying a function that takes the underlying type to a monad of that type. We’ve been characterizing this as a method with signature:
static M<R> ApplySpecialFunction<A, R>( M<A> monad, Func<A, M<R>> function)
Finally, both these methods must obey the monad laws, which are:
- Applying the construction function to a given instance of the monad produces a logically identical instance of the monad.
- Applying a function to the result of the construction function on a value, and applying that function to the value directly, produces two logically identical instances of the monad.
- Applying to a value a first function followed by applying to the result a second function, and applying to the original value a third function that is the composition of the first and second functions, produces two logically identical instances of the monad.
Whew! And now perhaps you see why I started this series all those weeks ago with the idea of exploring the pattern by looking at examples, rather than starting in with the monad laws.
Next time on FAIC I’ll explain what these mechanisms are more traditionally called.
The information for Ramanujan’s passport photo can be found on Wikimedia Commons.
I’ve been following along from the beginning and I’ve understood everything that’s been said. At some point in this journey I should have had a moment of enlightenment which led me to see that, wow I can do this, that, and these other useful things with Monads. That has not happened.
I’m hoping there will be a part (nine?) which demonstrates why, as a C# programmer, I should care about Monads.
Others may have a different answer, but for me learning about Monads opened up the world of more expressive type systems. A real turning point was realizing what C# could not express and Haskell type classes could express. Then discovering what Haskell’s type system cannot express or enforce. With this richer picture of the world of computation I feel I became a much better C# programmer. I now had names for more concepts and could reason about those concepts with concrete laws (something that is hard to do with just a perspective of “design pattern”). More and more of my design work (in C#) was a matter of writing down Haskell types and seeing where things went wrong or discovering some new and profound way of looking at the problem because. Often these new perspectives were implied by algebraic transformations of the types.
I would also like to see a post about that. Monads sound interesting and your explanation has been wonderfully clear, but the syntax is ugly in C# and we’ve been using the existing monadish types (like IEnumerable) without the monad pattern. Perhaps this is a failure of my imagination, but is there something great that the monad pattern can accomplish in C# that outweighs its ugly syntax? Is it simply that designing types that could be used with the monad pattern helps avoid creating certain leaky abstractions? Or is it all just academic? :-)
But the syntax in C# 3 is beautifully clear, it is:
That’s the syntax for calling
ApplySpecialFunction(x, f)in C#. We just call it
SelectManyinstead of
ApplySpecialFunction. The problem is that of course that syntax only reads nicely for the sequence monad. But as we’ll see in a few more episodes, that syntax can be used on any monad, provided that you rename
ApplySpecialFunctionto
SelectMany.
I got too curious to see how SelectMany would work with Nullable just to discover the compiler wouldn’t call the overload I was expecting, but ignoring the extra unexpected parameter I got somewhere, just not exactly what a reader would expect:
namespace Monads
{
class Program
{
static void Main(string[] args)
{
Func<double, decimal?> f = y =>
{
try
{
return new Nullable((decimal)y);
}
catch (OverflowException)
{
return new Nullable();
}
};
double? x = 5;
var r = from a in x
from b in f(a)
select “the real wtf”;
Console.WriteLine(r.ToString());
}
}
public static class NullableMonad
{
public static TResult? SelectMany<TSource, TResult, Twtf>(this TSource? value, Func<TSource, TResult?> selector, Func<TSource, TResult, Twtf> wtf)
where TSource: struct
where TResult:struct
{
return value.HasValue ? selector(value.GetValueOrDefault()) : null;
}
}
}
To understand the interest of monads for a C# programmer, just look at the monad exemples in the first article: Nullable, IEnumerable and Task were all considered important enough to have syntactic sugar added to the language itself to use them better. Basically, things like the ? notation for nullable, yield and linq for IEnumerable and await for Tasks make the compiler itself implement the monad pattern for you.
Most of the recent improvements in the C# language are linked one way or another to monads. i think that’s reason enough to care.
I hope to see a future article that implements SelectMany and demonstrates the interaction with Linq :-)
Hey Eric, this has been a really interesting series, as always. I’m also hoping you include a section about “when you might use a Monad” with maybe an example of something that doesn’t currently exist in the BCL.
On a totally unrelated note; do you know any good books you could recommend about designing compilers? I would prefer something that is lighter on the theory side and more heavy on the practical side.
Thanks!
The definitive answer: The dragon book.
Unfortunately I don’t have an answer to your question, but having read the Dragon Book I can say that it’s probably not what you’re looking for. It’s primarily theoretical, and the practical part is mostly left for you to do as an exercise. It’s also quite old, and I think you’d have a hard time bridging the gap between what was acceptable back then and what you might expect from a modern compiler. It’s still worth a look, though, because it was the first great book on compiler-writing. But try before you buy…
The Dragon Book walks you through the entire process of creating a compiler, not with lengthy prose, but with real code. I have read both the 2nd and 3rd editions. The 3rd was released in 2006; hardly “quite old”.
My copy of the Dragon Book has a copyright of 1986. That made me feel “quite old”.
I got lots of insights from the book “Domain Specific Languages” by Martin Fowler and Rebecca Parsons
It both provides the theoretical background where needed and shows you examples implemented in quite up-to-date tools.
A simple series (which is quite old but I think still useful) is “Let’s Build a Compiler, by Jack Crenshaw”. Check out
This. “Let’s Build A Compiler” is far more practical and easier to understand than the Dragon Book. It’s a shame it was never finished, but it’s complete *enough* to give you a good, solid understanding of the principles involved.
Func<double, Nullable> toDecimal = y => Math.Abs(y) < decimal.MaxValue :
new Nullable((decimal)y) : new Nullable();
Eric there is a typo after “Math.Abs(y) < decimal.MaxValue".
Just a note: comparing a double to decimal.MaxValue is tricky. There’s no implicit conversion between decimal and double, so Math.Abs(y) < decimal.MaxValue won't work. If you convert the left side to decimal, you may get an OverflowException. If you cast the right side to double, it won't represent the same value. Also, logically your check should be less-than-or-equal rather than less-than, because if it equals the maximum value it should be fine, but (decimal)d throws an exception when d == (double)decimal.MaxValue.
To avoid these problems, I define a constant to equal 7.92281625142643331939E+28, which is the maximum double value that can be converted into a decimal. That makes an assumption about the range of the decimal type, but the range is documented and decimal.MaxValue is const (meaning it'd break existing binaries to change it) so I don't feel the assumption is unsafe.
y => {
try
{
return new Nullable<decimal>((decimal)y);
}
catch(OverflowException)
{
return new Nullable<decimal>();
}
}
Does it works?
Comparisons between different numeric types can only really be done accurately by code which examines both numbers in their native type and takes into account differences between them. The .NET Framework doesn’t do that even in equality-comparison cases where the semantics should be clear and well-defined (for example, while one could define a proper equivalence relation between values of types `double` and `long` [such that for any three variables x,y,z of any combination of those types, if x==y and y==z, then x==z], the `==` operator in C# does not do so (e.g. x=1L<<62; y=(double)x; z=x+1). Unless one is going to explicitly code comparison operators that "understand" their operands [e.g. writing a `long`/`double` comparison operator which reports unequal if the double is outside the range of a long or has a non-zero fractional part, and otherwise converts to long and does the comparison], I would posit that semantics will be clearer if one requires that code explicitly converts things to the same format before comparison. Note that in the case of `double`-vs-`Decimal` comparisons, in most cases where a `Decimal`-to-`double` conversion would be imprecise, the resulting `double` value will also have no precise `Decimal` representation either.
Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1316
Eric, would you mind using WordPress’s “more” function in your articles? It makes the front page of your blog *so* much easier to navigate.
I’ll look into it, thanks. I am a WordPress noob, obviously. :-)
Took me a while to find what the more function (more tag) was:
Eric,
this is a great series of articles.
I’m facing a design problem with a type with monadic properties (or so I think…).
I’ve posted in SO (), maybe it’s of some interest for you.
Excellent job!
Giacomo Stelluti Scala
It is really helpful. Thanks | http://ericlippert.com/2013/03/14/monads-part-seven/ | CC-MAIN-2014-52 | refinedweb | 2,867 | 60.55 |
I am using php
mysqli_connect for login to a MySQL database (all on localhost)
<?php//DEFINE ('DB_USER', 'user2');//DEFINE ('DB_PASSWORD', 'pass2');DEFINE ('DB_USER', 'user1');DEFINE ('DB_PASSWORD', 'pass1');DEFINE ('DB_HOST', '127.0.0.1');DEFINE ('DB_NAME', 'dbname');$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);if(!$dbc){ die('error connecting to database'); }?>
this is the mysql.user table:
MySQL Server ini File:
[mysqld]# The default authentication plugin to be used when connecting to the serverdefault_authentication_plugin=caching_sha2_password#default_authentication_plugin=mysql_native_password
with
caching_sha2_password in the MySQL Server ini file, it's not possible at all to login with user1 or user2;
error: mysqli_connect(): The server requested authentication method unknown to the client [caching_sha2_password] in...
with
mysql_native_password in the MySQL Server ini file, it's possible to login with user1, but with user2, same error;
how can I login using
caching_sha2_password on the mySql Server?
I need to use SHA-1 as a PRNG so that is why it needs some key, but in python libs such as hashlib and pycryptodome I didn't find any opportunity for this. Are there any ready solutions? Or maybe there's another way to use SHA-1 as PRNG in python? The quistion is asked because the code of SHA-1 PRNG in NIST tests confused me a bit.(the code is from NIST tests, it's in sts-2.1.2/sts-2.1.2/src/generators.c in the end). To be honest,I expected that SHA-1 PRNG works like this:
r=sha1(x)
r=sha1(r)But with that NIST code I really don't understand how to implement SHA-1 PRNG on python.
// Uses 160 bit Xkey and no XSeed (b=160)// This is the generic form of the generator found on the last page of the Change Notice for FIPS 186-2voidSHA1(){ ULONG A, B, C, D, E, temp, Wbuff[16]; BYTE Xkey[20], G[20], M[64]; BYTE One[1] = { 0x01 }; int i, num_0s, num_1s, bitsRead; int done; ULONG tx[5] = { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 }; if ( ((epsilon = (BitSequence *) calloc(tp.n,sizeof(BitSequence))) == NULL) ) { printf("Insufficient memory available.\n"); exit(1); } ahtopb("ec822a619d6ed5d9492218a7a4c5b15d57c61601", Xkey, 20);// ahtopb("E65097BAEC92E70478CAF4ED0ED94E1C94B15446", Xkey, 20);// ahtopb("6BFB9EC9BE37B2B0FF8526C222B76E0E91501753", Xkey, 20);// ahtopb("5AE8B9207250257D0A0C87C0DACEF78E17D1EF9D", Xkey, 20);// ahtopb("D99CB53DD5FA9BC1D0176F5DF8D9110FD16EE21F", Xkey, 20); for ( i=0; i<tp.numOfBitStreams; i++ ) { num_0s = 0; num_1s = 0; bitsRead = 0; do { memcpy(M, Xkey, 20); memset(M+20, 0x00, 44); // Start: SHA Steps A-E A = tx[0]; B = tx[1]; C = tx[2]; D = tx[3]; E = tx[4]; memcpy((BYTE *)Wbuff, M, 64);#ifdef LITTLE_ENDIAN byteReverse(Wbuff, 20);#endif sub1Round1( 0 ); sub1Round1( 1 ); sub1Round1( 2 ); sub1Round1( 3 ); sub1Round1( 4 ); sub1Round1( 5 ); sub1Round1( 6 ); sub1Round1( 7 ); sub1Round1( 8 ); sub1Round1( 9 ); sub1Round1( 10 ); sub1Round1( 11 ); sub1Round1( 12 ); sub1Round1( 13 ); sub1Round1( 14 ); sub1Round1( 15 ); sub2Round1( 16 ); sub2Round1( 17 ); sub2Round1( 18 ); sub2Round1( 19 ); Round2( 20 ); Round2( 21 ); Round2( 22 ); Round2( 23 ); Round2( 24 ); Round2( 25 ); Round2( 26 ); Round2( 27 ); Round2( 28 ); Round2( 29 ); Round2( 30 ); Round2( 31 ); Round2( 32 ); Round2( 33 ); Round2( 34 ); Round2( 35 ); Round2( 36 ); Round2( 37 ); Round2( 38 ); Round2( 39 ); Round3( 40 ); Round3( 41 ); Round3( 42 ); Round3( 43 ); Round3( 44 ); Round3( 45 ); Round3( 46 ); Round3( 47 ); Round3( 48 ); Round3( 49 ); Round3( 50 ); Round3( 51 ); Round3( 52 ); Round3( 53 ); Round3( 54 ); Round3( 55 ); Round3( 56 ); Round3( 57 ); Round3( 58 ); Round3( 59 ); Round4( 60 ); Round4( 61 ); Round4( 62 ); Round4( 63 ); Round4( 64 ); Round4( 65 ); Round4( 66 ); Round4( 67 ); Round4( 68 ); Round4( 69 ); Round4( 70 ); Round4( 71 ); Round4( 72 ); Round4( 73 ); Round4( 74 ); Round4( 75 ); Round4( 76 ); Round4( 77 ); Round4( 78 ); Round4( 79 ); A += tx[0]; B += tx[1]; C += tx[2]; D += tx[3]; E += tx[4]; memcpy(G, (BYTE *)&A, 4); memcpy(G+4, (BYTE *)&B, 4); memcpy(G+8, (BYTE *)&C, 4); memcpy(G+12, (BYTE *)&D, 4); memcpy(G+16, (BYTE *)&E, 4);#ifdef LITTLE_ENDIAN byteReverse((ULONG *)G, 20);#endif // End: SHA Steps A-E done = convertToBits(G, 160, tp.n, &num_0s, &num_1s, &bitsRead); add(Xkey, 20, G, 20); add(Xkey, 20, One, 1); } while ( !done ); fprintf(freqfp, "\t\tBITSREAD = %d 0s = %d 1s = %d\n", bitsRead, num_0s, num_1s); fflush(freqfp); nist_test_suite(); } free(epsilon);}
I am trying to setup python flask based server to setup webhook with sha1 signature. I could able to use simple verification token but not able to use sha1 algorithm.
Could someone share the sample python script reference ?
All the documentation and examples I've seen all use C# code to generate the secret, like this:
new Secret("secret".Sha256())
This is fine for an initial setup and inserting into the database on startup, but what if I want to add a secret directly to the database at run time. Preferably I'd like to give instructions to a customer that doesn't involve any code.
I've tried using online tools to hash the string then Base64 encode the string but it's not matching what the code generates so I think I'm missing a step.
This question already has an answer here:
I am using Google Tag Manager and I would like to use the variable "DOM element" (that relays CSS selectors), to catch text1 inside the span tag and use it as a variable. I can't get the text using the selectors
I have tried using span#widgetBirdset.pxs-attribute as a selector. Here's the span tag where i want to get it:
<span id="widgetBirdset.pxs-attribute <div class="pxs-dot"> <svg width="20" height="20" xmlns="" viewBox="0 0 303.68 469.22"> <g class="Calque_2" data- <g class="Layer_1" data- <path class="pxs-html5" d="M151.83,469.22a13,13,0,0,1-12.68-10L99.43,294.36a151.1,151.1,0,0,1-17.26-7.61,148.42,148.42,0,0,1-22.55-14.31,151.83,151.83,0,1,1,199.59-228,152.06,152.06,0,0,1,38.09,151,154.42,154.42,0,0,1-8.9,22.76,152.79,152.79,0,0,1-84.16,76.1L164.51,459.25A13,13,0,0,1,151.83,469.22Zm0-441A123.69,123.69,0,0,0,95.14,261.7a125.85,125.85,0,0,0,20.33,8.3,14.08,14.08,0,0,1,9.43,9.54l26.93,111.8,26.78-111.15c0-.06.19-.72.2-.78a13,13,0,0,1,8.89-9.26,123.43,123.43,0,0,0,87.74-117.6c0-.24,0-.47,0-.71s0-.48,0-.72A123.65,123.65,0,0,0,151.83,28.22Z"></path> <path class="pxs-html5" d="M151.83,207.16a56,56,0,1,1,56-55.95A56,56,0,0,1,151.83,207.16Zm0-85.82a29.87,29.87,0,1,0,29.87,29.87A29.9,29.9,0,0,0,151.83,121.34Z"></path> </g> </g> </svg> </div>text1</span>
I expect the output text1 and want to hash it SHA-1 in Google Tag Manager
Thanks, | https://www.convertstring.com/zh_TW/Hash/SHA384 | CC-MAIN-2019-47 | refinedweb | 1,162 | 64.24 |
Java relational operators determine the relationship between two operands.
The relational operators in Java are:
For example, the following code fragment is perfectly valid. It compares two int values and assign the
result to
boolean value
c.
public class Main { public static void main(String[] argv) { int a = 4; int b = 1; boolean c = a < b; System.out.println("c is " + c); } }
The result of
a < b (which is false) is stored in
c.
The outcome of a relational operator is a boolean value.
In the following code, the
System.out.println outputs the result of a relational operator.
public class Main { public static void main(String args[]) { // outcome of a relational operator is a boolean value System.out.println("10 > 9 is " + (10 > 9)); } }
The output generated by this program is shown here: | http://www.java2s.com/Tutorials/Java/Java_Language/3020__Java_Relational_Operators.htm | CC-MAIN-2017-43 | refinedweb | 134 | 50.43 |
At Ignite 2017, we announced the public preview of near real-time metric alerts in Azure. This new kind of alerts provide the following improvements over the current metric alerts.
- Improved Latency – You can create near real-time metric alerts that monitor metric values as frequently as 1 minute.
- More control over metric conditions – You can create near real-time metric alert rules that can monitor minimum, maximum, average, and total of the metric over the evaluation period.
- Combined monitoring of multiple metrics – You can create a single near real-time metric alert rule that can monitor multiple metrics (currently two) at the same time.
- Modular notification system – You can use action groups with near real-time metric alerts. Action groups provide a reusable set of actions that can be used with multiple alerts. By using action groups with near real-time metric alerts, you can send SMS, email, or call web hook when an alert gets triggered.
Using near real-time metric alerts
Let’s look at how to create a near real-time metric alert.
1. In the Azure portal, locate the resource you are interested in monitoring and select it. You can also do the same for all supported resource types centrally from Monitor>Alerts.
2. Select Alerts or Alert rules under the Monitoring section. The text and icon may vary slightly for different resources.
3. Click the Add near real time metrics alert (preview) command. If the command is grayed out, ensure the resource is selected in the filter.
4. Name your alert rule, and choose a Description, which also shows in notification emails.
5. Select the Metric you want to monitor, then choose a Condition, Time Aggregation, and Threshold value for the metric. Optionally, select another Metric you want to monitor, then choose a Condition, Time Aggregation, and Threshold value for the second metric.
6. Choose the Evaluation Period and Evaluation Frequency.
7. Specify if you want to use a New or Existing Action Group.
8. If you choose to create New Action Group, give the action group a name and a short name, specify actions (SMS, Email, or Web hook) and fill respective details.
9. Select OK when done to create the alert.
How does a near real-time alert work?
Let’s look at this with the help of an example. Say you have configured your rule as follows:
Starting at around when the alert was created, the alert will look at the past 5 minutes of data for %CPU Usage and NetworkIn metrics, calculate the average %CPU Usage and Total NetworkIn values, and check if they are above their respective thresholds. The alert will fire only if both the thresholds are breached. The conditions are evaluated again after 1 min. The alert is resolved if one of the metrics go below their thresholds.
Supported resources
These are some of the resource types that are supported today by near real-time metric alerts:
- Microsoft.Compute/virtualMachines:
- Microsoft.Compute/virtualMachineScaleSets:
- Microsoft.DBforMySQL/servers
- Microsoft.DBforPostgreSQL/servers
- Microsoft.Cache/Redis
- Microsoft.ServiceBus/namespaces
For a full list of supported resource types, see the documentation. Support for more resources is coming soon.
For more information on near real-time metric alerts, see the documentation. We would love to hear your feedback. Send us any questions or feedback to azurealertsfeedback@microsoft.com. | https://azure.microsoft.com/tr-tr/blog/get-alerts-faster-with-near-real-time-alerting-for-azure-platform-metrics/ | CC-MAIN-2021-21 | refinedweb | 555 | 55.74 |
Camm Maguire <address@hidden> writes: > Greetings! > > 1) I've put in what I hope are analogs to your very helpful patches > regarding data seg size limits and mallocing error messages. > Please check them out and let me know if I've overlooked anything. > I'm assuming without any shred of evidence that fputs won't malloc > from other calls in the existing code. It doesn't work as commited; same symptoms as before. I tested the following program on Debian and OpenBSD: #include <stdio.h> #define USE_FPUTS 0 void *malloc(void) { #if USE_FPUTS fputs("recursion\n", stderr); #else write(1, "in malloc\n", 10); #endif return NULL; } int main(void) { fputs("start\n", stderr); return 0; } On Debian, only "start" is printed, but on OpenBSD, both "in malloc" and "start" are printed. gdb confirms that something calls malloc before main is reachead - that's why I put the setrlimit call in alloc.c instead of main.c. Anyway, in both cases it seems that fputs does not use malloc. Then, setting USE_FPUTS to 1, I get the same result as with GCL - malloc uses fputs, which reaches into some library without debugging symbols, which calls malloc, which calls fputs... etc. After digging around a bit in OpenBSD libc, it seems to me that stdio will happily use unbuffered I/O if it can't allocate memory, but it needs the return value to notice that. Like this: 1. Something (still not sure what) makes stdio try to allocate a buffer. 2a. My fake malloc returns NULL - stdio uses unbuffered I/O and is happy with that. 2b. My fake malloc calls fputs with stderr, which has no buffer yet - goto 1. Thus, to avoid recursion the malloc of GCL must never use stdio to report failure. (OpenBSD specific, that is, as stdio of glibc seems not to use malloc) And, if GCL malloc is to fail ungraciously without giving the option of retrying later (which seems to me quite sane), the setrlimit call needs to happen as soon as possible - in OpenBSD's case before main. > 2) Re EFAULT in writing saved_pre_gcl -- this is almost certainly in > unexec. The code is taken straight from emacs, so if OpenBSD has a > working emacs, we should have a working solution here too. Thanks for the pointer, I'll see what I find. Regards, Magnus | http://lists.gnu.org/archive/html/gcl-devel/2004-03/msg00278.html | CC-MAIN-2016-26 | refinedweb | 392 | 70.53 |
This is the mail archive of the libc-alpha@sourceware.org mailing list for the glibc project.
On Thu, 19 Sep 2019, Alistair Francis wrote: > To allow struct __timespec64 and struct timespec to be the same on a > 32-bit architecture with a 64-bit time_t we need to add padding to the > struct timespec. This padding requires knowledge of the machines > endianess, which requires us exporting the endianness in > time/bits/types/struct_timespec.h. > > To reduce the number of macros that we are exporting let's split out an > endian_t.h header file that can be used. An installed header has to be appropriately listed in "headers" in some directory's Makefile to cause it to be installed; otherwise you get code that builds file in the glibc source tree but breaks with an installed compiler and headers. The bits/types/ namespace is *only* for headers defining a single type (that is, bits/types/endian_t.h would be a header that defines the endian_t typedef and nothing else). So it's not appropriate for this header. You can't use "#include <time/...>" in an installed header because that would also break when using an installed compiler and headers. #includes in installed headers need to use the <bits/*> path the included header would have when installed. Then you add an include/bits/ wrapper in the glibc source tree to allow the uninstalled header to be found when building glibc. (And time/ is not the right location for a header about endianness. Either string/, or use the top-level bits/ directory and so avoid the need for any wrapper at all.). -- Joseph S. Myers joseph@codesourcery.com | https://sourceware.org/legacy-ml/libc-alpha/2019-09/msg00321.html | CC-MAIN-2021-04 | refinedweb | 276 | 63.8 |
Get/Set method
Scotty Steven
Ranch Hand
Joined: Jan 27, 2012
Posts: 80
posted
Mar 20, 2012 19:54:47
0
I am working my way through a text book, trying to self-teach during my spare time. One of the exercises has me setting up a class called Purchase, with get and set methods. It then wishes me to set up a method in that class called display, to display the stored info (I've blocked out the code starting on lines 30-34 of the second class where this should happen). In the second class, called CreatePurchase, I create the info to send to set methods, with loops and exception handling.
I am stuck on how to do the display part of the exercise. I am attaching code. HELP!
import java.util.*; public class CreatePurchase { public static void main(String[] args) { //delclarations int invoiceNum, a1; double saleAmt; boolean invLoop = true; boolean saleLoop = true; String cleanInputBuffer; Scanner input = new Scanner(System.in); while(invLoop) { try { Purchase onePurch = new Purchase(); System.out.print("Enter the invoice number: "); invoiceNum = input.nextInt(); if(invoiceNum >= 1000 && invoiceNum <= 8000) { onePurch.setInvNumber(invoiceNum); invLoop = false; } else { System.out.println("Invoice amounts must be " + "between 1000 and 8000."); invLoop = true; } } catch(InputMismatchException error) { System.out.println("Invalid data type."); cleanInputBuffer = input.nextLine(); } }//end while(invLoop) while(saleLoop) { try { Purchase twoPurch = new Purchase(); System.out.print("Enter the sales amount $"); saleAmt = input.nextDouble(); if(saleAmt >=0.01) { twoPurch.setSaleAmount(saleAmt); saleLoop = false; } else { System.out.println("Sales amount must be greater then 0"); saleLoop = true; } } catch(InputMismatchException error) { System.out.println("Invalid data type."); cleanInputBuffer = input.nextLine(); } }//end while(saleLoop) }//end main() } // end class
public class Purchase { // declarations private int invNumber; private double saleAmount; private double saleTaxAmount; private double SALES_TAX = .05; public int getInvNumber() { return invNumber; } // end getInvNumber() public void setInvNumber(int i) { invNumber = i; } // end setSiteNumber() public double getSaleAmount() { return saleAmount; } // end getSaleAmount() public void setSaleAmount(double a) { saleAmount = a; saleTaxAmount = saleAmount * SALES_TAX; } // end setSaleAmount() /* public static void display(int a2) { System.out.println("Sales invoice #" + ?); }//end display() */ } // end class Purchase
Scotty Steven
Ranch Hand
Joined: Jan 27, 2012
Posts: 80
posted
Mar 21, 2012 01:53:27
0
Anybody?
Manoj Kumar Jain
Ranch Hand
Joined: Aug 22, 2008
Posts: 193
I like...
posted
Mar 21, 2012 02:26:37
0
I didn't look deeply in your code but what I understand is that you want to show value of Purchase object and you want a Display method in Purchase Class.
You should declare a Display() method without any argument list like public void Display(). You can call this method from your CreatePurchase class with Purchase class object like onePurch.display();
Inside this method just place the System.out.print statement to print the values of the object like System.out.print("Value of invoice is: " +invNumber);
Hope this help.
Do not wait to strike till the iron is hot; but make it hot by striking....
Santhosh ayiappan
Ranch Hand
Joined: Jan 30, 2007
Posts: 80
I like...
posted
Mar 21, 2012 02:30:13
0
You have created 2 purchase class objects , but you have not stored them any where. Try to retain the objects in a collection object. Then iterate the collection and get the purchase object and get the values from the object.
Regards
Santhosh
Scotty Steven
Ranch Hand
Joined: Jan 27, 2012
Posts: 80
posted
Mar 21, 2012 03:20:13
0
@Manoj Kumar Jain
This help got me close enough to soling my problem. I had some other logic errors to deal with as well as I was out of scope when I tried to execute.
Anyways, Thank you to those who answered.
I agree. Here's the link:
subject: Get/Set method
Similar Threads
endless loop
Java Validation! Field should be Integer
StackOverflowError
try...catch blocks giving <identifier> expected error
Class and Object Problem
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton | http://www.coderanch.com/t/570962/java/java/Set-method | CC-MAIN-2015-40 | refinedweb | 662 | 65.32 |
recommend to some jython users to hang in irc.freenode.net, jython. I have found the java channel to be pretty cool and the python channel pretty cool. Of course there is no one in the jython channel. Of course people dont like IRC for network security reasons and it is a little geeky, but all that is myth.
Thanks for the update.
-Jonathan
-----Original Message-----
From: jython-dev-admin@...
[mailto:jython-dev-admin@...] On Behalf Of Samuele
Pedroni
Sent: Monday, August 23, 2004 4:31 AM
To: jython-dev@...
Subject: [Jython-dev] log
I appreciate all offers of help, and I'm fully aware that Jython has=20
suffered from not being in conditions that allowed breaking and dividing
tasks and a release early/release often style.
When such a style and mode can be hopefully re-established with the next
alphas, Jython will indeed have use of new contributors.
You haven't heard of me because I have been doing over the last period some
not forseen work
for a company in Sweden.
I still intend to finish the work I started on the newstyle-branch, where
I'm implementing
new-style classes for Jython.
It is still true that before the branch has landed in the trunk and there's
a new alpha,
it is hard to contribute and I will not have much bandwidth to review new
patches, that btw risk to assume the old world unless they follow what is
going on on the branch.
I appreciate all offers of help, and I'm fully aware that Jython has
suffered from not being in conditions that allowed breaking and dividing
tasks and a release early/release often style.
When such a style and mode can be hopefully re-established with the next
alphas, Jython will indeed have use of new contributors.
regards.
Hi
I'm also new to this list and I too would like to help see to that =
jython=20
catches up with python. I have a bachelor degree in computer science=20
(mostly j2se/j2ee programming) and are currently extending it to a=20
masters degree. For example I've read a course on compiler technology.
> And I am assuming jython doesnt work with tools like twisted yet?
Jython is compatible with python 2.1, so you might have a chance=20
with one of the old debian packages of twisted (if it not uses any=20
c extensions).
What's the status of the 2.2 release? Any todo list for 2.2b?
I've tried the python regrtest... doesn't look so good :)
I'm currently working on fixing the following coercion bug:
class C:
def __coerce__(self, other):
return 2, other
assert C() =3D=3D 2.0
-> java.lang.ClassCastException
...johahn
I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details | https://sourceforge.net/p/jython/mailman/jython-dev/?viewmonth=200408&viewday=23 | CC-MAIN-2016-40 | refinedweb | 505 | 71.65 |
KeyPressEvent don't work with ibus?
Here is my code:
@
#include <QApplication>
#include <QTextEdit>
#include <QKeyEvent>
class TextEdit : public QTextEdit {
void keyPressEvent(QKeyEvent *e) {
qDebug("pressed key %d", e->key());
}
void keyReleaseEvent(QKeyEvent *e) {
qDebug("released key %d", e->key());
}
};
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
TextEdit e;
e.show();
return a.exec();
}
@
The problem is, all text input are not captured by keyPressEvent when any ibus input method is on.
I tested with ibus-pinyin and ibus-mozc and the only config it works is in mozc's direct input mode (not Latin mode, which buffers inputs inline and require a return to submit). ibus-pinyin's English mode also doesn't work.
But it's strange that ASCII inputs in both ibus-pinyin's English mode and ibus-mozc's Latin mode are captured by keyReleaseEvent.
-Is there any way to filter user input regardless of languages and input methods? How is Qt Creator's fakevim mode implemented?-
My environment is GNOME 3.6.3 in Gentoo, with Qt 4.8.5 in Gentoo repo and Qt 5.1.1 downloaded from this site.
Edit: I've found inputMethodEvent so the question is solved but it's still strange for text not captured in keyPressEvent being captured in keyReleaseEvent. | https://forum.qt.io/topic/34996/keypressevent-don-t-work-with-ibus | CC-MAIN-2018-22 | refinedweb | 215 | 66.64 |
After knowing primitive data types and Java rules of Data Type Casting (Type Conversion), let us cast double to long.
By memory-wise, double and long both take 8 bytes of memory. Even then, a double value cannot be assigned to a long (here, rules of casting does not work) as double carries a mantissa (value after decimal point) where as long does not (it is a whole number). In explicit casting, mantissa part is truncated.
The left-side value can be assigned to any right-side value and is done implicitly. The reverse like short to byte requires explicit casting.
Examples of implicit casting
long x = 10;
double y = x;
byte x = 10;
int y = x;
Following program on double to long explains explicit casting, observe, Java style where a double is assigned to a long.
public class Conversions { public static void main(String args[]) { double d1 = 10.5; // 8 bytes // long l1 = d1; // error, double to long long l1 = (long) d1; // data truncation, 0.5 gone System.out.println("double value: " + d1); // prints 10.5 System.out.println("Converted long value: " + l1); // prints 10 } }
Output screenshot of double to long Java
long l1 = d1;
The above statement raises a compilation error "possible loss of precision".
long l1 = (long) d1;
The double d1 is explicitly type casted to long l1. Observe, the syntax of explicit casting. On both sides, it should be long only. When casted, the precision of 0.5 is lost (for this reason only, compiler does not compile). This is known as data truncation.
View all for 65 types of Conversions | https://way2java.com/casting-operations/java-double-to-long/ | CC-MAIN-2022-33 | refinedweb | 265 | 66.54 |
Qt Quick Controls 2: Same background, multiple buttons
- guy incognito
Hi all,
I got a few buttons and all got the same background. Now in every button there is this code:
background: Rectangle{ implicitHeight: x; implicitWidth: y; color: button.pressed ? "lightgray" : "white"; }
Is it possible, like in Qt Quick Controls, to define a single background rectangle and apply it to all buttons?
Hi,
You just have to create a new reusable file, exemple BackGround.qml (uppercase 'B ' is important to be able to reuse this component)
like this :
//Back.qml
import QtQuick 2.0
Rectangle {
color :backMouse.pressed? "red" : "green"
anchors.fill: parent
MouseArea{
id:backMouse
anchors.fill: parent
}
}
using :
Button{
text: "btn 3"
background: Back{} // Back is our reusable component
}
i hope it helps you,
LA
@guy-incognito Either what LeLev said, or you can make a custom Button component and reuse that. If there are many customized but identical parts in your buttons it makes sense to customize the whole Button, otherwise it's reasonable to customize only the background.
This is actually a very common thing in Controls 2, everything is customized that way. Each type's documentation has also "Customizing X" link.
- guy incognito
Thanks to both of you! | https://forum.qt.io/topic/81666/qt-quick-controls-2-same-background-multiple-buttons/2 | CC-MAIN-2019-04 | refinedweb | 203 | 57.57 |
Common teardown scenario for ember routes backed by a data model
ember-data-route is built and maintained by DockYard, contact us for expert Ember.js consulting.
Ensure you clean up after your models.
Any routes you deactivate will check the
modelto ensure it is not unsaved. If it is it will either rollback or remove the model from the store depending if has been previously persisted.
npm install ember-data-route --save-dev
Add the mixin to any route you want:
import Ember from 'ember'; import DataRoute from 'ember-data-route';
export default Ember.Route.extend(DataRoute, { ... });
By default when you transition out of the route the data model is rolled-back/removed automatically after the router is deactivated. However, you may want to detect if this is going to happen and alert the user of changes that will be lost. Typically you could use
window.confirmto allow the user to decide to proceed or not. In the route you are mixing into you can provide your own
willTransitionConfirmfunction to handle this. By default this function returns
trueand is passed the
transitionobject as an argument for you to handle. One possible override could be:
export default Ember.Route.extend(DataRouteMixin, { willTransitionConfirm() { return window.confirm("You have unsaved changes that will be lost. Do you want to continue?"); } });
Sometimes
modelisn't the place where your primary model is located, so setting
primaryModelto something else would allow you to override that setting.
export default Ember.Route.extend(DataRouteMixin, { primaryModel: 'user' });
This will look on
controller.user, instead of
controller.model.
We are very thankful for the many contributors
This library follows Semantic Versioning
Please do! We are always looking to improve this gem. Please see our Contribution Guidelines on how to properly submit issues and pull requests.
Licensed under the MIT license | https://xscode.com/DavyJonesLocker/ember-data-route | CC-MAIN-2021-49 | refinedweb | 301 | 50.84 |
Reindex a target site in Find (Schedule Job)
Hey Guys,
We all use Episerver Find as a search provider and it is a very handy tool for the site search. I also prefer Find over all the other search provider in Epi.
But index rebuild is very time consuming if you have multiple sites hosted in the Episerver CMS.
I am working on a project and it has around 50+ sites those are using the search functionality and whenever I want to rebuild the index for one site I have to run the pre-defined schedule job(EPiServer Find Content Indexing Job) and it takes around 1-2 hours because it rebuilt the index for all the sites.
I need a way to rebuild the indexes for the specific site so I have created a new schedule job.
using System; using System.Text; using System.Web; using EPiServer.Find.Cms; using EPiServer.Find.Helpers.Text; using EPiServer.PlugIn; using EPiServer.Scheduler; using EPiServer.Web; namespace ABC.Framework.Web.Business { [ScheduledPlugIn(DisplayName = "Rebuild Targeted Site Indexes", GUID = "A71C3D81-C481-4CB5-A5B9-66BC7C0095FA")] public class SiteIndexScheduledJob : ScheduledJobBase { private bool _stopSignaled; public SiteIndexScheduled() { if (!string.IsNullOrEmpty(SiteDefinition.Current.Name)) { //Call OnStatusChanged to periodically notify progress of job for manually started jobs OnStatusChanged($"Starting execution of rebuild indexes for {SiteDefinition.Current.Name} site"); var statusReport = new StringBuilder(); // ReIndex the indexes for the sites that have * in its host configuration ContentIndexer.ReIndexResult reIndexResult = ContentIndexer.Instance.ReIndex( status => { if (status.IsError) { string errorMessage = status.Message.StripHtml(); if (errorMessage.Length > 0) statusReport.Append($"{errorMessage}"); } OnStatusChanged( $"Indexing job [{(SiteDefinition.Current.Name)}] [content]: {status.Message.StripHtml()}"); }, () => _stopSignaled); } else { return "Job is cancelled. Please add a host entry with * in site, which you rebuild the indexes"; } //For long running jobs periodically check if stop is signaled and if so stop execution if (_stopSignaled) { return "Stop of job was called"; } return $"Index rebuild successful for {SiteDefinition.Current.Name}"; } } }
It basically rebuilds the indexes for the current site but as you know that if you try to access the "SiteDefinition.Current" in the schedule job it will not return the site, so to overcome this thing you need to apply a wild card character * in the site. Once you applied the wild card character you will get that site as a current site. You can read more about it HERE
So add a wild card character on the site on which you want to rebuild the indexes. Please refer below screenshot for your reference.
Once you are done with this. Please go to Admin->Admin and run the new schedule job "Rebuild Targeted Site Indexes". You will see that it will start the indexing for the wild card character site.
I hope it helps.
Thanks
Ravindra
Nice!
Could better if we have a Admin Tool that will show multiple sites for selection.
When click reindex then trigger job for those sites only!
// Ha Bui
Nice write up (Y)
Thanks, @Son Do.
@Ha Bui - Created an Admin Tool for this -
Thanks
Ravindra S. Rathore
Good work @Ravindra! | https://world.episerver.com/blogs/ravindra-s--rathore/dates/2019/9/now-you-can-reindex-a-targetted-site/ | CC-MAIN-2021-04 | refinedweb | 504 | 59.8 |
Java Applet's and the Web
Difficulty: 1 / 10.
Assumed Knowledge: Basic HTML knowledge
Information: By the time you're finished follow this tutorial, You will be able to write basic applets, create a minimum requirement HTML containers and put your applet on the internet (through HTML).
What is an Applet used for..?
Applets are used to provide interactive features to web applications that cannot be provided by HTML alone. They can capture mouse input and also have controls like buttons or check boxes. In response to the user action an applet can change the provided graphic content
I'm using Eclipse IDE for this tutorialTo start this tutorial, Open your java IDE, create a new project and make a new class file, I will call mine appletTest.java. Once we have that sorted we will add a few lines to our project,
Starting with the imports we will use.
import java.awt.*; import java.applet.*;
What are these imports..?
The java.awt or abstract window toolkit package contains all of the classes for creating user interfaces and for painting graphics and images.
The java.applet package contains all the classes for creating applets.
Next, we'll add the extensions to the class.
public class appletTest extends Applet { }
Adding this Applet extension to the class allows us to edit to create and edit an applet (this is one of the classes in the java.applet package).
We will now add the graphics method.
public void paint (Graphics g) { g.drawRect(10, 10, 300, 100); g.drawString("Basic Java Applet", 20, 25); }
By creating this method using the information in the brackets ( ) allows us to add graphical content to our applet (Graphics is apart of the awt package). g.drawRect allows the user to draw a basic rectangle at specific X and Y coords, and at specific Width's and Height's.
Creating the HTML container
A Container is an object that stores other objects (its elements), and that has methods for accessing its elements. In particular, every type that is a model of Container has an associated iterator type that can be used to iterate through the Container's elements.
This is the process to create a HTML file in the Eclipse IDE, by all means, a previous made one can be dragged and droped.
I will use the same name as i did before, appletTest.html
Once we have made our .html file, we will now want to edit the contents, Once again this is the process to edit the HTML file in the Eclipse IDE, This can be done by selecting the file and opening it with notepad or other software.
Let's create our HTML container,
<html> <head><title>Basic Applet</title></head> <body><applet codebase = "." code = "appletTest.class" name = "Basic Applet" width = "500" height = "500" hspace = "0" vspace = "0" align = "middle"></applet> </body> </html>
Make sure you have debugged the .java file, and that it has created a .class file. (this should be with the .class file)
once you've have completed this, its time to view the final result,
| http://forum.codecall.net/topic/65062-java-java-applets-and-the-web/ | CC-MAIN-2020-40 | refinedweb | 514 | 62.27 |
ASP.NET offers a variety of techniques to manage state: application state, session state, view state, and more. You can read more about these other state management collections in the resources section at the bottom of this page, because in this article we are only going to focus on the Items collection of the HttpContext class. First, let’s be clear and state that what you keep in the Items collection will have a very limited scope. Anything you place into the Items collection will only be around for the duration of a single web request, unlike the Session collection, which will keep it’s contents around for each user as long as they continue to make requests. Nevertheless, we will demonstrate several useful techniques with the Items collection in this article.
To understand how to use the Items collection, which is a member property of the HttpContext class, let’s first take a look at the HttpContext class itself.
HttpContext
An HttpContext object will encapsulate specific details of a single HTTP request. Properties of this class include the Request object, the Response object, the Session object, and an AllErrors property which keeps an array of Exception objects accrued during the current request. You can easily access the context for a request from any member function of a Page class:
private void Page_Load(object sender, System.EventArgs e) { Context.Items["MyObject"] = new object(); object o = Context.Items["MyObject"]; }
In the code above you can see the Items collection is as easy to use as the Session object. Underneath the covers, the Items container is a Hashtable object holding key and value pairs. Ask for an item by name to retrieve an object reference.
Another way to get to the context from anywhere within an ASP.NET application is to use the HttpContext.Current property. Current is a static property which will return the HttpContext object for the current HTTP request. You can use Current from any object in the logical thread of execution for the request (more details to come in another article). The following is an example:
public class TestContext : System.Web.UI.Page { private void Page_Load(object sender, System.EventArgs e) { MyClass myClass = new MyClass(); myClass.DoFoo(); } // generated code } class MyClass { public void DoFoo() { HttpContext.Current.Response.Write("Doing Foo"); } }
Being able to grab an HttpContext item from anywhere in the ASP.NET application is a powerful concept, but be careful not to abuse the privilege. For example, you wouldn’t want middle tier objects writing out directly to the Response object as this would break the encapsulation rules of an n-tier architecture.
HttpContext.Items
Now that we know how to get to the Context, let’s take a look at some of the uses for the Items collection it contains. One use of the Items collection is to transfer values to another WebForm when using Server.Transfer. As an example, let’s look at the Load event handler for WebForm1.aspx
private void Page_Load(object sender, System.EventArgs e) { ArrayList list = new ArrayList(3); list.Add("This list "); list.Add("is for "); list.Add("WebForm2 to see."); Context.Items["WebForm1List"] = list; Server.Transfer("WebForm2.aspx"); }Here we are populating an ArrayList to place into the Items collection and transferring control to WebForm2.aspx. The Load event for WebForm2.aspx prints the contents of the list.
private void Page_Load(object sender, System.EventArgs e) { ArrayList list = Context.Items["WebForm1List"] as ArrayList; if(list != null) { foreach(string s in list) { Response.Write(s); } } }
Note this technique does not work if you use Response.Redirect. A Redirect results in another round trip to the client and a new HTTP request – thus a new Context object without our ArrayList. To span requests, you’ll need to use the Session object or another state container. Also, there are other techniques you can use to pass state between two forms when using Server.Transfer, these other techniques can be found in the resources section of the article.
Another place to use Context.Items is in the Application_BeginRequest method. Visual Studio generates this method in the Global class of global.asax.cs. If you want to catch a request at the very beginning of the ASP.NET pipeline, Application_BeginRequest is the place to be. This is so early in the pipeline, Session state has not yet been associated with the request. Trying to use the Session object in the event handler will force the following exception:
System.Web.HttpException: Session state is not available in this context.
You can, however, use Context.Items during Application_BeginRequest. This is an ideal spot to load request specific state to carry through until ASP.NET completes the request. You could, for instance, inspect the incoming request URL and load a preferences object with different settings if the site is balitmore.odetocode.com versus. Later, during the Load event of any page, you can inspect the Preferences object in the Items collection to make changes to the UI
protected void Application_BeginRequest(Object sender, EventArgs e) { string prefix = Request.Url.Host.ToUpper(); if(prefix.StartsWith("BALTIMORE")) { Context.Items["PREFERENCES"] = // Load Baltimore preferences } else { Context.Items["PREFERENCES"] = // Load default preferences } }
Using the Context.Item collection you can pass state anywhere during the lifetime of the request – across HttpModules, HttpHandlers, Webforms, and Application events.
--
by K. Scott Allen (scott @ OdeToCode.com)
Additional Resources
Personalization in ASP.NET 1.1
Passing Server Control Values Between Pages
Nine Options for Managing Persistent User State in Your ASP.NET Application | http://odetocode.com/Articles/111.aspx | CC-MAIN-2015-11 | refinedweb | 916 | 58.69 |
- NAME
- MANUAL
- NEXT STEPS
- AUTHOR
- DISCLAIMER OF WARRANTIES
NAME
Type::Tiny::Manual::UsingWithMouse - how to use Type::Tiny with Mouse
MANUAL
First read Type::Tiny::Manual::Moo, Type::Tiny::Manual::Moo2, and Type::Tiny::Manual::Moo3. Everything in those parts of the manual should work exactly the same in Mouse.
This part of the manual will focus on Mouse-specifics.
Overall, Type::Tiny is less well-tested with Mouse than it is with Moose and Moo, but there are still a good number of test cases for using Type::Tiny with Mouse, and there are no known major issues with Type::Tiny's Mouse support.
Why Use Type::Tiny At All?
Mouse does have a built-in type constraint system which is fairly convenient to use, but there are several reasons you should consider using Type::Tiny instead.
Type::Tiny provides helpful methods like
whereand
plus_coercionsthat allow type constraints and coercions to be easily tweaked on a per-attribute basis.
Something like this is much harder to do with plain Mouse types:
has name => ( is => "ro", isa => Str->plus_coercions( ArrayRef[Str], sub { join " ", @$_ }, ), coerce => 1, );
Mouse tends to encourage defining coercions globally, so if you wanted one Str attribute to be able to coerce from ArrayRef[Str], then all Str attributes would coerce from ArrayRef[Str], and they'd all do that coercion in the same way. (Even if it might make sense to join by a space in some places, a comma in others, and a line break in others!)
Type::Tiny provides automatic deep coercions, so if type Xyz has a coercion, the following should "just work":
isa xyzlist => ( is => 'ro', isa => ArrayRef[Xyz], coerce => 1 );
Type::Tiny offers a wider selection of built-in types.
By using Type::Tiny, you can use the same type constraints and coercions for attributes and method parameters, in Mouse and non-Mouse code.
Type::Utils
If you've used Mouse::Util::TypeConstraints, you may be accustomed to using a DSL for declaring type constraints:
use Mouse::Util::TypeConstraints; subtype 'Natural', as 'Int', where { $_ > 0 };
There's a module called Type::Utils that provides a very similar DSL for declaring types in Type::Library-based type libraries.
package My::Types { use Type::Library -base; use Type::Utils; use Types::Standard qw( Int ); declare 'Natural', as Int, where { $_ > 0 }; }
Personally I prefer the more object-oriented way to declare types though.
In Mouse you might also declare types like this within classes and roles too. Unlike Mouse, Type::Tiny doesn't keep types in a single global flat namespace, so this doesn't work quite the same with Type::Utils. It still creates the type, but it doesn't store it in any type library; the type is returned.
package My::Class { use Mouse; use Type::Utils; use Types::Standard qw( Int ); my $Natural = # store type in a variable declare 'Natural', as Int, where { $_ > 0 }; has number => ( is => 'ro', isa => $Natural ); }
But really, isn't the object-oriented way cleaner?
package My::Class { use Mouse; use Types::Standard qw( Int ); has number => ( is => 'ro', isa => Int->where('$_ > 0'), ); }
Type::Tiny and MouseX::Types
Types::Standard should be a drop-in replacement for MooseX::Types. And Types::Common::Numeric and Types::Common::String should easily replace MouseX::Types::Common::Numeric and MouseX::Types::Common::String.
That said, if you do with to use a mixture of Type::Tiny and MouseX::Types, they should fit together pretty seamlessly.
use Types::Standard qw( ArrayRef ); use MouseX::Types::Mouse qw( Int ); # this should just work my $list_of_nums = ArrayRef[Int]; # and this my $list_or_num = ArrayRef | Int;
-mouse Import Parameter
If you have read this far in the manual, you will know that this is the usual way to import type constraints:
use Types::Standard qw( Int );
And the
Int which is imported is a function that takes no arguments and returns the Int type constraint, which is a blessed object in the Type::Tiny class.
Type::Tiny mocks the Mouse::Meta::TypeConstraint API so well that most Mouse and MouseX code will not be able to tell the difference.
But what if you need a real Mouse::Meta::TypeConstraint object?
use Types::Standard -mouse, qw( Int );
Now the
Int function imported will return a genuine native Mouse type constraint.
This flag is mostly a throwback from when Type::Tiny native objects didn't directly work in Mouse. In 99.9% of cases, there is no reason to use it and plenty of reasons not to. (Mouse native type constraints don't offer helpful methods like
plus_coercions and
where.)
mouse_type Method
Another quick way to get a native Mouse type constraint object from a Type::Tiny object is to call the
mouse_type method:
use Types::Standard qw( Int ); my $tiny_type = Int; my $mouse_type = $tiny_type->mouse_type;
Internally, this is what the
-mouse flag makes imported functions do.
Type::Tiny Performance
Type::Tiny should run pretty much as fast as Mouse types do. This is because, when possible, it will use Mouse's XS implementations of type checks to do the heavy lifting.
There are a few type constraints where Type::Tiny prefers to do things without Mouse's help though, for consistency and correctness. For example, the Mouse XS implementation of Bool is... strange... it accepts blessed objects that overload
bool, but only if they return false. If they return true, it's a type constraint error.
Using Type::Tiny instead of Mouse's type constraints shouldn't make a significant difference to the performance of your code.
NEXT STEPS
Here's your next step:
Type::Tiny::Manual::UsingWithClassTiny
Including how to Type::Tiny in your object's
BUILDmethod, and third-party shims between Type::Tiny and Class:. | http://web-stage.metacpan.org/pod/distribution/Type-Tiny/lib/Type/Tiny/Manual/UsingWithMouse.pod | CC-MAIN-2021-04 | refinedweb | 953 | 56.39 |
This Bugzilla instance is a read-only archive of historic NetBeans bug reports. To report a bug in NetBeans please follow the project's instructions for reporting issues.
I would like to see a Java Hint added that, when I have the cursor on a parameter, gives me the option to assign the parameter to a (new) field when I hit alt-enter.
I miss this feature from Eclipse.
Hm, such a hint exists for quite a long time and works OK to me - could you please attach a sample class on which it does not work? Thanks.
Hi,
This hint works when in a constructor, but not in a method:
public class ClassA {
public void setMyField(String myField) {
}
}
If method 'setMyField()' is specified in an interface, and added to the class definition from the interface, then I start my coding with filling in the interface definition methods. Not with specifying the constructor and parameters.
Also missing this feature from eclipse and it is not available even in 7.2. | https://bz.apache.org/netbeans/show_bug.cgi?id=181087 | CC-MAIN-2020-16 | refinedweb | 170 | 67.49 |
Installing Graphviz on Windows
Being able to plot/generate graph-based images (be it
networkx, a
keras model structure, or what have you) is a very handy utility to have. However, the backend needed to support simple calls to, say
keras.utils.plot_model() is nontrivial– at least on Windows.
Getting the Binary sorted out
Basically, the Python libraries used to do this kind of operation are actually wrappers/interfaces around a popular Open Source tool called Graphviz, so merely
pip installing your library of choice only gets at the wrapper, not the underlying codebase that’ll do the heavy lifting.
Because we want to install new Python utilities that rely on non-python-file/module backends, it’s most appropriate to leverage Anaconda. The following command will get you need:
conda install graphviz pydot
This will pull down all of the appropriate library code and tuck it under
../user/Anaconda3/, which is already naturally included in your
sys.path variable, like so
from IPython.display import Image Image('images/graphviz_loc.PNG')
Once you’ve got that, you’re home free to do all of the appropriate importing/use to leverage the underlying engines
import graphviz graphviz.backend.ENGINES
{'circo', 'dot', 'fdp', 'neato', 'osage', 'patchwork', 'sfdp', 'twopi'} | https://napsterinblue.github.io/notes/algorithms/graphs/graphviz_windows/ | CC-MAIN-2021-04 | refinedweb | 206 | 54.42 |
One of the things that makes numerical computation interesting is that it often reverses the usual conceptual order of things, using advanced math to compute things that are introduced earlier.
Here’s an example I recently ran across [1]. The hyperbolic functions are defined in terms of the exponential function:
But it may be more efficient to compute the exponential function in terms of hyperbolic functions. Specifically,
Why would you want to compute the simple thing on the left in terms of the more complicated thing on the right? Because hyperbolic sine is an odd function. This means that half its power series coefficients are zero: an odd function only has odd powers in its power series.
Suppose you need to compute the exponential function in an environment where you only have a limited number of registers to store constants. You can get more accuracy out of the same number of registers by using them to store coefficients in the power series for hyperbolic sine than for exp.
If we store n coefficients for sinh, we can include powers of x up to 2n – 1. And since the coefficient of x2n is zero, the error in our Taylor approximation is O(x2n+1). See this post for more on this trick.
If we stored n coefficients for exp, we could include powers of x up to n-1, and our error would be O(xn).
To make things concrete, suppose n = 3 and x = 0.01. The error in the exp function would be on the order of 10-6, but the error in the sinh function would be on the order of 10-14. That is, we could almost compute exp to single precision and sinh to almost double precision.
(I’m glossing over a detail here. Would you really need to store, for example, the 1 coefficient in front of x in either series? For simplicity in the argument above I’ve implicitly said yes. Whether you’d actually need to store it depends on the details of your implementation.)
The error estimate above uses big-oh arguments. Let’s do an actual calculation to see what we get.
from math import exp, sinh, sqrt def exp_taylor(x): return 1 + x + 0.5*x**2 def sinh_taylor(x): return x + x**3/6 + x**5/120 def exp_via_sinh(x): s = sinh_taylor(x) return s + sqrt(s*s + 1) def print_error(approx, exact): print(f"Computed: {approx}") print(f"Exact: {exact}") print(f"Error: {approx - exact}") x = 0.01 approx1 = exp_taylor(x) approx2 = exp_via_sinh(x) exact = exp(x) print("Computing exp directly:\n") print_error(approx1, exact) print() print("Computing exp via sinh:\n") print_error(approx2, exact)
This produces
Computing exp directly: Computed: 1.0100500000000001 Exact: 1.010050167084168 Error: -1.6708416783473012e-07 Computing exp via sinh: Computed: 1.0100501670841682 Exact: 1.010050167084168 Error: 2.220446049250313e-16
Our errors are roughly what we expected from our big-oh arguments.
More numerical analysis posts
[1] I saw this identity in Matters Computational: Ideas, Algorithms, Source Code by Jörg Arndt.
7 thoughts on “Conceptual vs Numerical”
How well does this work for other functions? If you take a function, re-write it in terms of it’s odd (or even) part, and compute values, is there generally a speedup?
It’s generally more efficient to apply power series expansions to either even or odd functions. But if you simply break a function into an even part and an odd part, there’s no savings. For example, if you write exp(x) as sinh(x) + cosh(x), you don’t save anything; even though sinh(x) and cosh(x) have half as many coefficients as exp(x), they don’t overlap, and so you end up storing all the coefficients of exp(x).
How many registers do you need to use to compute sqrt(x)?
I’ve implicitly assumed that
sqrtis available. In any case,
sqrtis not computed via power series. It’s usually computed via Newton’s method or some variation on that method.
Of course a simple Taylor expansion is often not the best series for a numerical computation, right? From my memory modern processors/libraries are more likely to use rational approximations, and even without that I’d expect that the minimal-error polynomial for sinh() over some interval to not be the Taylor polynomial, at least not in general.
It’s not immediately clear to me if the even/odd trick here still works? Though I’d hope you’d still get something out of it.
The link to the book is
Well, the best case, I would venture, would be computing sech(x) and expressing exp(x) via sech(x). Sech(x) has the advantage of odd and alternating sign series, so you could quickly estimate error, how many terms to compute etc | https://www.johndcook.com/blog/2020/08/03/conceptual-vs-numerical/ | CC-MAIN-2022-40 | refinedweb | 804 | 55.54 |
Child sprites' mediators are never destroyed, they keep catching events from context!
Hi guys,
I have a situation that I couldn't find a way out yet even I googled for like a week. I am either making a very basic mistake or I am expecting something that RL2 doesn't provide. Therefore I will start with a question:
1) I have a parent view* that is being mediated. This view has a child view that is being mediated with its own mediator. The question is that when I remove the parent view from the stage, should I expect the child view's mediator to be destroyed?
Well if the answer of this question is a YES, then I have a problem. If it is a NO, is there an option to turn this on or should I remove each children of this parent view from the stage one by one? I will put here a sample of code in order to make it easy to understand.
The code sample below is a bit complex from the example above, there are mediators that extend from each other. But I think the problem is the same for both examples.
// VehicleView, SpeedPanel extends from Sprite, // CarView extends from VehicleView // VehicleMediator, SpeedPanelMediator extends from Mediator // CarMediator extends from VehicleMediator // CarView owns a SpeedPanel component mediatorMap.mapMatcher(new TypeMatcher().allOf(VehicleView, CarView)).toMediator(VehicleMediator); mediatorMap.map(SpeedPanel).toMediator(SpeedPanelMediator);
carView.parent.removeChild(carView);
// When the line above is executed, CarMediator gets destroyed. However SpeedPanelMediator is not destroyed and continues catching events from the context, consider SpeedPanelMediator below:
public class SpeedPanelMediator extends Mediator { [Inject] public var view:SpeedPanel; override public function initialize():void { injector.injectInto(view); addContextListener(SpeedEvent.UPDATE, onSpeedUpdated); } private function onSpeedUpdated(e:SpeedEvent):void { view.updateSpeed(e.speed); } }
Even if the CarView is removed from the stage and CarViewMediator is destroyed, the SpeedPanelMediator is never destroyed and the onSpeedUpdated method continues to be called.
I want the SpeedPanelMedatior matched to my SpeedPanel object to
be destroyed when the CarView gets removed from the stage.
I am able to achieve this manually by removing SpeedPanel from the CarView (ex: carView.removeChild(speedPanel). Is that the way it is?
- All views are subtypes of Starling Sprite.
Comments are currently closed for this discussion. You can start a new one.
Keyboard shortcuts
Generic
Comment Form
You can use
Command ⌘ instead of
Control ^ on Mac
Support Staff 1 Posted by Ondina D.F. on 20 Jun, 2014 04:05 PM
Hi,
Thanks for showing some code and for explaining the workflow! That's always a good idea when asking a question, but not everyone does that:)
The answer is Yes, if the child view has been removed from stage as well.
But if there are still references to views and/or mediators they will be kept alive.
Normally, SpeedPanel would be removed from stage when CarView gets removed.
First thing to check is if SpeedPanel has been indeed removed from stage and garbage collected. Use something like Flash Builder profiler to find loitering objects and which class has a reference to another class.(don't forget to force the gc if you use the profiler)
If SpeedPanel is still there, look at what could keep it alive. Look at this discussion for details:...
In your SpeedMediator you have this line:
injector.injectInto(view);
What are you injecting into the view?
Are you using as3-signals? If yes, don't forget to remove their listeners!!
It is a good idea to have a destroy()/clean() method inside of views, that takes care of removing all possible references to the view in order for it to get garbage collected.
So, yes, you can do that, but first try to see what's keeping it alive.
Maybe I misunderstood your question? I'm not sure what you want to be kept alive and what should get destroyed. Do you want to manually mediate/unmediate views?
In case you can't find a solution, try to reproduce the issue in a bare-bone project, where you have only the 3 views/mediators in question. If you want, you can attach the simplified app as a zip and I'll take a look at it. Also, try your scenario with simple Sprites that don't extend a Starling sprite. Maybe Starling is the culprit ;) Are you using one of the Starling extensions for robotlegs?
Let me know how it goes.
Ondina
2 Posted by ikbalnamli on 23 Jun, 2014 01:59 PM
Hi Ondina,
Thank you for your reply. I have found a solution, yay! Let me answer some of your questions to clarify the case here:
I am using as3-signals, I remove their listeners carefully.
injector.injectInto(view); This line is for PostConstruct.
I am using SARS (Starling extension for robotlegs).
Well after some investigation and debugging about mediators I ended up with the MediatorManager.as class of robotlegs and I realized that Event.REMOVED_FROM_STAGE listener is added to every flash DisplayObject in the addMediator function. Since I use starling DisplayObject these listeners which are responsible for destroying the mediators are never added. Let me put the corresponding code snippet here:
Well I supposed that SARS should have resolved this issue, after some investigation I found out that SARS is not aware of children sprites that are removed.
So I decided to fork your MediatorMap extension and changed imports from flash.display.DisplayObject to starling.display.DisplayObject :)
For now everything works like a charm.
Support Staff 3 Posted by Ondina D.F. on 27 Jun, 2014 08:19 AM
Sorry for the delay in replying.
I have no idea whether Vjekoslav is still maintaining the SARS project, but trying to open an issue on github wouldn't hurt:)
I'm not familiar enough with SARS and Starling to be able to see if there is a better solution to your problem, especially one that doesn't require changing robotlegs' classes.
But, who knows, maybe the solutions I presented in the discussion mentioned below could inspire you, despite my Starling-newbiness ;)...
Ondina D.F. closed this discussion on 11 Jul, 2014 08:10 AM. | http://robotlegs.tenderapp.com/discussions/robotlegs-2/11293-child-sprites-mediators-are-never-destroyed-they-keep-catching-events-from-context | CC-MAIN-2019-13 | refinedweb | 1,023 | 56.05 |
Version... sigh... 702/22/2016 at 19:31 • 0 comments
Version 7 of the PCB. And still issues.
Apparently I soldered the current measurement resistor on badly. The motor driver ground level shifts too much when the motors are driven. Kills theMCU.
I'm back to using the AT32UC3L016. Mainly because it has PWM on every pin. I thought that this would make it easier for me to do the PCB traces. Yeah, no. I also misread the clocking options on the data sheet, so this design is now limited to a 16MHz clock.
The programming interface this time around is the Atmel-proprietary 1-pin protocol. You're going to need a JTAGICE3 or similar to program it if you're going to try this design. Also, as a result of the Atmel merger, the AT32 series is probably on it's way out the door. Support was minimal as it was; now it's going for good.
On the positive side, going to AriettaG25 for the Linux board gives a... compact result. Of course, Raspberry Pi Zero will work just as well if you don't need the second USB port for the camera. Arietta has 2 USB ports available straight away. They set the third to USB slave mode in the kernel driver, from the looks of it.
The best part of this post though? The mechanics. I figured them out. ...No? Well, I was happy with them for a moment...
P.S. I updated the GitHub project. It's now cleaner and has instructions in the README.txt .
V4 published to GitHub07/07/2015 at 07:42 • 0 comments
The 4th version is now published. You never saw version 3. Or version 1. But never fear, for those were dismal failures not worthy of your attention.
In this version there are 2 separate battery packs. Why? Because the 130 size motors were a pain with more than 6 volts. Also, now I don't have to worry about isolating the CPU side from the motor's power line effects.
I read from somewhere online that RC hobby servos usually work down to 3.5V and can accept 3.3V control signals. And here I've been wasting time and energy to put 5V level conversion just for servo control! What a waste. While I'm at it, I might as well remove the 5V regulator from the servos and just connect them to the motor's battery pack. Since I have servos only for the camera, they're not heavily loaded and should be happy with 3-4 AA cells.
That'll also get the servos to the motor-side battery pack and I'll have one less source of interference. Funny how simplification works.
But that's still a bit in the future. Right now, the v4 still has the level shifters and regulator for servo control.
Note to self: Make silk-screen text thicker. It doesn't seem to survive the fab process too well at current thickness.
Code added to GitHub03/14/2015 at 19:30 • 0 comments
I've added a new picture and added all the code to GitHub, so that anyone may now replicate my results.
I received the PCBs for the optocoupler from China already. And I orderd the parts from Farnell. Unfortunately, I'd picked a part for the 1-gate buffer that they turned out not to have in stock. It's in backorder.
No, I'm not going to wait for 6 months for the part to come in stock again. I have another PCB coming from China already. This one will just break out a MicroUSB connector's pins so that I can solder as thick a ground cable in there as it needs.
EDIT: P.S. The new photo isn't just for vanity's sake. I switched battery holders to be able to move the battery much lower. Despite how it looks, it should be much more stable now.
Grounding issue with Raspberry Pi01/13/2015 at 17:35 • 0 comments.
Both motors run, controllable from UART11/28/2014 at 17:36 • 0 comments
Status
90% of components now attached to the controller board. And the rest may not get populated at all, as they seem to be largely unnecessary for the time being. I'd imagined that more servoes could be needed. Adding them later is easy though; I just need to solder on the headers. No software changes necessary.
Finished the class for driving motors with the timer channels and PWM. I'm beginning to think that the choise of MCU paid off after all. I'm using 2 timer channels for motor control, 1 for the servos, and I need 1 for timing periodic tasks and communication timeouts. That leaves 2 timer channels free. Plus simple PWM on any pin if I feel like it.
Added a new picture to the gallery. But I should add it here too... I'll just resize it so it's not as humongous.
Capacitors.
I put 100nF ceramic caps on both motors between the leads and the casing. This should keep the electrical noise to a minimum. But if I ever notice any interference, I still have some ferrite rings I can put on it.
NOTE: If you put all 3 capacitors on a DC motor like I have, remember to make a connection from the casing to the ground. Otherwise the 2 caps from the leads to the casing will do nothing. The ground connection is the black wire in the photo.
Other functions
Servos move on command too. Channel 1 had a small bug. NOTE: If someone took my earlier published code in use, servo channel 1 will not work. I'll see if I can edit in a fix.
A led can be blinked remotely. The first thing I actually implemented, as it's the least likely to break something if I get the code wrong. The worst a red LED can do is burn 5mA of current. So if you ever build a communications link to something that will affect a physical action, try using it on a LED first and leave the other functions commented out until the LED works flawlessly. Trust me, you don't want to test a comms link on an electric motor; your project may run out of control if you do.
Turnigy servos have a continuous rotation mode?10/18/2014 at 14:57 • 0 comments
Things I learned today:
-If nothing seems to work, check that you're toggling the right pin.
-Always double-check your timers' clock source and -rate.
-If the servo PWM signal is outside the 1-2 ms area, Turnigy servos will rotate continuously. Or at least the TGY-1800A model did. And seemed unharmed afterwards.
Dear diary,
I sent the last 4 hours scratching my head because one of the sercvo control pins on the MCU didn't seem to change states. After I finally realized that I could just add to the debugger's watch window the whole class, I realized that both pin number variables (Clk and Rst) had the same number. Traced that to a wrong assignment in the initializer.
After that was sorted out, I realized that the servo I'd connected to the board was rotating continuously at times. I'd set my test code to move all servos approximately 30 degrees every 2 seconds, for 12 seconds total, and then start over from the other extreme. Since this is servos we're talking about, with a PWM control signal, the pulse length was the obvious culprit. And so I checked and double-checked the stated values written to the timer's registers. But those were all in the correct range. Then I observed what the (presumed) pulse width was when it entered continuous rotation. It was around 1.25ms. This had me checking for an off-by-half mistakes in the clock source.
The AVR32 MCU I have here does not sport a prescaler as such. Instead, it has 5 clock inputs that are f32KHzRC, fFB/2 .. fFB/128. The fFB is the speed of the high-speed bus, the same as mu fCPU, which is 10MHz. I'd of course picked the fastest clock signal available. And promptly forgot, a week later when I wrote the code to use it, that it wasn't the 10Mhz of the fCPU, but fFB/2 = fCPU/2 = 10MHz/2 = 5MHz.
Facepalm time. I was producing servo pulses between 2.0ms and 4.0ms. Yes, that would produce unspecified behavior.
I still couldn't be bothered to put my code anywhere online, so here's the servo class:
#include "Servo4017.h" #include <tc.h> #include <gpio.h> void Servo4017::init(uint16_t gpioPinRst, uint16_t gpioPinClk, volatile avr32_tc_t *timer, uint16_t timerChannel, uint8_t pinsInverted) { // Set the initial position to be at 50% of range. // That is, start centered. for(uint16_t i = 0; i < numServoChannels; i++) { mServoPositions[i] = 32768; } mServoNum = 0; mClkPin = gpioPinClk; mRstPin = gpioPinRst; mPinsInverted = pinsInverted; pmTimer = timer; mTimerChannel = timerChannel; // Initialize to the end of the cycle with reset high and clock low. mCycleTimeLeft = 1000; mPhase = 3; gpio_enable_gpio_pin(mClkPin); gpio_enable_gpio_pin(mRstPin); // Take into account the possibly reversed state. if(mPinsInverted == 0) { gpio_configure_pin(mRstPin, (GPIO_DIR_OUTPUT | GPIO_INIT_HIGH)); gpio_configure_pin(mClkPin, (GPIO_DIR_OUTPUT | GPIO_INIT_LOW)); } else { gpio_configure_pin(mRstPin, (GPIO_DIR_OUTPUT | GPIO_INIT_LOW)); gpio_configure_pin(mClkPin, (GPIO_DIR_OUTPUT | GPIO_INIT_HIGH)); } gpio_local_enable_pin_output_driver(mRstPin); gpio_local_enable_pin_output_driver(mClkPin); // TODO: Hardware init tc_waveform_opt_t tcOpts; tcOpts.channel = mTimerChannel; tcOpts.bswtrg = TC_EVT_EFFECT_NOOP; tcOpts.beevt = TC_EVT_EFFECT_NOOP; tcOpts.bcpc = TC_EVT_EFFECT_NOOP; tcOpts.bcpb = TC_EVT_EFFECT_NOOP; tcOpts.aswtrg = TC_EVT_EFFECT_NOOP; tcOpts.aeevt = TC_EVT_EFFECT_NOOP; tcOpts.acpc = TC_EVT_EFFECT_NOOP; tcOpts.acpa = TC_EVT_EFFECT_NOOP; tcOpts.wavsel = TC_WAVEFORM_SEL_UP_MODE_RC_TRIGGER; tcOpts.enetrg = false; tcOpts.eevt = TC_EXT_EVENT_SEL_XC0_OUTPUT; tcOpts.eevtedg = TC_SEL_NO_EDGE; tcOpts.cpcdis = false; // Don't disable on RC compare tcOpts.cpcstop = false; // Don't stop on RC compare tcOpts.burst = TC_BURST_NOT_GATED; tcOpts.clki = TC_CLOCK_RISING_EDGE; tcOpts.tcclks = TC_CLOCK_SOURCE_TC2; // = PBAclock / 2 // Init timer 1 for servo and second-counter duty. int resp = tc_init_waveform (pmTimer, &tcOpts); tc_interrupt_t tcInts; tcInts.covfs = false; tcInts.cpas = false; tcInts.cpbs = false; tcInts.cpcs = true; tcInts.etrgs = false; tcInts.ldras = false; tcInts.ldrbs = false; tcInts.lovrs = false; tc_configure_interrupts(pmTimer, mTimerChannel, &tcInts); // Start the timer. 1.0ms is given for the assertion of reset to take effect. tc_write_rc(pmTimer, mTimerChannel, 1000); tc_start(pmTimer, mTimerChannel); } void Servo4017::setPos(uint16_t servo, uint16_t pos) { if(servo >= numServoChannels) { return; } // Fit the desired servo position to the timing range. uint32_t tmp = pos; tmp *= 10000UL; tmp /= 65535UL; // Add the minimum interrupt protection part. // (It's deducted elsewhere, so don't worry about that.) tmp += 2500; mServoPositions[servo] = tmp; } void Servo4017::interruptCallback(void) { tc_read_sr(pmTimer, mTimerChannel); // Operate as non-volatile in the outermost if-structure uint16_t tmp = mPhase; // This was the 0.75ms high phase for Clk pin if(tmp == 0) { // Set Clk low for Phase 1. if(mPinsInverted == 0) { gpio_local_clr_gpio_pin(mClkPin); } else { gpio_local_set_gpio_pin(mClkPin); } // Set the timer and calculate the remaining time tc_write_rc(pmTimer, mTimerChannel, mServoPositions[mServoNum] / 2); mCycleTimeLeft -= mServoPositions[mServoNum]; mServoNum++; mPhase = 1; } // This was the 0.25ms + (servo position) low time for the Clk pin else if(tmp == 1) { // Not the last servo yet. if(mServoNum < numServoChannels) { // Set Clk high and calculate and set the time if(mPinsInverted == 0) { gpio_local_set_gpio_pin(mClkPin); } else { gpio_local_clr_gpio_pin(mClkPin); } mPhase = 0; tc_write_rc(pmTimer, mTimerChannel, 7500 / 2); } // Was last servo else { mPhase = 3; // Set Rst high if(mPinsInverted == 0) { gpio_local_set_gpio_pin(mRstPin); } else { gpio_local_clr_gpio_pin(mRstPin); } // The remaining cycle time is 4-12ms. Half that is 2 to 6 ms. // The maximum 60,000 ticks just fits to the counter. tc_write_rc(pmTimer, mTimerChannel, mCycleTimeLeft/4); } } else if(tmp == 3) { mPhase = 4; // Set Rst low if(mPinsInverted == 0) { gpio_local_clr_gpio_pin(mRstPin); } else { gpio_local_set_gpio_pin(mRstPin); } // The remaining cycle time, 2 to 6 ms. tc_write_rc(pmTimer, mTimerChannel, mCycleTimeLeft/4); } else // tmp == 4, hopefully... { // Phase 4 is always followed by phase 0. mPhase = 0; // Full cycle time is 20ms = 200,000 ticks. mCycleTimeLeft = 200000; // Start from the first servo again. mServoNum = 0; if(mPinsInverted == 0) { gpio_local_set_gpio_pin(mClkPin); } else { gpio_local_clr_gpio_pin(mClkPin); } // Will clock out the first channel's 0.75ms again tc_write_rc(pmTimer, mTimerChannel, 7500 / 2); } }
And header:
#ifndef __SERVO4017_H__ #define __SERVO4017_H__ #include <stdint.h> #include <tc.h> class Servo4017 { public: Servo4017(){} // Warning!: gpio_local_init() MUST BE DONE BEFORE calling this function. // Init must be called before any other action is taken. // It will initialize the dependencies. Namely the timer interface. void init(uint16_t gpioPinRst, uint16_t gpioPinClk, volatile avr32_tc_t *timer, uint16_t timerChannel, uint8_t pinsInverted); // uint16_t represents full scale of motion for servo, // or that of 1.0ms..2.0ms output pulse length for servo driver. // Halfway-point is therefore max(uint16_t) / 2 void setPos(uint16_t servo, uint16_t pos); void interruptCallback(void); private: Servo4017( const Servo4017 &c ); Servo4017& operator=( const Servo4017 &c ); static const uint16_t numServoChannels = 8; // Timer bits volatile avr32_tc_t *pmTimer; volatile uint16_t mTimerChannel; // Pins to use for output volatile uint16_t mClkPin; volatile uint16_t mRstPin; // Indicates the servo channel currently being counted out volatile uint16_t mServoNum; // The positions of the servos, in timer ticks, plus 0.25ms added for minimum interrupt execution time uint16_t mServoPositions[numServoChannels]; // In phase 0, the Clk pin is set high for 0.75ms. For phase 1, Clk is set low for the duration of 0.25ms + (1.0ms * servo position). // Phase 3 happens when the last servo has been through phase 1, and in it the Rst pin is set high for 1.0ms. // In phase 4 the Rst pin is set low for 20.0ms - (sum of all servos total signalling time). The 20.0ms is // in theory not necessary to be timed accurately. However, some rare servos and other effectors may be sensitive, so time it out. // Phase 4 will be divided to parts that can be counted with the timer channel's current 6.5ms maximum. volatile uint8_t mPhase; // Keeps count of how much longer the current timing cycle must last. All servo signalling times will be deducted // and the remainder waited out at the end of each cycle. volatile uint32_t mCycleTimeLeft; // Are the output pins inverted in functionality? // Note: Documentative comments do not take into account // output polarity unless specifically stating otherwise. volatile uint8_t mPinsInverted; }; #endif //__SERVO4017_H__
C++ on AVR32 with Atmel Studio 6 is a pain10/17/2014 at 20:22 • 0 comments
Dear diary. Remind me not to try "paths less trodden" quite so often.
I spent two evenings this week just trying to figure out why the binary size went from 3k to 50k. The only difference between before and after was my adding an instance of the freshly finished Servo4017 class to the SW.
Looking through the .map file I noticed that a lot of standard library functions, e.g. malloc, were getting linked in. Which I considered weird, since the only instance I'd added was definitely static. I started to remove anything that might cause it. I don't remember the exact order in which I bisected the class, but the problem disappeared immediately after I removed the destructor. Ah, ha...? And WTF...
So, lesson learned: don't be the first or the last to go somewhere. The first ones won't get paved roads, and the last ones usually don't come back with all their body parts.
TL;DR:
Adding a destructor to a C++ class in Atmel Studio causes it to link in half the standard library, including all possible memory control functions.
In other news, I soldered in the TSR-1 regulator for the servos and the 4017 IC itself. I didn't test the library yet though; I've been busy with real life and work. For the same reason you don't get a new photo. Well, I'm also not feeling like celebrating the addition of just a few more components. Let me reiterate: too much real life happening.
And don't get fooled by the front page picture getting changed. It's not a new photo; I just shuffled the photos around to get a better one as the preview image. I'm not usually much for PR, but getting one jolly wrencher and... uh... one follower?... after a few months of the project being up usually means one of two things: Either my project has absolutely no interest to anyone ever. Or I make a crappy first impression. Now, I'm not Einstein, Spielberg or Spock, but I'm rather certain that it's still the second option. And the only way to make a first impression in the project listings is the picture. So... advice for those who may follow: Put a front page photo that has actual object in it. Bonus points if it also has PCBs, gears (or other power transmission mechanics) and/or wiring. Extra bonus for shiny objects and blue LEDs. Trust me on this one.
Boards arrived, assembly underway10/01/2014 at 18:03 • 0 comments
The boards actually arrived 2 weeks ago. I just couln't gather the willpower to write a log entry. Especially seeing as I already got dropped from any competition. But let's see this through anyway. I don't want to end up as a part of the statistics on projects abandoned here after not being selected.
As you can see unless you're blind or browsing ascii-only, I've already started assembly. I like to do the build process in phases, with testing in between.
1. Power input and CPU regulation. Because if I screw it up, I end up with burned components. Burnt components is bad, so testing power input and regulation before assembling further is recommended. Funny fact: I always thought that I should put a 100nF ceramic also on the output of a 1117 regulator. Turns out that I shouldn't, but it still hasn't burned anything, for which I shall say a prayer of thanks to my god.
2. CPU and bypass caps. It has a lot of pins in a small space, so it's the easiest component to destroy with a solder bridge. Can also be destroyed by badly chosen capacitors due to the internal 3.3V->1.8V regulator that will get unstable with low-ESR bypass caps. Tested after soldering by connecting to JTAG and reading ID and voltage.
3. Xtal and caps. Tested by programming CPU to use Xtal and sending out strings
through UART to see that the frequency is as expected.
4. Voltage and temperature measurement, and power cutoff FET and led. This stage is here really to test the cut-off functionality. OK, and allowing you to program your MCU to cut the power if the rest of your board sports an otherwise smoke-producing error.
And that's about how far I've gotten by now. More when I get more soldering done. I solder slow and careful, so don't hold your breath.
Lessons learned this time:
Atmel Studio does not have an easy way to switch to a more lightweight C-library for C++ AVR32 projects. Using sprintf causes the full library to get linked, which takes about 20k of space and is way too much on the 32k of FLASH the AT32UC3L032 sports.
If such a library even exists for AVR32, of which I'm not so certain either. If anyone knows one way or another, leave me a comment. And instructions, please.
In the meanwhile, time to roll my own integer-to-string functions.
Second revision of board almost done08/24/2014 at 14:51 • 0 comments
Don't you hate it when you have to put the work "almost" in your log?
I updated the picture of the layout. You should be able to see now where I'm going with this.
Board TODO:
1. Attach the Board Power FET's control to an MCU I/O. Choose a good pin.
2. Put solderstop-less polygon on the main battery and GND traces, so that I can reinforce those with copper strands after the board is fabbed.
3. Add debug LEDs.
I know that blinking LEDs are bad for the eyesight and sanity of anyone later admiring my handiwork, but they make such wonderful debugging interfaces. ...Alternatively, I could add some more headers to any free pins. Headers conneced to spare I/O pins tend to buffer against screw-ups.
I found someone with a Youku account, so video08/20/2014 at 19:22 • 0 comments
I don't want to know why they have an account, but here's a link to the video required by the rules:
Be warned that it contains absolutely nothing that wasn't written in the description already. In fact, I'm not sure if the video contains enough information to pass the rules check. But it's 22:21 here in my time zone and I didn't sleep enough last night either, so I think I'll just leave good enough alone.
Now to wait for the weekend, and maybe I'll actually finish the PCB redesign. | https://hackaday.io/project/2610/logs | CC-MAIN-2021-31 | refinedweb | 3,473 | 67.25 |
Multithreaded Hash Table
If your application needs a "Hash Table" type of structure you have several options.
One is to use the java.util.Hashtable. In a multithreaded environment it would be safe, but not very efficient. If you have a couple of threads that want to read from the hash table, they will have to wait for each other. This wait is not necessary. There is no problem having multiple threads reading a structure.
Another solution is to use the java.util.HashMap. Again in a multithreaded environment, you have to ensure that it is not modified concurrently or you can reach a critical memory problem, because it is not synchronized in any way.
I thought that the solution was to use the static Collections.synchronizedMap method. I was expecting it to return a better implementation. But if you look at the source code you will realize that all they do in there is just a wrapper with a synchronized call on a mutex, which happens to be the same map, not allowing reads to occur concurrently.
In the Jakarta commons project, there is an implementation that is called FastHashMap. This implementation has a property called fast. If fast is true, then the reads are non-synchronized, and the writes will perform the following steps:
Clone the current structure Perform the modification on the clone Replace the existing structure with the modified clone
This implementation will work fine for the applications that write everything that they need into the structure at startup, and then only perform reads. You can see that writing into this structure is expensive. For the case where you need to do some writes every now and then, it can introduce a significant memory/performance issue.
I wrote a very simple implementation. It starts creating a ReentrantReadWriteLock. Then every time we do a read operation we lock for reading. When we want to do an operation that modifies the structure, we call a write lock.
Here an excerpt from the code:
public class FastSynchronizedMap implements Map,
Serializable {
private final Map m;
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
.
.
.
public V get(Object key) {
lock.readLock().lock();
V value = null;
try {
value = m.get(key);
} finally {
lock.readLock().unlock();
}
return value;
}
public V put(K key, V value) {
lock.writeLock().lock();
V v = null;
try {
v = m.put(key, value);
} finally {
lock.writeLock().lock();
}
return v;
}
.
.
.
}
Note that we do a try finally block, we want to guarantee that the lock is released no matter what problem is encountered in the block.
This implementation works well when you have almost no write operations, and mostly read operations.
When we want to insert into a hash table, we can see that depending on the hash code of the key that we are trying to insert, we will modify only one section of the structure. We could create a lock for each of the sections. In that way we can even have concurrent writes happening at the same time.
An approach like that one is the one followed by the ConcurrentHashMap in the concurrency API. Looking at the implementation is interesting.
There is an inner class called Segment. The Segment is a "specialized version of hash tables". When you want to do an insert or read operation in the ConcurrentHashMap, it first finds the Segment where the key belongs too. After that it proceeds to do the operation on the respective Segment.
Interestingly enough, the Segment uses a ReentrantLock (actually it extends the ReentrantLock, I guess to save an instance). The lock is only used when writing to the table. When a read occurs no lock is performed.
If you are aware of the Java Memory Model you can be asking yourself what about the visibility? Can you get a partially built object when you are accessing it?
Actually, the HashEntry that holds the value, and the value itself are defined as volatile. In that way you are guaranteed to read the value only when it has been fully initialized.
And there is a check after performing the get to make sure a null reference is not being returned (this can happen if the compiler happens to reorder the operations). In the case of a null reference, it performs the lock to ensure that we have the proper visibility and then read the value.
The choice of the structure to use, will depend on the scenario where you want to use it. Understanding how each of the structures work would be the first step into getting the right decision.
If you are working on a web application, and you are loading some data into a hash table when the Servlet is initialized and then just reading the data from concurrent requests a HashMap should suffice. If you are just updating the table from time to time on a very controlled way, an implementation like the one I proposed above would do the job. If you are going to be updating the data often, a ConcurrentHashMap will actually give you better performance. However, if you want to iterate the data, and have guarantees that the data is correct, then may be a Hashtable is the answer.
For those of you who are interested in concurrency, I would encourage you to look at the implementation of the ConcurrentHashMap. I would say that it is a nice source to learn from.
- Login or register to post comments
- Printer-friendly version
- elevy's blog
- 1859 reads | http://weblogs.java.net/blog/elevy/archive/2007/04/multithreaded_h.html | crawl-003 | refinedweb | 911 | 64.1 |
[PATCH 04/10] mm, oom_adj: make sure processes sharing mm have same view of oom_score_adj
From:
Michal Hocko
Date:
Fri Jun 03 2016 - 05:17:58 EST ]
From: Michal Hocko <mhocko@xxxxxxxx>
oom_score_adj is shared for the thread groups (via struct signal) but
this is not sufficient to cover processes sharing mm (CLONE_VM without
CLONE_THREAD resp. CLONE_SIGHAND) and so we can easily end up in a
situation when some processes update their oom_score_adj and confuse
the oom killer. In the worst case some of those processes might hide
from oom killer altogether via OOM_SCORE_ADJ_MIN while others are
eligible. OOM killer would then pick up those eligible but won't be
allowed to kill others sharing the same mm so the mm wouldn't release
the mm and so the memory.
It would be ideal to have the oom_score_adj per mm_struct because that
is the natural entity OOM killer considers. But this will not work
because some programs are doing
vfork()
set_oom_adj()
exec()
We can achieve the same though. oom_score_adj write handler can set the
oom_score_adj for all processes sharing the same mm if the task is not
in the middle of vfork. As a result all the processes will share the
same oom_score_adj. The current implementation is rather pessimistic
and checks all the existing processes by default if there are more than
1 holder of the mm but we do not have any reliable way to check for
external users yet.
Changes since v2
- skip over same thread group
- skip over kernel threads and global init
Changes since v1
- note that we are changing oom_score_adj outside of the thread group
to the log
Signed-off-by: Michal Hocko <mhocko@xxxxxxxx>
---
fs/proc/base.c | 53 ++++++++++++++++++++++++++++++++++++++++++++++++-----
include/linux/mm.h | 2 ++
mm/oom_kill.c | 2 +-
3 files changed, 51 insertions(+), 6 deletions(-)
diff --git a/fs/proc/base.c b/fs/proc/base.c
index 520fa467cad0..f5fa338daaed 100644
--- a/fs/proc/base.c
+++ b/fs/proc/base.c
@@ -1040,14 +1040,13 @@ static ssize_t oom_adj_read(struct file *file, char __user *buf, size_t count,
static int __set_oom_adj(struct file *file, int oom_adj, bool legacy)
{
static DEFINE_MUTEX(oom_adj_mutex);
+ struct mm_struct *mm = NULL;
struct task_struct *task;
int err = 0;
task = get_proc_task(file_inode(file));
- if (!task) {
- err = -ESRCH;
- goto out;
- }
+ if (!task)
+ return -ESRCH;
mutex_lock(&oom_adj_mutex);
if (legacy) {
@@ -1071,14 +1070,58 @@ static int __set_oom_adj(struct file *file, int oom_adj, bool legacy)
}
}
+ /*
+ * Make sure we will check other processes sharing the mm if this is
+ * not vfrok which wants its own oom_score_adj.
+ * pin the mm so it doesn't go away and get reused after task_unlock
+ */
+ if (!task->vfork_done) {
+ struct task_struct *p = find_lock_task_mm(task);
+
+ if (p) {
+ if (atomic_read(&p->mm->mm_users) > 1) {
+ mm = p->mm;
+ atomic_inc(&mm->mm_count);
+ }
+ task_unlock(p);
+ }
+ }
+
task->signal->oom_score_adj = oom_adj;
if (!legacy && has_capability_noaudit(current, CAP_SYS_RESOURCE))
task->signal->oom_score_adj_min = (short)oom_adj;
trace_oom_score_adj_update(task);
+
+ if (mm) {
+ struct task_struct *p;
+
+ rcu_read_lock();
+ for_each_process(p) {
+ if (same_thread_group(task,p))
+ continue;
+
+ /* do not touch kernel threads or the global init */
+ if (p->flags & PF_KTHREAD || is_global_init(p))
+ continue;
+
+ task_lock(p);
+ if (!p->vfork_done && process_shares_mm(p, mm)) {
+ pr_info("updating oom_score_adj for %d (%s) from %d to %d because it shares mm with %d (%s). Report if this is unexpected.\n",
+ task_pid_nr(p), p->comm,
+ p->signal->oom_score_adj, oom_adj,
+ task_pid_nr(task), task->comm);
+ p->signal->oom_score_adj = oom_adj;
+ if (!legacy && has_capability_noaudit(current, CAP_SYS_RESOURCE))
+ p->signal->oom_score_adj_min = (short)oom_adj;
+ }
+ task_unlock(p);
+ }
+ rcu_read_unlock();
+ mmdrop(mm);
+ }
err_unlock:
mutex_unlock(&oom_adj_mutex);
put_task_struct(task);
-out:
return err;
}
diff --git a/include/linux/mm.h b/include/linux/mm.h
index 79e5129a3277..9bb4331f92f1 100644
--- a/include/linux/mm.h
+++ b/include/linux/mm.h
@@ -2248,6 +2248,8 @@ static inline int in_gate_area(struct mm_struct *mm, unsigned long addr)
}
#endif /* __HAVE_ARCH_GATE_AREA */
+extern bool process_shares_mm(struct task_struct *p, struct mm_struct *mm);
+
#ifdef CONFIG_SYSCTL
extern int sysctl_drop_caches;
int drop_caches_sysctl_handler(struct ctl_table *, int,
diff --git a/mm/oom_kill.c b/mm/oom_kill.c
index 25eac62c190c..d60924e1940d 100644
--- a/mm/oom_kill.c
+++ b/mm/oom_kill.c
@@ -415,7 +415,7 @@ bool oom_killer_disabled __read_mostly;
* task's threads: if one of those is using this mm then this task was also
* using it.
*/
-static bool process_shares_mm(struct task_struct *p, struct mm_struct *mm)
+bool process_shares_mm(struct task_struct *p, struct mm_struct *mm)
{
struct task_struct *t;
--
2.8.1 ] | https://lkml.iu.edu/hypermail/linux/kernel/1606.0/02240.html | CC-MAIN-2022-40 | refinedweb | 701 | 61.87 |
Richard Jones' Log: Distutils MANIFEST checking
So it turns out that some programs don't unpack distutils tarballs correctly. My test runner now executes the following code:
def check_manifest(): """Check that the files listed in the MANIFEST are present when the source is unpacked. """ try: f = open('MANIFEST') except: print '\n*** SOURCE ERROR: The MANIFEST file is missing!' sys.exit(1) try: manifest = [l.strip() for l in f.readlines()] finally: f.close() err = [line for line in manifest if not os.path.exists(line)] if err: n = len(manifest) print '\n*** SOURCE ERROR: There are files missing (%d/%d found)!'%( n-len(err), n) sys.exit(1)
Distutils doesn't automatically check the files unpacked from a source distribution against the packaged MANIFEST. I'm not sure that it could, without potentially breaking some of the other distribution mechanisms. This uncertainty comes from having no clue as to how I could make it run this function when someone tries to install Roundup from source... Anyone? :)
Update: I believe the following is safe. Instead of checking the manifest at install time, I check it at build time:
from distutils.command.build import build class build_roundup(build): def run(self): check_manifest() build.run(self)
later:
setup( ... cmdclass = { 'build': build_roundup, }, )
Oh, I want to run it in the setup file (it's defined in there). My concern is that it can't be run for every kind of setup.py invocation - hence I need to figure how to hook it into invocations of the "install" command. And make sure that things like RPM packaging and windows installer thingies don't break.
(and I've added a note to the install regarding WinZIP's classic more, thanks!)
There's a checkbox in WinZIP that allows you to unpack everything into a single directory. In my experience, when people get "errors" from WinZIP (which are warnings that they're overwriting files) and files are missing, they've always messed around with that option.
Adding "If you're using WinZIP's 'classic' interface, make sure the 'Use folder names' check box is checked before you extract the files." to the instructions might help.
As for the sanity check itself, why not add it to the setup.py file?
Cheers /F | http://www.mechanicalcat.net/richard/log/Python/Distutils_MANIFEST_checking | CC-MAIN-2014-52 | refinedweb | 375 | 66.74 |
Hey, readers! Today, we will be having a look at one of the most interesting function of Python NumPy module – numpy.reshape() function.
So, let us begin!
Table of Contents
What is numpy.reshape() function?() function.
Moreover, it allows the programmers to alter the number of elements that would be structured across a particular dimension.
Let us now focus on the syntax of reshape() function in the below section.
Syntax of reshape() function
Have a look at the below syntax!
array.reshape(shape)
- array — The data structure to be reshaped (always an array!)
- shape — Integer tuple values that decide the dimension of the new array
The reshape() function does not alter the elements of the array. It only changes the dimensions of the array i.e. the schema/structure.
Now, let us try to visualize the changes in the dimension using the reshape() function through an example:
Let us consider an array arr = {1,2,3,4,5,6} having dimension 1×6. This array can be re-framed into the following forms:
3×2 dimension:
2×3 dimension:
6×1 dimension:
Let us now implement the concept of reshape() function through some examples as shown below.
Examples of reshape() function
In the below example, we have created a 1-D numpy array using the function
numpy.array(). Further, we have changed the dimensions of the array to 2×2.
import numpy as np a = np.array([1, 2, 3,4]) print("Elements of the array before reshaping: \n", a) reshape = a.reshape(2,2) print("\n Array elements after reshaping: \n", reshape)
Output:
Elements of the array before reshaping: [1 2 3 4] Array elements after reshaping: [[1 2] [3 4]]
Now, we have created a 2 Dimensional Array and have changed the dimension of the array to a 1-D array by providing -1 as the argument to the reshape() function.
import numpy as np a = np.array([[1, 2, 3,4],[2,4,6,8]]) print("Elements of the array before reshaping: \n", a) reshape = a.reshape(-1) print("\n Array elements after reshaping: \n", reshape)
Output:
Elements of the array before reshaping: [[1 2 3 4] [2 4 6 8]] Array elements after reshaping: [1 2 3 4 2 4 6 8]
Here, we have created an array using numpy.arange() function. Then, we have changed the dimension of the array to 2×3 i.e. 2 rows and 3 columns.
import numpy as np a = np.arange(6) print("Elements of the array before reshaping: \n", a) reshape = a.reshape(2,3) print("\n Array elements after reshaping: \n", reshape)
Output:
Elements of the array before reshaping: [0 1 2 3 4 5] Array elements after reshaping: [[0 1 2] [3 4 5]]
Conclusion
By this, we have come to the end of this topic. Hope this article helps in understanding the concept well.
Feel free to comment below, in case you come across any question.
Till then, Happy Learning!! | https://www.journaldev.com/44456/numpy-reshape | CC-MAIN-2021-25 | refinedweb | 495 | 54.73 |
The aim of this example is it to be able to build a 2-bit fulladder using two 1-bit fulladder modules as shown below.
The 1-bit fulladder module should be built using the off-the-shelf logic gates in libLCS. The code is as follows.
#include <iostream> #include <lcs/or.h> #include <lcs/and.h> #include <lcs/not.h> #include <lcs/tester.h> #include <lcs/simul.h> #include <lcs/changeMonitor.h> // All classes of the libLCS are defined in the namespace lcs. using namespace lcs; using namespace std; // Define a class MyFullAdder. Our 1-bit fulladder modules will be instances // of this class. class MyFullAdder { public: // The constructor should take single line Bus<1> objects as inputs, one each for // the two data lines, carry input, sum output and the carry output. MyFullAdder(const Bus<1> &S, const Bus<1> &Cout, const Bus<1> &A, Bus<1> &B, Bus<1> &Cin); // The destructor. ~MyFullAdder(); private: // a, b, c are the two data inputs and the carry input respectively. Bus<1> a, b, c; // s is the sum output, and cout is the carry output. Bus<1> s, cout; // A pointer member for each of the gates which constitute our FullAdder. // The number and type of the gates is same as in the 1st basic example. Not<> *n1, *n2, *n3; And<3> *sa1, *sa2, *sa3, *sa4; And<3> *ca1, *ca2, *ca3, *ca4; Or<4> *so, *co; }; MyFullAdder::MyFullAdder(const Bus<1> &S, const Bus<1> &Cout, const Bus<1> &A, Bus<1> &B, Bus<1> &Cin) : a(A), b(B), c(Cin), s(S), cout(Cout) { Bus<> a_, b_, c_, s1, s2, s3, s4, c1, c2, c3, c4; // Each of the gates should be initialised with proper bus // connections. The connections are same as in the 1st basic // example. // Initialising the NOT gates. n1 = new Not<>(a_, a); n2 = new Not<>(b_, b); n3 = new Not<>(c_, c); // Initialising the AND gates for the // minterms corresponding to the sum output. sa1 = new And<3>(s1, (a_,b_,c)); sa3 = new And<3>(s3, (a,b_,c_)); sa2 = new And<3>(s2, (a_,b,c_)); sa4 = new And<3>(s4, (a,b,c)); // Initialising the AND gates for the // minterms corresponding to the carry output. ca1 = new And<3>(c1, (a_,b,c)); ca2 = new And<3>(c2, (a,b_,c)); ca3 = new And<3>(c3, (a,b,c_)); ca4 = new And<3>(c4, (a,b,c)); // Initialising the OR gates which // generate the final outputs. so = new Or<4>(s, (s1,s2,s3,s4)), co = new Or<4>(cout, (c1,c2,c3,c4)); } MyFullAdder::~MyFullAdder() { // The destructor should delete each of the gates // which were initialised during construction. delete n1; delete n2; delete n3; delete sa1; delete sa2; delete sa3; delete sa4; delete ca1; delete ca2; delete ca3; delete ca4; delete so; delete co; } int main(void) { // Declaring the busses involved in out circuit. // Note that the bus c0 (the carry input to the first full-adder) // has been initialised with a value of 0 (or lcs::LOW) on its line. Bus<> a1, b1, a2, b2, c0(0), S1, C1, S2, C2; // Initialising the 1-bit full adder modules. MyFullAdder fa1(S1, C1, a1, a2, c0), fa2(S2, C2, b1, b2, C1); // Initialising monitor objects which monitor the inputs and the // 3 sum bits. ChangeMonitor<4> inputMonitor((a1,b1,a2,b2), "Input", DUMP_ON); ChangeMonitor<3> outputMonitor((S1,S2,C2), "Sum", DUMP_ON); // Initialising a tester object which feeds in different inputs // into our circuit. Tester<4> tester((a1,b1,a2,b2)); Simulation::setStopTime(2000); // Set the time upto which the simulation should run. Simulation::start(); // Start the simulation. return 0; }
When the above code is compiled and run, the following output is obtained.
At time: 0, Input: 0000 At time: 0, Sum: 000 At time: 200, Input: 0001 At time: 200, Sum: 001 At time: 300, Input: 0010 At time: 300, Sum: 010 At time: 400, Input: 0011 At time: 400, Sum: 011 At time: 500, Input: 0100 At time: 500, Sum: 001 At time: 600, Input: 0101 At time: 600, Sum: 010 At time: 700, Input: 0110 At time: 700, Sum: 011 At time: 800, Input: 0111 At time: 800, Sum: 100 At time: 900, Input: 1000 At time: 900, Sum: 010 At time: 1000, Input: 1001 At time: 1000, Sum: 011 At time: 1100, Input: 1010 At time: 1100, Sum: 100 At time: 1200, Input: 1011 At time: 1200, Sum: 101 At time: 1300, Input: 1100 At time: 1300, Sum: 011 At time: 1400, Input: 1101 At time: 1400, Sum: 100 At time: 1500, Input: 1110 At time: 1500, Sum: 101 At time: 1600, Input: 1111 At time: 1600, Sum: 110
Below is the screenshot of the gtkwave plot of the generated VCD file. | http://liblcs.sourceforge.net/one_bit_fa_gate_level_module.html | CC-MAIN-2017-22 | refinedweb | 796 | 67.99 |
This article has been excerpted from book "Graphics Programming with GDI+".So far we have seen only the draw methods of the Graphics class. As we discussed earlier, pens are used to draw the outer boundary of graphics, shapes, and brushes are used to fill the interior of graphics shapes. In this section we will cover the Fill methods of the Graphics class. You can fill only certain graphics shapes; hence there are only a few Fill methods available in the Graphics class. Table 3.5 lists them.The FillCloseCurve MethodFillCloseCurve fills the interior of a closed curve. The first parameter of FillClosedCurve is a brush. It can be solid brush, a hatch brush, or a gradient brush. The second parameter is an array of points. The third and fourth parameters are optional. The third parameter is a fill mode, which is resented by the FillMode enumeration. The FillMode enumeration specifies the way the interior of a closed path is filled. It has two modes: alternate or winding. The values for alternate and winding are Alternate and Winding, respectively. The default mode is Alternate. The fill mode matters only if the curve intersects itself (see Section 3.2.1.10).To fill a closed curve using FillClosed Curve, an application first creates a Brush object and an array of points for the curve. The application can then set the fill mode and tension (which is optional) and call FillClosedCurve.Listing 3.24 creates an array of PointF structures and a SolidBrush object, and calls FillClosedCurve.LISTING 3.24: Using FillClosedCurve to fill a closed curveprivate void Form1_Paint (object sender, System.Windows.Forms.PaintEventArgs e) { // Create a pen Pen bluePen = new Pen (Color.Blue, 1); // Create an array of points, 90.0F); PointF[] ptsArray = { pt1, pt2, pt3, pt4, pt5 }; // Fill a closed curve float tension = 1.0F; FillMode flMode = FillMode.Alternate; SolidBrush blueBrush = new SolidBrush(Color.Blue); e.Graphics.FillClosedCurve(blueBrush,ptsArray,flMode,tension); // Dispose of object blueBrush.Dispose(); }TABLE 3.5: Graphics fill methods
FillCloseCurve
Fills the interior of a closed cardinal spline curve defined by an array of Point structures.
FillEllipse
Fills the interior of an ellipse defined by a bounding rectangle specified by a pair of coordinates, a width and a height.
FillPath
Fills the interior of a GraphicsPath object.
FillPie
Fills the interior of a pie section defined by an ellipse specified by a pair of coordinates, a width, a height, and two radial lines.
FillPolygon
Fills the interior of a polygon defined by an array of points specified by Point structures.
FillRectangle
Fills the interior of a rectangle specified by a pair of a coordinates, a width, and a height.
FillRectangles
Fills the interiors of a series of rectangles specified by Rectangle structures.
FillRegion
Fills the interiors of a Region object.
{ // Create a solid brush SolidBrush greenBrush = new SolidBrush(Color.Green); //); // Fill path e.Graphics.FillPath(greenBrush, path); // Dispose of object greenBrush.Dispose(); }}Figure 3.38 shows the output from Listing 3.26. As the figure shows, the fill method fills all the covered areas of a graphics path.FIGURE: 3.38: Filling a graphics pathThe FillPie MethodFillPie fills a pie section with a specified brush. It takes four parameters: a brush, the rectangle of the ellipse, and the start and sweep angles. The following code calls FillPie.g.FillPie(new SolidBrush (Color.Red),0.0F, 0.0F, 100, 60, 0.0F, 90.0F);The FillPolygon MethodFillPolygon fills a polygon with the specified brush. It takes three parameters: a brush, an array of points, and a fill mode. The FillMode enumeration defines the fill mode of the interior of the path. It provides two fill modes: Alternate and Winding. The default mode is Alternate.In our application we will use a hatch brush. So far we have seen only a solid brush. A solid brush is a brush with one color only. A hatch brush is a brush with a hatch style and two colors. These colors work together to support the hatch style. The HatchBrush class represents a hatch brush.The Code in Listing 3.27 uses FillPolygon to fill a polygon using the Winding mode.LISTING 3.27: Filling a polygonGraphics g = e.Graphics;// Create a solid brushSolidBrush greenBrush = new SolidBrush (Color.Green);// Create points for polygonPointF p1 = new PointF (40.0F, 50.0F);PointF p2 = new PointF (60.0F, 70.0F);PointF p3 = new PointF (80.0F, 34.0F);PointF p4 = new PointF (120.0F, 180.0F);PointF p5 = new PointF (200.0F, 150.0F);PointF[] ptsArray ={p1, p2, p3, p4, p5};// Draw polygone.Graphics.FillPolygon (greenBrush, ptsArray);// Dispose of objectsgreenBrush.Dispose();Figure 3.39 shows the output from Listing 3.27. As you can see, the fill method fills all the areas of a polygon.Filling Rectangle and RegionsFillRectangle fills a rectangle with a brush. This method takes a brush and a rectangle as arguments. FillRectangles fills a specified series of rectangles with a brush, and it takes a brush and an array of rectangles. These methods also have overloaded forms with additional options. For instance, if you're using a HatchStyle brush, you can specify background and foreground colors. Note: The HatchBrush class is defined in the System.Drawing.Drawing2D namespace.The source code in Listing 3.28 uses FillRectangle to fill two rectangles. One rectangle is filled with a hatch brush, the other with a solid brush.LISTING 3.28: Filling rectangleprivate void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e) { // Create brushes SolidBrush blueBrush = new SolidBrush(Color.Blue); // Create a rectangle Rectangle rect = new Rectangle(10, 20, 100, 50); // Fill rectangle e.Graphics.FillRectangle(new HatchBrush(HatchStyle.BackwardDiagonal, Color.Yellow, Color.Black), rect); e.Graphics.FillRectangle(blueBrush, new Rectangle(150, 20, 50, 100)); // Dispose of object blueBrush.Dispose(); }Figure 3.40 shows the output from Listing 3.28FillRegion fills a specified region with a brush. This method takes a brush and a region as input parameters. Listing 3.29 creates a Region object from a rectangle and calls FillRegion to fill the region.LISTING 3.29: Filling regionsRectangle rect = new Rectangle (20, 20, 150, 100);Region rgn = new Region(rect);e.Graphics.FillRegion(new SolidBrush (Color.Green), rgn);ConclusionHope the article would have helped you in understanding Fill Methods in GDI+. Read other articles on GDI+ on the website.
Fill Methods in GDI+
Working with Brushes and Pens in GDI+
Hi all.I have a big problem with filling an open GraphicsPath figure with Graphics.FillPath(brush, path).According to MSDN 'the path is filled as if the open figure were closed by a straight line from its ending point to its starting point.' In this case figure similar to ie. 'e' drawed created as one open figure by adding lines and Beziers is filled as if it is closed. The result I want to achieve is ONLY the upper part of the fig filled. Can any one suggest me a sollution ? | http://www.c-sharpcorner.com/UploadFile/mahesh/fill-methods-in-gdi/ | crawl-003 | refinedweb | 1,153 | 61.12 |
Hey,
I've just blogged about using Office 365 client libraries in Xamarin.Android application. The blog post, 'Put Some Office 365 in Your Apps' can be read here:
Do let me know your views and feedback.
Mayur
Thanks for the post, It would be great to get this integration working esp. considering Xamarin's close relationship with Microsoft. However It's important to note this functionality is in early preview and is pretty buggy and very sparsely documented so far IMO, so appreciate your post in that regard:
Case in Point: I have been trying to get a Xamarin.iOS app authenticating to a sharepoint online instance using these new Office365 libraries working for nearly 2 weeks now with no luck.
I also followed along with your post and this one to try the Office365 API on Xamarin.iOS:
However I have been running into authentication and Visual Studio issues:
Some background - I have an MSDN Subscription access to Azure and Office 365
I created an instance of Sharepoint Online (a site collection) using my MSDN developer subscription
I associated my SharePoint online site tenant with my AD instance
see
AND I followed the steps here:
3.I used my MSDN account to setup an Azure AD instance for Office 365
to register a client application :
-See:
using these instructions:
_
noting that:_
"On the sign-in dialog box, enter the username and password for your Office 365 tenant (Figure 3). We recommend that you use your Office 365 Developer Site. Often, this user name will follow the pattern
@.onmicrosoft.com.
If you do not have a developer site, you can get a free Developer Site as part of your MSDN Benefits, or sign up for a free trial. Be aware that the user must be an admin user—but for tenants created as part of an Office 365 Developer Site, this is likely to be the case already.''
screenshot of error:
References
SO issue link:
Authentication Process:
I also tried some of the code here:
Ran into issues similar to those posted here
REST based authentication option:
Sample Code (REST Authentication & Windows 8)
using .NET client libraries in windows 8 (it would be great if this functionality was available in Xamarin)
Thanks for the reply Ahmed.
I'm aware that many users are having issues integrating O365 libraries and services into their apps. And also there is limited documentation as those libraries are still in preview.
However, I would like to suggest you to re-check your SharePoint Online/O365 configuration with Azure AD. Because, I just tried (in Visual Studio using Xamarin.Android) adding reference to O365 services and it worked for me. And I believe it can consume services too from SharePoint. I've yet to try in Xamarin.iOS though.
Please, see attached image which shows I can successfully add O365 services to my app. Here, I'm having similar setup, i.e. personal MSDN subscription, configured with O365 Dev Account and SharePoint sites.
Let me know if you're still facing any issues.
Hope this helps.
Mayur
Thanks -yes I'll keep working on it!
Hey Mayur,
are there any plans to provide O365 API as component for Xamarin Studio? I've used it with VS but regarding my current App I'd like to build an iOS only... So this is actually the only reason why I will have to power on a windows machine.... Trying to get rid of it
Hello Mayur,
Awesome post! helped a lot!. One question though, do you happen to know if I could somehow reproduce manually the registing process of the Office API that is done in Visual Studio but in Xamarin Studio?
I followed your instructions mimicking your solution and I managed to add the Office 365 API package from Studio and all the code seemed to be working fine except that it gave me a blank screen without authentication
.
Then I got my hands dirty and noticed that when you register the API from Visual Studio it adds a [assembly: Microsoft.Office365.OAuth.ClientId line in the assemblyInfo.
I tried my luck and I added this line on Xamarin Studio and voila, Auth screen buuuut it just won't login...I guess that it detects that it is not the original app registered...so much for my hacking
Any ideas would help a fellow developer 4 days ahead of a presentation and poor as a rat
Cheers!
J
We are working hard to ensure that the bugs that appear in the Preview will be eliminated once we go into General Availability with these Connected Services. Keep an eye on blogs.office.com for news and code samples that we'll ship very soon.
Hello Thorsten,
Even I would love to have a component or NuGet for this API. But current VS extension does a lot of heavy work behind the scene (e.g. register the app in Azure Active Directory). Having said that, I don't have exact information on this. I'll keep posted once I get any confirmation.
Hi there,
About the Office 365 mail API, anyone has any idea how to retrieve the (rfc 822) message ID from the header? I can get the ID that Microsoft supplies but I need the unique one that is common in every header.
Thank you very much!
André
Great article. I'm having an issue with the latest Microsoft Office 365 Authentication library released on 10/28. I get the following error when adding a connected service.
install-package : Could not install package 'Microsoft.IdentityModel.Clients.ActiveDirectory 2.10.10910.1511'. You are trying to install this package into a project that targets 'MonoAndroid,Version=v2.2',
but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
I can get around this if I use the Nuget package manager to install the pre-release version from August 4. Any ideas?
Thanks,
Brian
The error is because the Microsoft.IdentityModel.Clients.ActiveDirectory 2.10.10910.1511 NuGet package does not have any assemblies that support MonoAndroid projects.
The pre-release NuGet package supports both MonoAndroid and iOS Classic projects.
Thanks for the response Matt. I was aware that the issue was related to the Microsoft.IdentityModel.Clients.ActiveDirectory 2.10.10910.1511 package. I was hoping that someone would have a way around this or know why Microsoft's latest package doesn't support MonoAndroid. Is this a bug or an intentional decision by Microsoft.
Brian
@BrianFraser - I believe that Microsoft have only recently spent time re-developing the Microsoft.IdentifyModel.Clients.ActiveDirectory NuGet package so it supports Xamarin.
I suspect you will not be able to extract the assembly from the non-pre-release NuGet package and use it from within an MonoAndroid project since it will likely use parts of the .NET framework not supported by MonoAndroid.
Looking at the Office 365 Client sample GitHub repository it looks like an old version 0.1.0-alpha of the Microsoft.Office365.OAuth.Xamarin NuGet package is used which does not have a dependency on Microsoft.IdentifyModel.Clients.ActiveDirectory so you could use that instead.
Right now the latest Office 265 OAuth Xamarin NuGet package will not install into an MonoAndroid project. Hopefully Microsoft will fix that.
Hi guys, I am investigating if this library is usefull for my current project. I have a Xamarin.Forms app, which support all 3 platforms.
To test some stuff out I created a new Shared Project and I could successfully add the Office 365 service for my IOS and Android project, but when I try to do so for Windows Phone I can login with my credentials but then I get the message as shown in the image.
So this raises a few questions for me:
Is this library supported for the Windows Phone (Silverlight) project in Xamarin?
If it is, can you help me understand what the message is saying or how I can resolve it?
I have to login with my own Office 365 credentials to add the connected service, but is it also possible to connect to a different Office 365 environment at runtime -> the user enters his/her own credentials..? I do not understand why I have to login with my own credentials to add these libraries.
This library is well supported on Windows/Phone apps. Not sure why are you getting this message. I tried to reproduce but I couldn't. May be a wrong question but, are you logging in as admin? I'll try once again to reproduce.
Regarding 3rd point: you're talking about multi-tenant applications. i.e. even though you register this app in your AD, when I log-in into your app, using my credentials, I should manage my O365 environment. As far as I understand, by default, native apps are multi-tenant and you don't need to do anything special.
Hmm well I did just gave up on trying because I read that Silverlight is not supported by these libraries in the comments of a blog? Are you sure you created a Xamarin Forms / Windows Phone Silverlight project and not a WinRT version?
Because I tried creating a new Silverlight project and then add this service but I got the same error. I also tried to add the libraries via NuGet myself, but I could not find the platform specific part for Windows Phone, which should be something like: Microsoft.Office365.OAuth.WinPhone (My other projects reference a Microsoft.Office365.OAuth.Android and Microsoft.Office365.OAuth.iOS)
If you did create a Silverlight project, could you maybe share this project with me, so I can maybe see any differences?
About the multi-tenant, that is what I expected so good to hear! But I still do not understand why I have to login when adding this connected service?
And also: I am not an admin of the O365 environment, do you think that should make a difference? I doubt it, because I don't have any problems with IOS and Android.
@MayurTendulkar I am trying to integrate the current Office 365 API Tools (v 1.0.22) in my Xamarin Android app. I am having trouble connecting the dots here, because I can't seem to find a useful tutorial for this. Your sample project also uses an older version (0.1.0-alpha). Do you have any good point to start with? Or do you maybe have a sample project with the newer version yourself?
@Guido_Kersten Can you follow this updated blog post to see if it helps you?
Let me know if you have any specific questions.
Hi guys
I hope someone can help me, I am trying to create a xamarin android app that connects to office 365 to pull contact information. I am trying to follow the methods demonstrated here:
I am able to add the connected service to my application and all the assemblies download although the sample cs files visible in the screenshot for step 4 from the tutorial(ActiveDirectorApiSample, CalendarApiSample etc) do not get added into my project. view screenshot1
When trying to add the EnsureClientCreated() method visual studio warns me that the Authenticator namespace could not be found so I try and add it . view screenshot2
I noticed that visual studio tries to add using Xamarin.Auth but if I check the source code from the tutorial I am following the Xamarin.Auth reference is not there:
If I use Xamarin.Auth then visual studio throws the error in screenshot3
can anyone confirm how I can resolve the Authenticator errors?
Hello there. The O365 tooling and API has changed a lot since this blog post last published. I'm working on updating the post with correct samples. Once it is updated, I'll post it here.
Thanks for showing the interest.
Hi Mayur
That will be awesome, I will be waiting for the updates.
Thanks!
Hi Mayur
Do you think this is something you will be able to complete soon? I am working on a project for my company that requires office 365 connectivity so access to the updated information soon would really be appreciated. if not the do you have any suggestions, links etc that could help out?
back is the primary muscle by services secondary must so is almost you almost get super muscle its overlap each other so is no me to really train them the gnome to three times awake I'm I make sure their breasts I’m resting as much as I can because risks you know is wonder most important things you can do some iris probably a week between each muscle and I make sure that I'm getting real good though you know that's going to be key may she had a real good give wrong path because you are we doing begin for another week and the next question is do you dislike districts in and I can't stress this enough you know for gas this really looking to put on its size and put on a mass and .
Hello, I've recently published a blog which talks about another component of Office 365 - OneDrive for Business. It discusses about how authentication works and how new APIs can be used. There are similar kind of APIs for Outlook, SharePoint, etc... You can read it here: | http://forums.xamarin.com/discussion/21367/put-some-office-365-in-your-apps | CC-MAIN-2015-18 | refinedweb | 2,245 | 63.49 |
ossp-uuid (3) - Linux Man Pages
ossp-uuid: OSSP Universally Unique Identifier
NAME
uuid - OSSP Universally Unique Identifier
VERSIONOSSP uuid 1.6.2 (04-Jul-2008)
DESCRIPTIONOSSP uuid is a ISO-C:1999 application programming interface (API) and corresponding command line interface (CLI) for the generation of DCE 1.1, ISO/IEC 11578:1996 and IETF++:1998, is the ISO-C application programming interface (API) of OSSP uuid.
UUID Binary Representation
According to the DCE 1.1, ISO/IEC 11578:1996 and IETF RFC-4122 standards, a DCE 1.1 variant UUID is a 128 bit number defined out of 7 fields, each field a multiple of an octet in size and stored in network byte order:
[4] version -->| |<-- | | | | [16] [32] [16] | |time_hi time_low time_mid | _and_version |<---------------------------->||<------------>||<------------>| | MSB || || | | | / || || | | |/ || || | | +------++------++------++------++------++------++------++------+~~ | 15 || 14 || 13 || 12 || 11 || 10 |####9 || 8 | | MSO || || || || || |#### || | +------++------++------++------++------++------++------++------+~~ 7654321076543210765432107654321076543210765432107654321076543210 ~~+------++------++------++------++------++------++------++------+ ##* 7 || 6 || 5 || 4 || 3 || 2 || 1 || 0 | ##* || || || || || || || LSO | ~~+------++------++------++------++------++------++------++------+ 7654321076543210765432107654321076543210765432107654321076543210 | | || || /| | | || || / | | | || || LSB | |<---->||<---->||<-------------------------------------------->| |clk_seq clk_seq node |_hi_res _low [48] |[5-6] [8] | | -->| |<-- variant [2-3]
An example of a UUID binary representation
. The binary representation format is exactly what the OSSP uuid API functions uuid_import() and uuid_export() deal with under UUID_FMT_BIN
.
UUID ASCII String Representation
According to the DCE 1.1, ISO/IEC 11578:1996 and IETF RFC-4122 standards, a DCE 1.1 variant UUID is represented as an ASCII string consisting of 8 hexadecimal digits followed by a hyphen, then three groups of 4 hexadecimal digits each followed by a hyphen, then 12 hexadecimal digits. Formally, the string representation is defined by the following grammar:
uuid = <time_low> "-" <time_mid> "-" <time_high_and_version> "-" <clock_seq_high_and_reserved> <clock_seq_low> "-" <node> time_low = 4*<hex_octet> time_mid = 2*<hex_octet> time_high_and_version = 2*<hex_octet> clock_seq_high_and_reserved = <hex_octet> clock_seq_low = <hex_octet> node = 6*<hex_octet> hex_octet = <hex_digit> <hex_digit> hex_digit = "0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9" |"a"|"b"|"c"|"d"|"e"|"f" |"A"|"B"|"C"|"D"|"E"|"F"
An example of a UUID string representation is the ASCII string
"
f81d4fae-7dec-11d0-a765-00a0c91e6bf6
". The string representation format is exactly what the OSSP uuid API functions uuid_import() and uuid_export() deal with under UUID_FMT_STR
.
Notice: a corresponding URL can be generated out of a ASCII string
representation of an UUID by prefixing with "
urn:uuid:
`` as in '' urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6
".
UUID Single Integer Value Representation
According to the ISO/IEC 11578:1996 and ITU-T Rec. X.667 standards, a DCE 1.1 variant UUID can be also represented as a single integer value consisting of a decimal number with up to 39 digits.
An example of a UUID single integer value representation is the decimal
number "329800735698586629295641978511506172918". The string
representation format is exactly what the OSSP uuid API functions
uuid_import() and uuid_export() deal with under
UUID_FMT_SIV
.
Notice: a corresponding ISO OID can be generated under the
``{joint-iso-itu-t(2) uuid(25)}'' arc out of a single integer value
representation of a UUID by prefixing with "2.25.``. An example OID
is ''2.25.329800735698586629295641978511506172918``. Additionally,
an URL can be generated by further prefixing with ''
urn:oid:
`` as in '' urn:oid:2.25.329800735698586629295641978511506172918
".
UUID Variants and Versions
A UUID has a variant and version. The variant defines the layout of the UUID. The version defines the content of the UUID. The UUID variant supported in OSSP uuid is the DCE 1.1 variant only. The DCE 1.1 UUID variant versions supported in OSSP uuid are:
- Version 1 (time and node based)
- These are the classical UUIDs, created out of a 60-bit system time, a 14-bit local clock sequence and 48-bit system MAC address. The MAC address can be either the real one of a physical network interface card (NIC) or a random multi-cast MAC address. Version 1 UUIDs are usually used as one-time global unique identifiers.
- Version 3 (name based, MD5)
- These are UUIDs which are based on the 128-bit MD5 message digest of the concatenation of a 128-bit namespace UUID and a name string of arbitrary length. Version 3 UUIDs are usually used for non-unique but repeatable message digest identifiers.
- Version 4 (random data based)
- These are UUIDs which are based on just 128-bit of random data. Version 4 UUIDs are usually used as one-time local unique identifiers.
- Version 5 (name based, SHA-1)
- These are UUIDs which are based on the 160-bit SHA-1 message digest of the concatenation of a 128-bit namespace UUID and a name string of arbitrary length. Version 5 UUIDs are usually used for non-unique but repeatable message digest identifiers.
UUID Uniqueness
Version 1 UUIDs are guaranteed to be unique through combinations of hardware addresses, time stamps and random seeds. There is a reference in the UUID to the hardware (MAC) address of the first network interface card (NIC) on the host which generated the UUID --- this reference is intended to ensure the UUID will be unique in space as the MAC address of every network card is assigned by a single global authority (IEEE) and is guaranteed to be unique. The next component in a UUID is a timestamp which, as clock always (should) move forward, will be unique in time. Just in case some part of the above goes wrong (the hardware address cannot be determined or the clock moved steps backward), there is a random clock sequence component placed into the UUID as a ``catch-all'' for uniqueness.
Version 3 and version 5 UUIDs are guaranteed to be inherently globally unique if the combination of namespace and name used to generate them is unique.
Version 4 UUIDs are not guaranteed to be globally unique, because they
are generated out of locally gathered pseudo-random numbers only.
Nevertheless there is still a high likelihood of uniqueness over space
and time and that they are computationally difficult to guess.
Nil UUID
There is a special Nil UUID consisting of all octets set to zero in the binary representation. It can be used as a special UUID value which does not conflict with real UUIDs.
APPLICATION PROGRAMMING INTERFACEThe ISO-C Application Programming Interface (API) of OSSP uuid consists of the following components.
CONSTANTS
The following constants are provided:
- UUID_VERSION
- The hexadecimal encoded OSSP uuid version. This allows compile-time checking of the OSSP uuid version. For run-time checking use uuid_version() instead.
The hexadecimal encoding for a version "$v.$r$t$l" is calculated with the GNU shtool version command and is (in Perl-style for concise description) "sprintf('0x%x%02x%d%02x', $v, $r, {qw(s 9 . 2 b 1 a 0)}->{$t}, ($t eq 's' ? 99 : $l))``, i.e., the version 0.9.6 is encoded as ''0x009206".
- UUID_LEN_BIN, UUID_LEN_STR, UUID_LEN_SIV
- The number of octets of the UUID binary and string representations. Notice that the lengths of the string representation (UUID_LEN_STR) and the lengths of the single integer value representation (UUID_LEN_SIV) does not include the necessary NUL
termination character.
- UUID_MAKE_V1, UUID_MAKE_V3, UUID_MAKE_V4, UUID_MAKE_V5, UUID_MAKE_MC
- The mode bits for use with uuid_make(). The UUID_MAKE_VN specify which UUID version to generate. The UUID_MAKE_MC forces the use of a random multi-cast MAC address instead of the real physical MAC address in version 1 UUIDs.
- UUID_RC_OK, UUID_RC_ARG, UUID_RC_MEM, UUID_RC_SYS, UUID_RC_INT, UUID_RC_IMP
- The possible numerical return-codes of API functions. The UUID_RC_OK
indicates success, the others indicate errors. Use uuid_error() to translate them into string versions.
- UUID_FMT_BIN, UUID_FMT_STR, UUID_FMT_SIV, UUID_FMT_TXT
- The fmt formats for use with uuid_import() and uuid_export(). The UUID_FMT_BIN indicates the UUID binary representation (of length UUID_LEN_BIN), the UUID_FMT_STR indicates the UUID string representation (of length UUID_LEN_STR), the UUID_FMT_SIV indicates the UUID single integer value representation (of maximum length UUID_LEN_SIV) and the UUID_FMT_TXT indicates the textual description (of arbitrary length) of a UUID.
FUNCTIONS
The following functions are provided:
- uuid_rc_t uuid_create(uuid_t **uuid);
- Create a new UUID object and store a pointer to it in *
uuid. A UUID object consists of an internal representation of a UUID, the internal PRNG and MD5 generator contexts, and cached MAC address and timestamp information. The initial UUID is the Nil UUID.
- uuid_rc_t uuid_destroy(uuid_t *uuid);
- Destroy UUID object uuid.
- uuid_rc_t uuid_clone(const uuid_t *uuid, uuid_t **uuid_clone);
- Clone UUID object uuid and store new UUID object in uuid_clone.
- uuid_rc_t uuid_isnil(const uuid_t *uuid, int *result);
- Checks whether the UUID in uuid is the Nil UUID. If this is the case, it returns true in *
result. Else it returns false in *
result.
- uuid_rc_t uuid_compare(const uuid_t *uuid, const uuid_t *uuid2, int *result);
- Compares the order of the two UUIDs in uuid1 and uuid2 and returns the result in *
result: -1
if uuid1 is smaller than uuid2, 0 if uuid1 is equal to uuid2 and +1 if uuid1 is greater than uuid2.
- uuid_rc_t uuid_import(uuid_t *uuid, uuid_fmt_t fmt, const void *data_ptr, size_t data_len);
- Imports a UUID uuid from an external representation of format fmt. The data is read from the buffer at data_ptr which contains at least data_len bytes.
The format of the external representation is specified by fmt and the minimum expected length in data_len depends on it. Valid values for fmt are UUID_FMT_BIN, UUID_FMT_STR and UUID_FMT_SIV.
- uuid_rc_t uuid_export(const uuid_t *uuid, uuid_fmt_t fmt, void *data_ptr, size_t *data_len);
- Exports a UUID uuid into an external representation of format fmt. Valid values for fmt are UUID_FMT_BIN, UUID_FMT_STR, UUID_FMT_SIV and UUID_FMT_TXT.
The data is written to the buffer whose location is obtained by dereferencing data_ptr after a ``cast'' to the appropriate pointer-to-pointer type. Hence the generic pointer argument data_ptr is expected to be a pointer to a ``pointer of a particular type'', i.e., it has to be of type " unsigned char **
" for UUID_FMT_BIN and " char **
" for UUID_FMT_STR, UUID_FMT_SIV and UUID_FMT_TXT.
The buffer has to be room for at least *
data_len bytes. If the value of the pointer after ``casting'' and dereferencing data_ptr is NULL
, data_len is ignored as input and a new buffer is allocated and returned in the pointer after ``casting'' and dereferencing data_ptr (the caller has to free(3) it later on).
If data_len is not NULL
, the number of available bytes in the buffer has to be provided in *
data_len and the number of actually written bytes are returned in *
data_len again. The minimum required buffer length depends on the external representation as specified by fmt and is at least UUID_LEN_BIN for UUID_FMT_BIN, UUID_LEN_STR for UUID_FMT_STR and UUID_LEN_SIV for UUID_FMT_SIV. For UUID_FMT_TXT a buffer of unspecified length is required and hence it is recommended to allow OSSP uuid to allocate the buffer as necessary.
- uuid_rc_t uuid_load(uuid_t *uuid, const char *name);
- Loads a pre-defined UUID value into the UUID object uuid. The following name arguments are currently known:
- name UUID
-
- nil 00000000-0000-0000-0000-000000000000
-
- ns:DNS 6ba7b810-9dad-11d1-80b4-00c04fd430c8
-
- ns:URL 6ba7b811-9dad-11d1-80b4-00c04fd430c8
-
- ns:OID 6ba7b812-9dad-11d1-80b4-00c04fd430c8
-
- ns:X500 6ba7b814-9dad-11d1-80b4-00c04fd430c8
-
The " ns:
XXX" are names of pre-defined name-space UUIDs for use in the generation of DCE 1.1 version 3 and version 5 UUIDs.
- uuid_rc_t uuid_make(uuid_t *uuid, unsigned int mode, ...);
- Generates a new UUID in uuid according to mode and optional arguments (dependent on mode).
If mode contains the UUID_MAKE_V1
bit, a DCE 1.1 variant UUID of version 1 is generated. Then optionally the bit UUID_MAKE_MC
forces the use of random multi-cast MAC address instead of the real physical MAC address (the default). The UUID is generated out of the 60-bit current system time, a 12-bit clock sequence and the 48-bit MAC address.
If mode contains the UUID_MAKE_V3
or UUID_MAKE_V5
bit, a DCE 1.1 variant UUID of version 3 or 5 is generated and two additional arguments are expected: first, a namespace UUID object ( uuid_t *
). Second, a name string of arbitrary length ( const char *
). The UUID is generated out of the 128-bit MD5 or 160-bit SHA-1 from the concatenated octet stream of namespace UUID and name string.
If mode contains the UUID_MAKE_V4
bit, a DCE 1.1 variant UUID of version 4 is generated. The UUID is generated out of 128-bit random data.
- char *uuid_error(uuid_rc_t rc);
- Returns a constant string representation corresponding to the return-code rc for use in displaying OSSP uuid errors.
- unsigned long uuid_version(void);
- Returns the hexadecimal encoded OSSP uuid version as compiled into the library object files. This allows run-time checking of the OSSP uuid version. For compile-time checking use UUID_VERSION
instead.
EXAMPLEThe following shows an example usage of the API. Error handling is omitted for code simplification and has to be re-added for production code.
/* generate a DCE 1.1 v1 UUID from system environment */ char *uuid_v1(void) { uuid_t *uuid; char *str; uuid_create(&uuid); uuid_make(uuid, UUID_MAKE_V1); str = NULL; uuid_export(uuid, UUID_FMT_STR, &str, NULL); uuid_destroy(uuid); return str; } /* generate a DCE 1.1 v3 UUID from an URL */ char *uuid_v3(const char *url) { uuid_t *uuid; uuid_t *uuid_ns; char *str; uuid_create(&uuid); uuid_create(&uuid_ns); uuid_load(uuid_ns, "ns:URL"); uuid_make(uuid, UUID_MAKE_V3, uuid_ns, url); str = NULL; uuid_export(uuid, UUID_FMT_STR, &str, NULL); uuid_destroy(uuid_ns); uuid_destroy(uuid); return str; }
HISTORYOSSP uuid was implemented in January 2004 by Ralf S. Engelschall <rse [at] engelschall.com>. It was prompted by the use of UUIDs in the OSSP as and OpenPKG projects. It is a clean room implementation intended to be strictly standards compliant and maximum portable.
SEE ALSOThe following are references to UUID documentation and specifications:
- •
- A Universally Unique IDentifier (UUID) URN Namespace, P. Leach, M. Mealling, R. Salz, IETF RFC-4122, July 2005, 32 pages,
- •
- Information Technology --- Open Systems Interconnection (OSI), Procedures for the operation of OSI Registration Authorities: Generation and Registration of Universally Unique Identifiers (UUIDs) and their Use as ASN.1 Object Identifier Components, ISO/IEC 9834-8:2004 / ITU-T Rec. X.667, 2004, December 2004, 25 pages,
- •
- DCE 1.1: Remote Procedure Call, appendix Universally Unique Identifier, Open Group Technical Standard Document Number C706, August 1997, 737 pages, (supersedes C309 DCE: Remote Procedure Call 8/1994, which was basis for ISO/IEC 11578:1996 specification),
- •
- Information technology --- Open Systems Interconnection (OSI), Remote Procedure Call (RPC), ISO/IEC 11578:1996, August 2001, 570 pages, (CHF 340,00),
- •
- HTTP Extensions for Distributed Authoring (WebDAV), section 6.4.1 Node Field Generation Without the IEEE 802 Address, IETF RFC-2518, February 1999, 94 pages,
- •
- DCE 1.1 compliant UUID functions, FreeBSD manual pages uuid(3) and uuidgen(2),
SEE ALSOuuid(1), uuid-config(1), OSSP::uuid(3). | https://www.systutorials.com/docs/linux/man/3-ossp-uuid/ | CC-MAIN-2021-31 | refinedweb | 2,390 | 53.51 |
view raw
I'm trying to get Python 3.5 to run in my terminal. I made a script using idle that printed out the version of python in use to try to solve my problem. The script looked like this:
import sys
print(sys.version_info)
sys.version_info(major=3, minor=5, micro=2, releaselevel='final', serial=0)
sys.version_info(major=2, minor=7, micro=10, releaselevel='final', serial=0)
To run idle from command line Type
idle3 in the terminal for
Python 3 idle and if you want to run
Python 2 idle, type
idle in the terminal .
Similarly, if you need to run a script or python prompt from terminal you should type
python3 when you want to use
Python 3 and
python when you want to run
Python 2. | https://codedump.io/share/W3YYN5TTmMxd/1/python-35-running-in-idle-shell-but-not-macos-terminal | CC-MAIN-2017-22 | refinedweb | 132 | 71.85 |
You can discuss this topic with others at
Read reviews and buy a Java Certification book at
O'Reilly have published a book specifically about Java I/O It get very good reviews at amazon. If you buy it from the following links I will get a small commission on the purchase
Buy from Amazon.com or from Amazon.co.uk
Write code that uses objects of the file class to navigate a file system.
In his excellent book Just Java and Beyond Peter van der Linden
starts his chapter on File I/O by saying
"It is not completely fair to remark, as some have, that support for I/O in java is "bone headed".
I think he was implying that it is not the perfect system, and so it is an area worthy of double checking your knowledge of before you go for the exam. When you are learning it you have the compensation that at least it is a useful area of the language to understand.
The java.io package is concerned with input and output. Any non trivial program will require I/O. Anything from reading a plain comma delimeted text file, a XML data file or something more exotic such as a network stream. The good news is that the Programmer Certification Exam only expects you to understand the basics of I/O, you do not have to know about Networking or the more exotic aspects of I/O.
Java I/O is based on the concept of streams. The computer term streams was first popularised with the Unix operating system and you may like to consider it as being an analogy with a stream of water. You have a stream of bits coming in at one end, you apply certain filter to process the stream. Out the other end of the pipe you send a modified version of the stream which your program can process..
The names of the I/O Stream classes are not intuitive and things do not always work as you might guess.
The File class is not entirely descriptive as an instance of the File class represents a file or directory name rather than a file itself.
My first assumption when asked about navigating a file system would be to look for a method to change directory. Unfortunately the File class does not have such a method and it seems that you simply have to create a new File object with a different directory for the constructor.
Also the exam may ask you questions about the ability to make and delete files and directories which may be considered to come under the heading of navigating the file system.
The file class offers
delete()
To delete a file or directory
mkdir() and mkdirs()
To create directories.
The File class contains the list() which returns a string array containing all of the files in a directory. This is very handy for checking to see if a file is available before attempting to open it. An example of using list.
import java.io.*; public class FileNav{ public static void main(String argv[]){ String[] filenames; File f = new File("."); filenames = f.list(); for(int i=0; i< filenames.length; i++) System.out.println(filenames[i]); } }
This simply outputs a list of the files in the current directory ("*.*")
The file class is important in writing pure java. I used to think that pure Java was just about not including native code, but it also refers to writing platform independent code. Because of the differences between in the way File systems work it is important to be aware of platform dependencies such as the directory separator character. On Win/DOS it is a backslash \, on Unix it is a forward slash / and on a Mac it is something else. You can get around this dependency by using the File.separator constant instead of hard coding in the separator literal. You can see this in use in the Filer example program that follows.
The following code is rather long (90 odd lines), but if you can make sense of this you will know most of what you need to understand the objective. The program allows you to browse the files in a directory and to change directories. It was partly inspired by some code in the Java in a Nutshell Examples book from O'reilly. A book I highly recommend. Here is a screen shot of this program in action under Linux
import java.awt.*; import java.awt.event.*; import java.io.*; public class Filer extends Frame implements ActionListener{ /************************************************************** Marcus Green October 2000 Part of the Java Programmer Certification tutorial available at. Addressing the objective to be able to use the File class to navigate the File system.This program will show a list of files in a directory .Clicking on a directory will change to the directory and show the contentsNote the use of File.separator to allow this to work on Unix or PC (and maybe even the Mac) ****************************************************************/ List lstFiles; File currentDir; String[] safiles; int iEntryType = 6; int iRootElement = 0; int iElementCount = 20; public static void main(String argv[]){ Filer f = new Filer(); f.setSize(300,400); f.setVisible(true); } Filer(){ setLayout(new FlowLayout()); lstFiles = new List(iElementCount); lstFiles.addActionListener(this); //set the current directory File dir = new File(System.getProperty("user.dir")); currentDir = dir; listDirectory(dir); add(lstFiles); addWindowListener( new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } } ); } public void actionPerformed(ActionEvent e){ int i = lstFiles.getSelectedIndex(); if(i==iRootElement){ upDir(currentDir); }else{ String sCurFile = lstFiles.getItem(i); //Find the length of the file name and then //chop of the filetype part (dir or file) int iNameLen = sCurFile.length(); sCurFile = sCurFile.substring(iEntryType,iNameLen); File fCurFile = new File(currentDir.toString()+File.separator + sCurFile); if(fCurFile.isDirectory()){ listDirectory(fCurFile); } } } public void upDir(File currentDir){ File fullPath = new File(currentDir.getAbsolutePath()); String sparent = fullPath.getAbsoluteFile().getParent(); if(sparent == null) { //At the root so put in the dir separator to indicate this lstFiles.remove(iRootElement); lstFiles.add(" "+File.separator+" ",iRootElement); return; }else{ File fparent = new File(sparent); listDirectory(fparent); } } public void listDirectory(File dir){ String sCurPath = dir.getAbsolutePath()+File.separator ; //Get the directorie entries safiles = dir.list(); //remove the previous lis and add in the entry //for moving up a directory lstFiles.removeAll(); lstFiles.addItem("[ .. ]"); String sFileName = new String(); //loop through the file names and //add them to the list control for(int i=0; i< safiles.length; i++){ File curFile = new File(sCurPath + safiles[i]); if(curFile.isDirectory()){ sFileName = "[dir ]" + safiles[i]; }else{ sFileName = "[file]"+safiles[i]; } lstFiles.addItem(sFileName); } add(lstFiles); currentDir=dir; } }
Which of the following will distinguish between a directory and a file
1) FileType()
2) isDir()
3) isDirectory()
4) getDirectory()
Which of the following methods of the File class will delete a directory or file
1) The file class does not allow you to delete a file or
directory
2) remove()
3) delete()
4) del()
How can you obtain the names of the files contained in an instance of the File class called dir?
1) dir.list()
2) dir.list
3) dir.files()
4) dir.FileNames()
Which of the following will populate an instance of the File class with the contents of the current directory?
1) File f = new File();
2) File f = new File("*.*");
3) File f = new File('*.*');
4) File f = new File(".");
Given the following code
File f = new File("myfile.txt");
What method will cause the file "myfile.txt" to be created in the underlying operating system.?
1) f.write();
2) f.close();
3) f.flush();
4) none of the above
Which of the following will chenge to the next directory above the
current directory
1) chDir("..");
2) cd(".");
3) up();
4) none of the above
Which of the following are fields or methods of the File class
1) getParent()
2) separator
3) dirname
4) getName();
3) isDirectory()
3) delete()
1) dir.list()
The list method will return a string array containing the contents of the current directory.
4) File f = new File(".");
This construction for the File class will obtain the contents of the current directory on a Dos or Unix style system but I am not sure what might happen on some other system with a more exotic file structure such as the Mac OS.
4) none of the above
The File class mainly just describes a file that might exist. To actually create it in the underlying operating system you need to pass the instance of the File class to an instance of one of the OutputStream classes.
4) none of these
Java has no direct way to change the current directory. A way around this is to create a new instance of the file class pointing to the new directory
1) getParent()
2) separator
4) getName();
You can browse the samples of the O'Reilly Java I/O book at
This topic is covered in the Sun Tutorial at
The Java API on the File class at
Sun
The JLS on Java IO a bit academic and bare
Richard Baldwin on
I/O
Joyothi has some handy tables for the I/O classes at
Last updated
24 Oct 2000
most recent version at | http://www.jchq.net/tutorial/11_01Tut.htm | crawl-001 | refinedweb | 1,531 | 63.09 |
I have a custom mxml component that I have created, and I wanted to somehow get the values of some of the textInput's that are on the main.mxml app. Is there a way to pass over the information into the custom component?
You can do this:
import mx.core.Application;
myLocalVar = Application.application.myAppVar;
Often instead of using Application.application. you can use parentDocument. or parentApplication.
See FB help sys for more details.
Very Good... I got that to work!
What about the other way around? Say for example, I want to change one of the textinput.text = XXX on my sample components from my main app, can I do that? declare an instance of the component.
Then do this:
myAppVar = myComp.myCompVar;
Wow, that was so easy I feel like an idiot.
Again... Thank you! | https://forums.adobe.com/thread/417132 | CC-MAIN-2018-30 | refinedweb | 138 | 62.14 |
Tools to query Bank of Russia
Project description
Description
Tools to query Bank of Russia
Provides methods to get the following information:
- Exchange rates on various dates
- Banks information (requisites, codes, numbers, etc.)
Requirements
- Python 3.6+
- requests Python package
- dbf_light Python package (to support legacy Bank format)
- click package (optional, for CLI)
Usage
CLI
$ pycbrf --help $ pycbrf rates $ pycbrf rates -d 2016-06-26 -c USD $ pycbrf banks $ pycbrf banks -b 045004641
CLI requires click package to be installed. Can be installed with pycbrf using:
$ pip install pycbrf[cli]
Python
from pycbrf import ExchangeRates, Banks rates = ExchangeRates('2016-06-26', locale_en=True) rates.date_requested # 2016-06-26 00:00:00 rates.date_received # 2016-06-25 00:00:00 rates.dates_match # False # Note: 26th of June was a holiday, data is taken from the 25th. # Various indexing is supported: rates['USD'].name # US Dollar rates['R01235'].name # US Dollar rates['840'].name # US Dollar rates['USD'] ''' ExchangeRate( id='R01235', name='US Dollar', code='USD', num='840', value=Decimal('65.5287'), par=Decimal('1'), rate=Decimal('65.5287')) ''' banks = Banks() bank = banks['045004641'] assert bank bank.swift # SABRRUMMNH1 bank.corr # 30101810500000000641 bank_annotated = Banks.annotate([bank])[0] for title, value in bank_annotated.items(): print(f'{title}: {value}')
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
pycbrf-1.1.0.tar.gz (14.2 kB view hashes)
Built Distributions
pycbrf-1.1.0-py3-none-any.whl (13.1 kB view hashes)
pycbrf-1.1.0-py2-none-any.whl (13.1 kB view hashes) | https://pypi.org/project/pycbrf/ | CC-MAIN-2022-27 | refinedweb | 275 | 53.58 |
bastidesamuel neuf fr wrote:I want to write littles programs in c on fedora I have done vi prog then chmod 755 prog
then i have drag and drop on "vi" some program of wiki dictionnary to
test that it work #include <stdio.h>
#include "math.h"
int main(void) { printf("%d\n",add(3,5)); }
but when I do ./prog
it return to me
./popo: line 4: syntax error near unexpected token `(' ./popo: line 4: `int main(void)'
I tried to search with google the problem it tell me that i must put "return 0 ;" at the end but .. I have the same error i dont understand .
int main(void) { printf("%d\n",add(3,5)); return 0; }
Thank you very much for help , sam ...
Try this:
$ mv prog prog.c $ make prog $ ./prog
Paul.
-- Matthew Saltzman
Clemson University Math Sciences mjs AT clemson DOT edu | https://listman.redhat.com/archives/fedora-list/2005-April/msg01357.html | CC-MAIN-2021-17 | refinedweb | 147 | 84.88 |
Red Hat Bugzilla – Bug 103385
Unhandled exception (syntax err) in anaconda after identifying existing versions
Last modified: 2007-04-18 12:57:15 EDT
From Bugzilla Helper:
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows 98) Opera 7.10 [en]
Description of problem:
Upgrading RedHat Linux 7.2 to RedHat Linux 9 from CD.
CD boots fine, identifies my monitor and video card and asks me to select mouse
manually. This then functions correctly when graphical installer launches.
I select language (English), keyboard (United Kingdom) and mouse again (serial
generic 2-button with 3-button emulation on COM1).
Then it tells me it is searching for existing versions of RedHat. The progress
bar moves fairly rapidly (5 seconds) and completes. This dialog disappears and
then the Unhandled Exception - Syntax Error is reported.
The following is copied from the attached anacdump. I believe it is the same as
the Unhandled Exception reported in the dialog box at the time.
Traceback (most recent call last):
File "/usr/lib/anaconda/gui.py", line 764, in nextClicked
self.setScreen ()
File "/usr/lib/anaconda/gui.py", line 960, in setScreen
exec s
File "<string>", line 1, in ?
File "/usr/lib/anaconda/iw/examine_gui.py", line 17, in ?
from package_gui import *
File "/usr/lib/anaconda/iw/package_gui.py", line 1068
i column = gtk.TreeViewColumn('Text', renderer, text = 1)
^
SyntaxError: invalid syntax
Version-Release number of selected component (if applicable):
How reproducible:
Always
Steps to Reproduce:
See description above.
I have tried using computer as-is and also switching the CMOS to fail-safe
settings. I recall that this enabled me to install version 7.2 successfully.
However, I get the same error with or without fail-safe settings.
Additional info:
Created attachment 94072 [details]
Anaconda core dump, as saved to floppy when the error occurred.
I would recommend testing your media if you have not already. This appears to be
due to an error loading the python sources from the install media.
Closing due to inactivity. Please reopen if you have any further information to
add to this bug report | https://bugzilla.redhat.com/show_bug.cgi?id=103385 | CC-MAIN-2017-09 | refinedweb | 346 | 52.26 |
.
Two month ago while the Store module was in the release tracker, Brandon Haynes from the Core Team conducted a security review. Brandon is well aware about security risks, PCI compliancy and CWE rules. His helpful advices have revealed some possible security holes. Thanks again Brandon for your hard work!
One of his advices was about cookie encryption. Currently only order ID and cart ID are stored in a session cookie. This is not a real security breach, but this violates some CWE rules. An attacker can forge a cookie and try to access to the cart content of someone else. The cart ID is a GUID generated by the .Net framework when a visitor adds the first product to his cart. Even if it’s difficult to discover a valid cart ID, it’s more secure to encrypt it. Concerning the order number, no one (except Admin) can access orders from someone else; but expose this value could be a limitation if a PCI security audit is conducted.
First I looked at the PortalSecurity class from the DotNetNuke.Security namespace; two methods allow you to manage encryption, Encrypt(string strKey, string strData) and Decrypt(string strKey, string strData). The main drawback of those methods is the encryption algorithm used. Many applications, including DotNetNuke, uses the DES algorithm to encrypt sensitive data while it is well known that this algorithm can be easily broken. This is not really a problem for most web sites, but again it could be a limitation in case of PCI security audit.
The .Net framework provides several classes to manage encryption needs. They are of three kinds: Hash, Symmetric and Asymmetric. The Store encryption helper class covers only symmetric algorithms. Given that the store module requires strong encryption, I write a class to facilitate the use of these algorithms. Use an encryption algorithm is never really easy and requires a general understanding of their functioning. Because the misuse of such an algorithm may expose you to security holes while you expect to be protected by encryption.
In the next part we will see how works symmetric algorithms and what are requirements to use them. If you can’t wait, download the class from the SVN repository at Codeplex. The SymmetricHelper class is full of comments, read them!
Gilles | https://www.dnnsoftware.com/community-blog/cid/136631/new-store-encryption-helper-class--part-1 | CC-MAIN-2020-40 | refinedweb | 383 | 56.76 |
In my app i need to save changed values (old and new) when model gets saved. Any examples or working code?
I need this for premoderation of content. For example, if user changes something in model, then administrator can see all changes in separate table and then decide to apply them or not.
You haven't said very much about your specific use case or needs. In particular, it would be helpful to know what you need to do with the change information (how long do you need to store it?). If you only need to store it for transient purposes, @S.Lott's session solution may be best. If you want a full audit trail of all changes to your objects stored in the DB, try this AuditTrail solution.
UPDATE: The AuditTrail code I linked to above is the closest I've seen to a full solution that would work for your case, though it has some limitations (doesn't work at all for ManyToMany fields). It will store all previous versions of your objects in the DB, so the admin could roll back to any previous version. You'd have to work with it a bit if you want the change to not take effect until approved.
You could also build a custom solution based on something like @Armin Ronacher's DiffingMixin. You'd store the diff dictionary (maybe pickled?) in a table for the admin to review later and apply if desired (you'd need to write the code to take the diff dictionary and apply it to an instance).
I've found Armin's idea very useful. Here is my variation;
class DirtyFieldsMixin(object): def __init__(self, *args, **kwargs): super(DirtyFieldsMixin, self).__init__(*args, **kwargs) self._original_state = self._as_dict() def _as_dict(self): return dict([(f.name, getattr(self, f.name)) for f in self._meta.local_fields if not f.rel]) def get_dirty_fields(self): new_state = self._as_dict() return dict([(key, value) for key, value in self._original_state.iteritems() if value != new_state[key]])
Edit: I've tested this BTW.
Sorry about the long lines. The difference is (aside from the names) it only caches local non-relation fields. In other words it doesn't cache a parent model's fields if present.
And there's one more thing; you need to reset
_original_state dict after saving. But I didn't want to overwrite
save() method since most of the times we discard model instances after saving.
def save(self, *args, **kwargs): super(Klass, self).save(*args, **kwargs) self._original_state = self._as_dict() | https://pythonpedia.com/en/knowledge-base/110803/dirty-fields-in-django | CC-MAIN-2020-45 | refinedweb | 423 | 68.26 |
How to bring time series data in following format for sequence to sequence prediction
1 answer
- answered 2018-11-08 06:23 jezrael
Use
shiftin loop with
f-strings:
#python 3.6+ for i in range(1,5): df[f'demand_{i}'] = df['demand'].shift(-i) #python bellow 3.6 for i in range(1,5): df['demand_{}'.format(i)] = df['demand'].shift(-i)
Sample:
df = pd.DataFrame({ 'demand':[4,7,8,3,5,0], }) for i in range(1,5): df['demand_{}'.format(i)] = df['demand'].shift(-i) print(df) demand demand_1 demand_2 demand_3 demand_4 0 4 7.0 8.0 3.0 5.0 1 7 8.0 3.0 5.0 0.0 2 8 3.0 5.0 0.0 NaN 3 3 5.0 0.0 NaN NaN 4 5 0.0 NaN NaN NaN 5 0 NaN NaN NaN NaN
See also questions close to this topic
- Python code percentage number compare problem
when i compared tow percentage number it gives me wrong answer
a="{0:%}".format(85/100) b="{0:%}".format(9/100) if b>a : print("done")
it should be pass if condition while its give me done in answer
- How to create sum of different kernel objects in TensorFlow Probability?
I have one question about specifying kernel function in
Tensorflow-probability.
Usually, if I want to create a kernel object, I will write
import tensorflow as tf import tensorflow_probability as tfp tfp_kernels = tfp.positive_semidefinite_kernels kernel_obj = tfp_kernels.ExponentiateQuadratic(*args, **karwgs)
I know that kernel object support batch broadcasting. But what if I want to build a kernel object that is the sum of several different kernel objects, like additive Gaussian processes?
I am not sure how to "sum" up the kernel object in Tensorflow. What I am able to do is to create several separate kernel objects
K1, ... KJIt seems that there is no similar question online.
Thanks for the help in advance.
- Counting words per sentence and sentences per paragraph in a text file
I'm having trouble obtaining normalising a dictionary. In my dictionary, I have a bunch of words we are meant to count in a text file. Now for each of these words/characters, "normalising", in the context of my project, is dividing their frequency/value by the total number of sentences in the given text. I then have to replace the old values of the dictionary with these new ones.
I.e. name of my dictionary is count, with keys and values like this:
{'and': 5, ';' : 3, '-' : 0...}
def main(textfile, normalize == True): . . . . if normalize == True: for x in count: new_count[x] = count[x]/numSentence print(x,count[x])
Here's a sample file to try any codes on: Also note in the above code the normalise == True is there because in the top-level function
- How can I write dataset information into a text file?
I want to write dataset information into a text file, but result is none.
Result:
----Dataset information----- None
Code:
text_file = open("output_file.txt","w") dataset = pd.read_csv("labelled_text.txt", delimiter="\t") text_file.write("----Dataset information-----\n") text_file.write("%s\n"%(dataset.info()))
How can i write this informaiton into a file.
Print function is okey, but writing into a text is not okey.
- pandas reversal of numbers based on condition
I have a data frame that looks something like this:
import pandas as pd d={'name':['edward','margaret'],'sex':['male','female'],'amt':[100,200]} df=pd.DataFrame(data=d)
I want to reverse the amt column if the sex is 'female'. So I need the amt to be -200 for the second record. Something like:
df.loc[df['sex']=='female','amt']=-200
- How to get pandas to act like MS Excel with cell arithmetic?
Objective: Have a function placed at a given position within a Pandas dataframe that updates with adjustments in the dataframe
Description: I am trying to subtract 75,000 from 400,000 to result in 325,000 and have it be displayed in a Pandas datframe. Currently, the row 'End Cash' provides me all the answers that I am expecting. However, these are hard coded values and not dynamic.
import pandas as pd data_2 = [['Init Cash', 400000, 325000,335000,355000,275000,225000,240000], ['Matur CDs',0,0,0,0,0,0,0], ['Interest',0,0,0,0,0,0,0], ['1-mo CDs',0,0,0,0,0,0,0], ['3-mo CDs',0,0,0,0,0,0,0], ['6-mo CDs',0,0,0,0,0,0,0], ['Cash Uses',75000,-10000,-20000,80000,50000,-15000,60000], ['End Cash', 325000,335000,355000,275000,225000,240000,180000]] df_2 = pd.DataFrame(data_2,columns=['Month', 'Month 1', 'Month 2', 'Month 3', 'Month 4', 'Month 5', 'Month 6', 'End']) df_2_copy = df_2.copy()
I thought I could get away with something like the following:
df_2_copy.iloc[7]['Month 1'] == (df_2_copy.iloc[0]['Month 1'] - df_2_copy.iloc[6]['Month 1'])
But, unfortunately, this does not work for me.
Any help would be appreciated.
- ordinary least squares coefficients calculation using np.einsum
Is there a way to calculate ordinary least squares coefficients
βin one
np.einsumcall given a vector of dependent variable
Yand a matrix of predictors
X?
- System of coupled ODE - heat exchanger problem
I'm solving a heat exchanger problem and have to find the final temperature. It's a system of ode's I've written the following code: It asks for me to define T and t, but I they're functions of x that I should find
import numpy as np import matplotlib.pyplot as plt from scipy.integrate import odeint #propriedades trietileno glicol na entrada T1 = 363 #K temperatura de entrada Wt = 3.6 #kg/s vazão #propriedades água na entrada t1 = 298 #K Ww = 1.0 Ww = [0.1, 0.5, 1] #kg/s vazões Di = 0.07792 #m diâmetro interno L = 3.048 #m comprimento do tubo U = 283.72 #W/m²K pi= 3.1415 cpt = 1901.09#, 2.7683*T + 896.2] #J/kg*K calor específico cpw = 4018.04#, -0.00003*(t^3) + 0.0403*(t^2) - 16.277*t + 6083.7] #J/kg*K calor específico cp = [cpt, cpw] def funct(y, x): y = T, t dTdx = (U * Di * pi / (Wt * cpt)) * (T - t) dtdx = (U * Di * pi / (Ww * cpw)) * (T - t) x = np.linspace(0, L, 100) return dTdx, dtdx # Vetor espaço # Initial condition y0 = T1, t1 sol = odeint(funct, y0 , x) # plot plt.plot(x, sol[:, 0], label='Trietilenoglicol') plt.plot(x, sol[:, 1], label='Água') plt.legend() plt.xlabel('posição')
but it gives me the following error message :
NameError Traceback (most recent call last) <ipython-input-47-2f2a81626e49> in <module> 35 # Initial condition 36 y0 = T1, t1 ---> 37 sol = odeint(funct, y0 , x) 38 39 # plot c:\users\idril\appdata\local\programs\python\python36\lib\site-packages\scipy\integrate\odepack.py in odeint(func, y0, t, args, Dfun, col_deriv, full_output, ml, mu, rtol, atol, tcrit, h0, hmax, hmin, ixpr, mxstep, mxhnil, mxordn, mxords, printmessg, tfirst) 242 full_output, rtol, atol, tcrit, h0, hmax, hmin, 243 ixpr, mxstep, mxhnil, mxordn, mxords, --> 244 int(bool(tfirst))) 245 if output[-1] < 0: 246 warning_msg = _msgs[output[-1]] + " Run with full_output = 1 to get quantitative information." <ipython-input-47-2f2a81626e49> in funct(y, x) 23 24 def funct(y, x): ---> 25 y = T, t 26 dTdx = (U * Di * pi / (Wt * cpt)) * (T - t) 27 dtdx = (U * Di * pi / (Ww * cpw)) * (T - t) NameError: name 'T' is not defined
I've already read many answered questions but still can't find the mistake.
- Is there a way to easily integrate a set of differential equations over a full grid of points?
The problem is that I would like to be able to integrate the differential equations starting for each point of the grid at once instead of having to loop over the
scipyintegrator for each coordinate. (I'm sure there's an easy way)
As background for the code I'm trying to solve the trajectories of a Couette flux alternating the direction of the velocity each certain period, that is a well known dynamical system that produces chaos. I don't think the rest of the code really matters as the part of the integration with
scipyand my usage of the
meshgridfunction of
numpy.
import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation, writers from scipy.integrate import solve_ivp start_T = 100 L = 1 V = 1 total_run_time = 10*3 grid_points = 10 T_list = np.arange(start_T, 1, -1) x = np.linspace(0, L, grid_points) y = np.linspace(0, L, grid_points) X, Y = np.meshgrid(x, y) condition = True totals = np.zeros((start_T, total_run_time, 2)) alphas = np.zeros(start_T) i = 0 for T in T_list: alphas[i] = L / (V * T) solution = np.array([X, Y]) for steps in range(int(total_run_time/T)): t = steps*T if condition: def eq(t, x): return V * np.sin(2 * np.pi * x[1] / L), 0.0 condition = False else: def eq(t, x): return 0.0, V * np.sin(2 * np.pi * x[1] / L) condition = True time_steps = np.arange(t, t + T) xt = solve_ivp(eq, time_steps, solution) solution = np.array([xt.y[0], xt.y[1]]) totals[i][t: t + T][0] = solution[0] totals[i][t: t + T][1] = solution[1] i += 1 np.save('alphas.npy', alphas) np.save('totals.npy', totals)
The error given is :
ValueError: y0 must be 1-dimensional.
And it comes from the 'solve_ivp' function of
scipybecause it doesn't accept the format of the
numpyfunction
meshgrid. I know I could run some loops and get over it but I'm assuming there must be a 'good' way to do it using
numpyand
scipy. I accept advice for the rest of the code too. | http://quabr.com/53202439/how-to-bring-time-series-data-in-following-format-for-sequence-to-sequence-predi | CC-MAIN-2019-22 | refinedweb | 1,626 | 66.64 |
!
Hi David,
You're SplitButton is absolutly awsome. I 'm using it on different project and the only problem i 've encountering, was about Zoom.
Now, all is perfect ! Thanks a lot !
Samuel,
Thanks for the kind words! 🙂
Hi David,
your Control is beautiful but it's not responding to command properly (WPF version). Menu items appear always grayed out.
is this a bug?
thanks
Fabio
Fabio,
I just tried this and found a problem that may be what you're seeing as well. The ContextMenu (on WPF; I haven't tried on Silverlight) isn't inheriting the DataContext from the SplitButton parent, so the Command Bindings on the MenuItem don't map to anything and aren't hooked up right. I'd expect this to leave the MenuItems in the default IsEnabled=true state, but maybe you're changing that?
At any rate, adding the following to the list of properties for the ContextMenu element inside the SplitButton/MenuButton Template in Generic.xaml fixed the problem I was seeing:
DataContext="{TemplateBinding DataContext}"
This is probably a good change to make anyway, but I'm not certain it will fix the problem you're seeing. If you wouldn't mind trying this out and letting me know, I'd appreciate it. Thanks!
Hi David,
thanks for your fast reply.
i've tryed oot your suggestion but nothing changed. here the fragments:
my xaml:
<localcontrols:MenuButton x:
<localcontrols:MenuButton.ButtonMenuItemsSource>
<MenuItem Header="Term only" Command="localclasses:MyCommands.DropTerm" />
<MenuItem Header="Term and narrowers" Command="localclasses:MyCommands.DropTermTree" />
</localcontrols:MenuButton.ButtonMenuItemsSource>
</localcontrols:MenuButton>
generic.xaml:
<ContextMenuService.ContextMenu>
<ContextMenu ItemsSource="{Binding ButtonMenuItemsSource, RelativeSource={RelativeSource TemplatedParent}}" Foreground="{TemplateBinding Foreground}" FlowDirection="{TemplateBinding FlowDirection}" DataContext="{TemplateBinding DataContext}" />
</ContextMenuService.ContextMenu>
thanks again
Fabio,
Two things to check:
1. When you made that change to generic.xaml, did you do it for *both* SplitButton and MenuButton?
2. Try removing the Command binding on MenuButton itself – I'm not sure what effect it would have, and it doesn't fit with my idea of how MenuButton should behave (always show the menu).
If neither of those helps, could you please create a small, self-contained sample and send it to me via the "Email Blog Author" link? The answer may depend on something specific about your scenario that isn't true for my simple test case.
Thanks!
hi David, neither of your suggestions worked for me. i've packed up a very simple project that look like the more complex one. i've posted it to skydrive.
here's the link:
cid-3c018077b51a3ea8.office.live.com/…/MenuButtonSample.zip
thanks in advance
Fabio
Fabio,
Thank you – I'll try to have a look at your sample in the next couple of days and let you know what I find.
Fabio,
I've looked at this a bit just now and I can tell you WHY it's not working – though I don't yet know how to fix it. 😐 What you're seeing is similar to the DataContext issue I identified above – but things are different for your scenario because you're using RoutedCommands instead of Bindings to ICommand implementations. What seems to be the case in your example is that the ContextMenu for the SplitButton doesn't have the main Window instance as a logical ancestor – so the RoutedCommands you've hooked up to your MenuItems don't bubble all the way up to the handlers you've attached to the main Window instance. I find that if I call AddLogicalChild from the SplitButton's handler for ContextMenu.Opened to set the Popup parent of the ContextMenu as a logical child of the SplitButton instance, the CanExecute handlers you've defined suddenly start getting called like we want! However, once I've made that change, the ContextMenu suddencly starts dismissing itself immediately after opening… So this is progress, but not quite all the way to a working solution. I'll keep looking into this, but wanted to give you an update now that I knew something more. Thanks for your patience!
David, thank you so much!
Fabio
Fabio,
I think I have fixed the problem. 🙂 Could you please contact me via and I'll reply with the new code so you can try it out yourself? If you confirm the fix, I'll blog it in the next couple of days and credit you for the bug report.
Thanks for your help!
Hi,
I read through the last few posts. Wondering if you have posted up any new code that will work with MVVM? I tried with:
<common:IconButton
<common:SplitButton.ButtonMenuItemsSource>
<toolkit:MenuItem
<toolkit:MenuItem
<toolkit:MenuItem
</common:SplitButton.ButtonMenuItemsSource>
</common:IconButton>
But it is not responding to my commands similar to the above…
Thanks!
tmcconechy,
MVVM scenarios should already work. I'm guessing your Bindings aren't pointing where you want – please have a look at the Output window when running your application to see if there are any diagnostic messages about Bindings not hooking up right.
Here's what I did to verify this on the latest SplitButton.zip with Silverlight 4, by the way:
public class MyCommand : ICommand
{
public bool CanExecute(object parameter)
{
return true;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
MessageBox.Show("Executed");
}
}
public MainPage()
{
InitializeComponent();
DataContext = new MyCommand();
}
<splitButton:SplitButton
<splitButton:SplitButton.ButtonMenuItemsSource>
<toolkit:MenuItem
<toolkit:MenuItem
</splitButton:SplitButton.ButtonMenuItemsSource>
</splitButton:SplitButton>
It worked as expected when I ran the modified sample. Hope this helps!
Great split button and thanks for the posts. Any thoughts on supporting toolkit themes?
Joey,
Thanks! I'm probably not going to do additional themes myself, but if someone did, I'd be happy to link to their work. 🙂
David,
I'm glad I found this control, very simple & easy to understand! I want to expand upon tmcconechy's question & your answer regarding Commands. I'm quite new to Silverlight but understand MVVM is a pattern worth learning, but I'm having difficulty understanding how you can determine which item was actually selected by the user? Everything funnels into MyCommand::Execute and I'm not seeing any way to differentiate what triggered the event. Thanks for any ideas / advice on what I might be missing.
John Langley,
Thanks for the compliments!
When commanding, it's common to use a dedicated command implementation for each "function". For example, there might be a command for Printing and it will be hooked up to the File/Print option and a Toolbar button and the Ctrl+P accelerator – and because they're all supposed to print, it doesn't care which one triggered it – it just prints. 🙂 Where things get a little different is when you have a command in a ListBox for something like "remove" and all the items look the same. In this case, I might use the CommandParameter property to pass in some item-specific information that the command implementation can then use to determine which specific item needs to be dealt with.
Hope this helps!
Great SplitButton, the easiest I have seen so far.
But I have a question regarding the MenuItem-part: I don't know my MenuItems in designtime so I cannot write them manual in xaml.
So I thought about binding a ObservableCollection of MenuItems (including ICommands and all that stuff) from my ViewModel, because I hold all the Information in a Collection anyway. But how to do bind to the Button? ButtonMenuItemsSource is not suited for binding.
I would be glad if you could help me with this! 🙂
I have constant battles with all kind of SplitButtons for a while now and it seems that ContextMenus try to wear me down. 😉
Oh, sorry, I was so stupid 🙂 Of course I just had to change ButtonMenuItemsSource into a DependencyProperty and everything is fine!
Thank you for such a nice and easy-to-use control! 🙂
Amaryllion,
I'm glad you got that sorted out – I'm sorry for the trouble! In case it helps you feel better, making that very change is on my TODO list for a future release of SplitButton. 🙂
PS – Thanks for the kind words!
Hi David,
Thank you for this control.
I want to report a bug:
The SplitButton control paced in a ChildWindow – SL4 – strange behaviour: the drop down section is out of place.
Any idea ?
Thank you
Hi – more info about:
"The SplitButton control paced in a ChildWindow – SL4 – strange behaviour: the drop down section is out of place.".
The problem appear only if Zoom Level (applied by IE) != 100 and SplitButton control paced in a ChildWindow;
rlodina,
I think I've heard of other issues with controls inside a ChildWindow at non-100% browser zoom levels. I haven't looked into this specifically, but my guess would be that something about ChildWindow affects how otherwise correctly-functioning controls operate (possibly the Popup or the centering mechanism?). If someone can identify why that is, it might help here…
this is a great set of extensions. Could you point me in the right direction to find what I need to update in the templates to have the control toolkit's styles picked up in these controls?
Kyle,
Thanks! 🙂 Unfortunately, the templating story for XAML doesn't make this task as easy as it could be. Basically, each theme's template contains a complete definition of the control's UI, so if you want to create a SplitButton using the "Whistler Blue" theme (or whatever), you'll need to start from the Button template for that theme. Fortunately, those templates are available via Blend's Edit Template feature or in source form as part of the Silverlight Toolkit download. The steps to customize a Button template for for SplitButton are quite simple – I outlined them in the original post: blogs.msdn.com/…/developer-test-case-customer-win-using-contextmenu-to-implement-splitbutton-and-menubutton-for-silverlight-or-wpf.aspx
Hope this helps!
I found that the contextmenu offset was still wrong when the split button was on a childwindow. I added the following scaling which seems to have fixed it:
_contextMenu.HorizontalOffset = ( desiredOffset.X – currentOffset.X ) * Application.Current.Host.Content.ZoomFactor;
_contextMenu.VerticalOffset = ( desiredOffset.Y – currentOffset.Y ) * Application.Current.Host.Content.ZoomFactor;
Mark,
That's great, thank you for sharing! 🙂
Hi David,
tried your sample in SL5 and the context menu position is not displayed under the button anymore.
Do you have a sample working for SL5?
Thanks.
Migus,
Sorry, I don't have a Silverlight 5 version handy. 🙁 If you find out what's broken with that platform and are able to follow-up here, that would be much appreciated!
Hey David,
I am using the SplitButton in a WPF .NET 4.0 application (it is the child of a stackpanel in a window). For some reason, the context menu (without any interaction) initially pops up in the top right corner of my primary monitor when the window is instantiated. It disappears after a couple seconds then all is well. Any idea why this occurs?
-Thanks. Great blog by the way! I am also utilizing your VirtualFile stuff for Drag and Dropping to windows 🙂
Chevon,
I'm not sure why that should happen… You might try setting a couple of breakpoints to see if the code to show the ContextMenu is getting triggered somehow. I don't recall that being a problem with the sample application, so maybe it has something to do with how your app is structured?
PS – Thanks for the kind words! 🙂 | https://blogs.msdn.microsoft.com/delay/2010/06/11/splitbuttoning-hairs-two-fixes-for-my-silverlight-splitbuttonmenubutton-implementation-and-true-wpf-support/ | CC-MAIN-2016-36 | refinedweb | 1,907 | 55.84 |
Simple linked list C++
When I typical write a linked list class to store int values I would setup the class something like this....
struct Node {
int _item;
Node *_next;
};
Node *_head;
However, I know have to write a program that will use IntNode.h to create a linked list implementation.
The way the designer setup this .h file is confusing me and have been unable to create the implementation cpp file.
Can someone review my IntNode.cpp and guide me on how to code the correct implementation ? No major changes can be made to the .h file.
The tester for the class would be a very simple program:
#include <iostream>
#include <string>
#include "IntNode.h"
int main()
Node NL;
NL = Node(1);
//add values
NL.info(8);
NL.info(7);
NL.info(6);
...
//display values
...
return(0);
}
Solution Preview
The basic trick here is to use one more class. There are many different ways of doing this.
1. You can define a class List and a private class Node inside the class List.
2. You can define the two classes and declare that one ...
Solution Summary
Simple linked list C++ is devised. | https://brainmass.com/computer-science/cpp/simple-linked-list-c-119906 | CC-MAIN-2017-17 | refinedweb | 193 | 76.11 |
There are many reasons you might find yourself needing to create an image gallery – whether it’s to show off album covers for a music app, to present feature images for articles in a feed, or to showcase your work in a portfolio. To make the right impression though, these apps should allow users to effortlessly swipe through multiple images without slowdown and that’s where things get a little tricky.
This tutorial will show you how to create a seamless gallery filled with nice big images and then adapt that for a number of different applications. Along the way, we’ll see how to use RecyclerViews, adapters and Picasso – so hopefully it will make for a great learning exercise, whatever you end up doing with it! Full code and project included below…
Introducing RecyclerView
To create our Android gallery, we’re going to use something called a RecyclerView. This is a handy view that acts very much like a ListView but with the advantage of allowing us to scroll quickly through large data sets. It does this by only loading the images that are currently in view at any given time. This means we can load more images without the app becoming very slow. There’s a lot more that you can do with this view and it’s used all over Google’s own apps, so check out the full explanation to using RecyclerView to find out more.
The good news is that this is all we really need to create our gallery – a RecyclerView filled with images. The bad news is that the RecyclerView is a little more complicated than most other views. Because of course it is.
RecyclerView is not, for starters, available to drag and drop using the design view. So we’ll just have to add it to the activity_main.xml, like so:
<android.support.v7.widget.RecyclerView android:
Notice that we’re referencing the Android Support Library. This means we also need to modify our build.gradle in order to include the dependency. Just add this line to the app level file:
compile 'com.android.support:recyclerview-v7:24.2.1'
And if that’s not installed, then you’re going to have to open the SDK manager and install it. Fortunately, Android Studio is pretty smart about prompting you to do all this. I just got a new computer, so I can play along with you!
Head back to the XML and it should now be working just fine. Except the list is not populated except with ‘item 1, item 2, item 3’. What we need to do, is load our images into here.
Creating your list of images
As mentioned, populating our recycler view is a little more complicated than using a regular list. By which, I mean it’s way more complicated… but it’s a great chance for us to learn some handy new skills. So there’s that.
For a RecyclerView, we’re also going to need a layout manager and an adapter. This is what’s going to allow us to organize the information in our view and add the images. We’ll start by initializing our views and attaching an adapter in the onCreate of MainActivity.java. This looks like so:
setContentView(R.layout.activity_main); RecyclerView recyclerView = (RecyclerView)findViewById(R.id.imagegallery); recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2); recyclerView.setLayoutManager(layoutManager); ArrayList<CreateList> createLists = prepareData(); MyAdapter adapter = new MyAdapter(getApplicationContext(), createLists); recyclerView.setAdapter(adapter);
We’re setting the layout as activity_main, then we’re finding the RecyclerView and initializing it. Notice that we use HasFixedSize to make sure that it won’t stretch to accommodate the content. We’re also creating the layout manager and the adapter here. There are multiple types of layout manager but true to gallery-form, we’re going to pick a grid rather than a long list. Remember to import the GridLayoutManager and the RecyclerView as Android Studio prompts you to do so. Meanwhile, when you highlight MyAdapter, you’ll be given the option to ‘Create Class MyAdapter’. Go for it – make your own MyAdapter.Java and then switch back. We’ll come back to this later.
Before we can use the new adapter class, we first need to create our data set. This is going to take the form of an array list. So in other words, we’re going to place a list of all our images in here, which the adapter will then read and use to fill out the RecyclerView.
Just to make life a little more complicated, creating the Array List is also going to require a new class. First though, create a string array and an integer array in the same MainActivity.Java:
private final String image_titles[] = { "Img1", "Img2", "Img3", "Img4", "Img5", "Img6", "Img7", "Img8", "Img9", "Img10", "Img11", "Img12", "Img13", }; private final Integer image_ids[] = { R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4, R.drawable.img5, R.drawable.img6, R.drawable.img7, R.drawable.img8, R.drawable.img9, R.drawable.img10, R.drawable.img11, R.drawable.img12, R.drawable.img13, };
The strings can be anything you want – these will be the titles of your images. As for the integers, these are image IDs. This means they need to point to images in your Drawables folder. Drop some images into there that aren’t too massive and make sure the names are all correct.
Remember: a list is a collection of variables (like strings or integers), whereas an array is more like a filing cabinet of variables. By creating an ArrayList then, we’re basically creating a list of filing cabinets, allowing us to store two collections of data in one place. In this case, the data is a selection of image titles and image IDs.
Now create a new Java Class called CreateList and add this code:
public class CreateList { private String image_title; private Integer image_id; public String getImage_title() { return image_title; } public void setImage_title(String android_version_name) { this.image_title = android_version_name; } public Integer getImage_ID() { return image_id; } public void setImage_ID(Integer android_image_url) { this.image_id = android_image_url; } }
What we have here is a method we can use to add new elements (setImage_title, setImage_ID) and retrieve them (getImage_title, getImage_ID). This will let us run through the two arrays we made and stick them into the ArrayList. You’ll need to import array lists.
We do this, like so:
private ArrayList<CreateList> prepareData(){ ArrayList<CreateList> theimage = new ArrayList<>(); for(int i = 0; i< image_titles.length; i++){ CreateList createList = new CreateList(); createList.setImage_title(image_titles[i]); createList.setImage_ID(image_ids[i]); theimage.add(createList); } return theimage; } }
So we’re performing a loop while we go through all the image titles and adding them to the correct array in the ArrayList one at a time. Each time, we’re using the same index (i), in order to add the image ID to its respective location.
Confused yet?
Using the adapter
Before you head over to MyAdapter.java, you first need to create a new XML layout in the layout directory. I’ve called mine cell_layout.xml and it looks like so:
<LinearLayout xmlns: <ImageView android: <TextView android: </LinearLayout>
All this is, is the layout for the individual cells in our grid layout. Each one will have an image at the top, with text just underneath. Nice.
Now you can go back to your MyAdapter.java. This is where we’re going to take the list, take the cell layout and then use both those things to fill the RecyclerView. We already attached this to the RecyclerView in MainActivity.Java, so now all that’s left is… lots and lots of complex code.
It’s probably easiest if I just show you…
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> { private ArrayList<CreateList> galleryList; private Context context; public MyAdapter(Context context, ArrayList<CreateList> galleryList) { this.galleryList = galleryList; this.context = context; } @Override public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false); return new ViewHolder(view); } @Override public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) { viewHolder.title.setText(galleryList.get(i).getImage_title()); viewHolder.img.setScaleType(ImageView.ScaleType.CENTER_CROP); viewHolder.img.setImageResource((galleryList.get(i).getImage_ID())); } @Override public int getItemCount() { return galleryList.size(); } public class ViewHolder extends RecyclerView.ViewHolder{ private TextView title; private ImageView img; public ViewHolder(View view) { super(view); title = (TextView)view.findViewById(R.id.title); img = (ImageView) view.findViewById(R.id.img); } } }
So what we’re doing here is to get our ArrayList and then create a ViewHolder. A ViewHolder makes it easier for us to iterate lots of views without having to write findViewByID every time – which would be impractical for a very long list.
We create the VewHolder by referencing the cell_layout file we created earlier, and then bind it with the data from our ArrayList. We find the TextView first and set that to be the relevant string, then we find the ImageView and use the image ID integer to set the image resource. Notice that I’ve also setScaleType to CENTER_CROP. This means that the image will be centered but cropped to fill the enter cell in a relatively attractive manner. There are other scale types but I believe that this is by far the most attractive for our purposes.
Don’t forget to import the ImageView and TextView classes. And remember you need to add some images to your drawables folder. Once you’ve done that though you should be ready to go!
Give it a try and you should end up with something that looks a little like this:
Except without all the pictures of me… This is just what I happened to have to hand, don’t judge!
Not working as expected? Don’t worry – this is a pretty complicated app for beginners. You can find the full thing over at GitHub here and then just work through each step while referring to the code.
Making this into a useful app
So right now we have a strange slideshow of photos of me. Not really a great app…
So what might you use this code for? Well, there are plenty of apps that essentially boil down to galleries – this would be a great way to create a portfolio for your business for example, or perhaps a visual guide of some sort.
In that case, we might want to add an onClick so that we can show some information, or perhaps a larger version of the image when someone taps their chosen item. To do this, we just need to import the onClickListener and then add this code to onBindViewHolder:
viewHolder.img.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context,"Image",Toast.LENGTH_SHORT).show(); } });
If we wanted to load a selection of photos on the user’s device meanwhile, we’d simply have to list files in a particular directory. To do that, we’d just need to use listFiles to take the file names and load them into our ListArray list, using something list this:
String path = Environment.getRootDirectory().toString(); File f = new File(path); File file[] = f.listFiles(); for (int i=0; i < file.length; i++) { CreateList createList = new CreateList(); createList.setImage_Location(file[i].getName()); }
Except you’ll be changing your path string to something useful, like the user’s camera roll (rather than the root directory). Then you can load the bitmaps from the images on an SD card or internal storage by using the image name and path, like so:
Bitmap bmp = BitmapFactory.decodeFile(pathName); ImageView img; img.setImageBitmap(bmp);
You’ll probably want to get thumbnails from them too. This way, the list will be populated dynamically – so that when new photos are added to that directory, you’re gallery will update to show them each time you open it. This is how you might make a gallery app for displaying the images on a user’s phone, for example.
Or alternatively, another way we could make this app a little fancier, would be to download images from the web.
This might sound like a whole extra chapter but it’s actually pretty simple as well. You just need to use the Picasso library, which is very easy and completely free. First, add the dependency like we did earlier:
compile 'com.squareup.picasso:picasso:2.5.0'
Then, change your ArrayList to contain two string arrays instead of a string and an integer. Instead of image IDs, you’re going to fill this second string array with URLs for your images (in inverted commas). Now you just swap out the line in your onBindViewHolder to:
Picasso.with(context).load(galleryList.get(i).getImage_ID()).resize(240, 120).into(viewHolder.img);
Remember to add the relevant permission and it really is that easy – you can now download your images right from a list of URLs and that way update them on the fly without having to update the app! Picasso will also cache images to keep things nice and zippy for you.
Note as well that if you wanted to have more than two images per row, you would simply swap:
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
For:
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),3);
This will give you something like the following:
If you don’t like the text and you just want images, then you can easily remove the string array from proceedings. Or for a quick hack if you don’t want to stray too far from my code, you can just make the TextView super thin.
Closing comments
And there you have it – your very own basic image gallery. There are plenty of uses for this and hopefully you’ve learned a few useful bits and pieces along the way. Stay tuned for more tutorials just like this one!
And remember, the full project can be found here for your reference. | https://www.androidauthority.com/how-to-build-an-image-gallery-app-718976/ | CC-MAIN-2019-04 | refinedweb | 2,310 | 64.2 |
Hello
I have bean
@Name("example")
@Scope(ScopeType.APPLICATION)
public class CustomerWrapper {
public String value = "password";
}
when I using #{example.value} in my page I got following error
Property 'value' not found
I always have to add getter and setters to my classes.
Best regards
Yes, in Java according to JavaBean Spec you must have getter-setter pairs, however most IDE's can generate these for you, e.g. Eclipse ctrl-1 on field - generate getters, setters... also right-click in Java editor of your source file -Source-generate getters, setters...
Or if you like more easy scripting style you can try groovy beans :)
Hi Mirek,
if you're using seam bijection (@In or @Out) you can omit the getter and setter methods, else you've to write them. In your case
public String value getter and setter must be added.
//Kevin | https://developer.jboss.org/thread/192460 | CC-MAIN-2018-39 | refinedweb | 142 | 63.39 |
> Remy Maucherat wrote:
>
> >.
I'll fix that this evening (unless you fix it before, of course).
>.
All right, that makes sense.
> > [snip]
> >.
True.
>).
In the cache I had in in DefaultServlet, the entries were valid for 30s,
after which they had to be revalidated.
>.
Well, I'm pretty much neutral on caching policies. However, the more
aggressive we are, the better the benchmarks. Perhaps we could have
configuration options for this so that the user could tweak for performance
once the website is put in production (IIS has options like this) ?
> >.
Some shading problems at the top of the table.
> >
>
> element. The displayed filename should still have the spaces in it.
Right. I forgot to fix the link ...
> > I'll work on the WebDAV servlet for the immediate future.
> > Propfind is already done, so you can browse the site using Webfolders.
>
> Cool.
I'll try to have PUT and the namespace operations (mkcol, copy, move,
delete) working soon.
Remy | http://mail-archives.apache.org/mod_mbox/tomcat-dev/200007.mbox/%3C004301bffb26$f278b830$2901a8c0@exoffice.com%3E | CC-MAIN-2018-26 | refinedweb | 159 | 76.32 |
Creating and Consuming .NET Web Services in 5 Easy Steps
This article was written in 2002 and remains one of our most popular posts. If you’re keen to learn more about .NET, you may find this recent article on combining LESS with ASP.NET of great interest.
The Internet has a new player on the scene. It’s been surrounded by a great deal of hype — and even some television commercials! Apparently, this new, "next generation technology" will change the way business is done on the Web. It seems that soon, companies, their applications or software, and any Internet-enabled devices will easily be able to communicate with, and provide services to, one another regardless of platform or language. Sounds revolutionary!
So, what exactly is it that will open these boundless lines of communication? Web Services, that’s what!
Web services give developers the ability to utilize four open Web standards:
- HTTP – Hypertext Transfer Protocol
The standard protocol used over Port 80, which traverses firewalls, and is responsible for requesting and transmitting data over the Internet.
- SOAP – Simple Object Access Protocol
An XML-inherent protocol that encloses a set of rules for data description and process. As a standard, this is the center-piece that complements the other three standards mentioned here.
- XML – Extensible Markup Language
The most common markup language in which all this information is written.
- WSDL – Web Services Description Language
An XML-based method used to identify Web Services and their access at runtime. .NET provides a tool called WSDL.exe, which essentially makes it quite easy to generate an XML Web service as an XML file. This contains all the methods and instructions the Web Service has, and typically uses SOAP as its default.
This article will see you create and consume a data-driven .NET XML Web service in 5 quick and easy steps!
I’ll assume that you have a decent grasp of common .NET data access, Web server controls, such a datagrid, and some object-oriented programming concepts. If not, don’t worry too much. If you complete the examples, and view the results, you should have no difficulty in keeping up and observing the causes and effects of what this tutorial entails.
Prior to .NET, there were other alternatives that could be used to access a Web service, such as Microsoft’s MSXML component, which enabled you to communicate with the given Web Service over HTTP POST. However, this process, while acceptable, is just not .NET.
Ok, let’s begin!
Step 1 – Create the Web Service
First we’ll create the Web service function or method that’ll you’ll call (or “expose”) over the Internet as you would any object-oriented class. The difference is that we’ll have to incorporate and import all the necessary Web Services namespaces, syntax and attributes, as well as our data namespaces, in this case. As this article uses C#, any important differences regarding VB will be shown as well.
So go ahead and copy the code below to a file called suppliers.asmx. Save it to your Inetpub/wwwroot folder, and then run it in your browser using. What you’ll see is a list of the Web Service Descriptions, including the Web service name and the exposed method.
By clicking the exposed method link, you’ll be presented with the three main protocols that are available for your use. Just so you know, the file with the .asmx extension is the actual Web Service file that enables the ASP.NET runtime to return all pertinent exposed Web service methods and information.
<%@ WebService Language="C#" Class="GetInfo" %>
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
[WebService(Description="My Suppliers List Web Service")]
public class GetInfo : WebService
{
[WebMethod(BufferResponse=true)]
public DataSet ShowSuppliers (string str)
{
SqlConnection dbConnection = new SqlConnection("server=(local);
uid=sa;pwd=;database=Northwind;");
SqlDataAdapter objCommand = new SqlDataAdapter("select
ContactName, CompanyName, City, Phone from Suppliers
where Country = '" + str + "' order by ContactName
asc", dbConnection);
DataSet DS = new DataSet();
objCommand.Fill(DS);
return DS;
dbConnection.Close();
dbConnection = null;
}
}
The
<%@ WebService Language="C#" Class="GetInfo" %> directive sets up the file as a Web Service, gives it a name and specifies the language it uses. | https://www.sitepoint.com/net-web-services-5-steps/ | CC-MAIN-2018-51 | refinedweb | 704 | 56.35 |
Yet another object-based Hacker News API wrapper for Python.
Project description
a Hacker News API wrapper written in Python
Purpose
This was written with the goal of sticking close to the API in terms of naming and structure, but with the added benefits that come with using Python objects.
Installation
Use one of the following, depending on how your system is configured:
pip install hnpy pip3 install hnpy python3 -m pip install hnpy
Usage
Create an instance of the main class like this:
import hnpy hn = hnpy.HackerNews()
Items
If you know an item’s ID, you can access it like this:
post = hn.item(8863)
An Item can be one of five types: “job”, “story”, “comment”, “poll”, or “pollopt.” You can determine its type by accessing post.type.
Item objects are loaded lazily, meaning they only make network requests when information that they don’t already have is needed.
Items can be checked for equality against other Items or against the ID in int or str form.
Items have various attributes which depend on their type. You can use hasattr() to programmatically determine whether a certain Item has an attribute or not. More on attributes here. Attribute names in hnpy are copied from field names in the API.
Items have five special attributes:
The link and content attributes are noted here because the API does not directly provide them, so they are not documented elsewhere. The parent, poll and by attributes are noted because they contain fully-featured, lazily-loaded Items as opposed to just the IDs that the API responds with. The rest of an Items attributes are delivered in the same format that they are received from the API.
The attributes can be accessed like so:
post.content post.link post.parent post.poll post.by
Items also have 2 special methods which iterate and deliver Items. Each takes an optional limit= parameter which defaults to 25.
The methods can be used like this:
for kid in post.kids(limit=5): print(kid.content) for opt in post.parts(): print(opt.content)
Listings
You can use hnpy to view the following listings provided by Hacker News:
- Top (this is the view shown on the homepage of Hacker News)
- Best
- New
- Ask HN Stories
- Show HN Stories
- Job Stories
Just like the special methods of an Item, these methods of a HackerNews object take an optional limit= parameter. They iterate over the specified listing, yielding lazy Items as they go.
Example:
for post in hn.best(limit=5): print(post.link)
The method names are:
- top()
- best()
- new()
- ask()
- show()
- jobs()
Users
A User can be created from a user’s name using the HackerNews.user() method:
user = hn.user('jl')
Besides the attributes noted in the Hacker News API documentation, Users contain the following attributes and methods:
Misc
The HackerNews object has a method updates() which returns an Updates object, which has iterating methods just like those of other objects (optional limit= parameter, objects yielded) which give the most recently changed item and profiles (more info here). Its two methods are items() and profiles().
The HackerNews object also has a method max_item() which returns a lazy version of the newest Item.
Credits
This package came originally from my A Bot project. It was adapted to support lazy loading of objects, and as a consequence has only four classes (HackerNews, Item, User, Updates), rather than having a class for every type of Item with a complex inheritance model. This version also supports Users and Updates, which the old version did not.
This package was inspired by the Python Reddit API Wrapper aka PRAW (docs/source) in its use of objects and iteration methods and limit= parameters.
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/hnpy/ | CC-MAIN-2021-21 | refinedweb | 642 | 61.77 |
Hello guys,
It's been a while since I last time posted in this forum.
I have strange problem regarding matrix allocation. I was asked to write code that includes 2D array dynamic allocation. I write two version of matrix allocation.
Here is in my opinio relevant part of the code:
#include <stdio.h> #include <stdlib.h> int main( void ) { int rows, cols; int i, j; /*int * mat1Blok;*/ int ** mat1; printf("Enter number of rows: "); scanf("%d", &rows); printf("Enter number of columns: "); scanf("%d", &cols); /*memory allocation*/ /* mat1Blok = malloc(rows * cols * sizeof(int)); mat1 = malloc(rows * sizeof(int*)); for (i = 0; i < rows; ++i) { mat1[i] = &mat1Blok[i * cols]; } */ mat1 = malloc(cols * sizeof(int*)); for(i = 0; i < cols; i++) { mat1[i] = malloc(rows * sizeof(int)); } printf("\nEnter elements row by row:\n"); for (i = 0; i < rows; i++) for(j = 0; j < cols; j++) scanf("%d",&mat1[i][j]); /* free (mat1); free (mat1Blok); */ for (i = 0; i < cols; i++) { free (mat1[i]); } free (mat1); system("PAUSE"); return 0; }
I have tested both versions with Dev-Cpp on Windows platform and sent to my friend who discovered that if he uses version which is commented, everything is OK, but if he the use version as in the above code he gets segmentation fault when entering elements. He tested it in Linux. I don't have linux installed and i ask you to test this code and check if it will fail on linux machine. I don't see a reason for such behaviour and simply can't figure out what is wrong. He sad he got segmentation fault with rows = 3 and cols = 2.
Can you please check it?
Thanks | https://www.daniweb.com/programming/software-development/threads/80196/2d-array-allocation-problem | CC-MAIN-2017-26 | refinedweb | 281 | 67.28 |
You are browsing a read-only backup copy of Wikitech. The live site can be found at wikitech.wikimedia.org
Logstash/Common Logging Schema
The Observability team embarked on a project to adopt a Common Logging Schema in 2020. After evaluating options, the Observability team determined that adopting the Elastic Common Schema (ECS) had the best chance of success with the lowest barrier to entry.
Goals
- Control field growth.
- Establish consensus on field types and content.
- Provide guiding documentation for developers and users.
- Lay the groundwork for greater than 90 days log retention in compliance with our Privacy Policy and Data Usage Guidelines.
- Improve the overall user experience.
Rationale
At the time of the initial investigation, the logging cluster stored more than 14,000 unique fields. A limited subset of these fields were understood and used. As evidenced by a manual audit of saved objects, around 154 fields were actively being used. Of those fields, this number could be reduced to 81 by consolidating on a single shared name based on the field's content. Consolidating on a Common Logging Schema enabled us to drop many thousands of fields and provide guidance for users to seeking to share fields based on their content.
It was regularly reported that Kibana was slow to respond, partially due to the sheer number of fields it was required to deal with. This user experience led many to opt to use mwlog over Kibana for diagnosing issues due to familiarity and performance. The same datapoints such as a client IP or a url were stored in many different fields depending on the choices of the log producer. Leveraging a Common Logging Schema improves Kibana performance and enables users to find which field names contain the datapoints they are looking for.
Type conflicts and disagreements about what data a particular field should contain were commonplace. Sometimes, this resulted in a "forking" of the index pattern in an attempt to rectify the conflict. This action ultimately did not fix the problem and instead worsened the problem by making the fields in conflict unqueryable. It further worsened performance of the logging cluster by doubling the number of indexes required to be in memory and queried every time. Adopting a Common Logging Schema externalized field definitions from implementation and provided guidance for their use to drive consensus.
The mapping template attempted to guess the type of every field. Strings were configured to be analyzed and duplicated to another field in keyword form. A field's type was determined by the first log encountered with that field name at the point of index creation. If two or more producers used the same field name and ElasticSearch encountered a less-used type for that field first, the result would be all logs using that field with the more prevalent type would be dropped until the next index was generated. The Common Logging Schema sought to define types so that compliant producers could expect their logs to not be lost due to a type conflict.
Logstash filter configurations were complex and amending them was a perilous and error-prone process. Most of this problem was mitigated by adding an e2e filter verification step in CI and writing test cases. This CI step came many years after the logging cluster was in production making for very little test coverage for the amount of filter configuration. Adopting a Common Logging Schema incentivized writing tests for log producers when Logstash transformations were required to be made, as well as setting up a "fast-track" path that bypassed most filters when a producer is able to produce compliant log events.
Elastic Common Schema was chosen due to its availability, flexibility, and that it covered most use cases out of the box. The process for amending the schema followed the same patch request workflow most of the organization was accustomed to. Documentation could be generated and deployed after each merge. A system to manage multiple versions was added to the logging cluster configuration management so that amendments to the schema would not require waiting until the next index rotation to take effect.
Generating ECS-compliant Events
Required Fields
The one required field is
ecs.version set to the current ECS version found on the Wikimedia Documentation Portal. All other fields must comply with the definitions found in the [1] field reference section.
Migration Process
In collaboration with the Observability team, the migration process for non-ECS-compliant logs will largely follow this protocol:
- Logstash will duplicate a limited volume of log data into an ECS-compatible “staging” index.
- Relevant Kibana saved objects will be identified with coordination from stakeholders.
- ECS integration will be improved until identified Kibana saved objects are considered functional.
- Logs directed at the legacy indexes will be disabled.
- Saved objects will updated to reference only the new ECS indexes.
Features
Timestamp
All ECS-compliant events will attempt to parse and appropriately locate the
timestamp field. It will be parsed as an ISO-8601 datetime string and moved into the ECS-compliant
@timestamp field. If this field is unavailable or unparseable,
@timestamp will be set to a generated timestamp set to when the event was received by the logging pipeline.
Dot-Expansion
All ECS-compliant events can be provided as nested JSON objects, dot-delimited namespaced fields, or a mixture of the two. For example, these examples are ECS-compliant and are equivalent:
{ "service": { "type": "my_app" }, "log": { "level": "INFO", "facility": "local7" }, "message": "Something happened.", "ecs": { "version": "1.7.0" } }, { "service.type": "my_app", "log.level": "INFO", "log.facility": "local7", "message": "Something happened.", "ecs.version": "1.7.0" }, { "service": { "type": "my_app" }, "log": { "level": "INFO" }, "log.facility": "local7", "message": "Something happened.", "ecs.version": "1.7.0" }
Type field removal
All ECS-compliant events will have the base-level
type field removed early in the pipeline to prevent legacy filters from modifying the event.
Grok failures
If a grok parse failure occurs with an ECS-compliant event, the value at
log.original will be moved to the
message field. This is so that the event will be still be queryable even if the pipeline is unable to parse it.
Allow only ECS top-level fields
ECS-compliant events pass through
filter_on_template which strips out undefined top-level fields and populates
normalized.dropped.* fields.
Dropped fields tracking
Events with fields dropped by
filter_on_template populate
normalized.dropped.* fields. These fields are arrays containing the keys not found in the ECS template.
Planned Features
These features are not yet available.
Level Normalization
Events providing a
log.level but not a
log.syslog object will have a
log.syslog object generated for them based on available data. This is to facilitate level sorting and range queries on log levels between disparate log level naming conventions.
If no log level indicator can be identified,
log.level will be set to
NOTSET.
If
log.level cannot be mapped to RFC5424 severity, then
log.syslog.severity.name will be set to "alert" and
log.syslog.severity.code will be set to "1".
Maintenance
Deploying an updated schema
Once the patch is merged and CI has built and deployed the new documentation:
- Download the mapping template from the ECS docs page and add it to Puppet in the logstash templates directory. The Logstash ECS Cleanup Filter may need updating as well.
- Update the
version => revisionpair in the versions hash. One version can have only one revision available at a given time.
- Merge Puppet changes.
Deploying a new version of ECS
Update the ECS repository to check out the new version and resolve build issues, if any, then:
- Download the mapping template from the ECS docs page and add it to Puppet in the logstash templates directory. The Logstash ECS Cleanup Filter may need updating as well.
- Add the
version => revisionpair to the versions hash. One version can have only one revision available at a given time.
- Merge Puppet changes. | https://wikitech-static.wikimedia.org/w/index.php?title=Logstash/Common_Logging_Schema&oldid=581549 | CC-MAIN-2022-05 | refinedweb | 1,312 | 56.05 |
- 03 Dec, 2019 3 commits
- KitaitiMakoto authored
Rubinius hasn't been tested on for years, nor is it really relevant as a Ruby implementation these days. While Oga probably still works fine on Rubinius, I don't want to claim we support something when we officially don't.
See #196 for more information.
- 02 Nov, 2017 1 commit
- 11 Jul, 2017 1 commit
- 03 Jul, 2017 1 commit
- 21 Apr, 2016 1 commit
- 10 Feb, 2016 1 commit
- 22 Jan, 2016 1 commit
- 06 Sep, 2015 1 commit
Querying the same document concurrently _could_ lead to problems, so lets just recommend users to not even try this.
- 29 Jun, 2015 1 commit
-
- 15 Jun, 2015 1 commit
-
- 15 May, 2015 1 commit
While the MIT license is a fantastic license for those too lazy (or unable) to understand more complex licenses it's too lax when it comes to protecting authors (= me). For example, there are no clauses regarding patents or ownership of source code. This means that patent trolls could, in theory, drag me to court. Of course one can still do that when using the MPL, but at least it has an explicit clause regarding patents. The MPL also provides a nice balance between the MIT license and the Apache license. I don't like the Apache license as it requires listing any significant changes in every changed file. In short, I don't really care what people do with my software (they could sell it for millions for all I care), as long as they don't drag me to court or otherwise hold me accountable for something.
- 11 May, 2015 3 commits
This is already covered in CONTRIBUTING.md.
- 27 Apr, 2015 2 commits
- 21 Mar, 2015 1 commit
-
- 17 Nov, 2014 2 commits
- 16 Nov, 2014 4 commits
This changes the behaviour of after_element when parsing documents using the SAX parsing API. Previously it would always receive a nil argument, which is kinda pointless. This commit changes that by making sure it receives a namespace name (if any) and the element name. This fixes #54.
This closes #57.
- 16 Sep, 2014 2 commits
- 12 Sep, 2014 2 commits
- 11 Sep, 2014 1 commit
- 10 Sep, 2014 3 commits
- 09 Sep, 2014 1 commit
- 03 Sep, 2014 3 commits
- 22 Jul, 2014 2 commits
- 23 Jun, 2014 1 commit | https://gitlab.com/yorickpeterse/oga/-/commits/master/README.md | CC-MAIN-2021-39 | refinedweb | 393 | 66.67 |
Eric SCHAEFFER wrote:
>
> Hi,
>
> I think it's a little bug:
>
> In Cocoon.java, when you use a servlet 2.1 container, you try to load the
> config file using the servlet context, but if an error occured, you just trap
> the error and execute the rest of the code. I think you should return (or
> throw an exception)...
>
> (l.126) } catch (Exception ex) {
> exception = ex;
> message = "Unable to open resource: " + confsName;
> //// TEST ////
> return;
> //// TEST ////
> }
>
> Eric.
You're right, forgot to make it return if there's a problem.
> PS: when using the servlet context, the path is "relative" to the context
> root. I wonder if it's a good thing:
> I've installed Cocoon in a separate directory, where I put all my java
> packages, with a subdir for each one (jimi, bsf, cocoon, xerces, xalan,
> etc...). With this "feature", I must put the Cocoon properties file in a root
> context subdir (Web-inf for example). Thus, the jar file and the properties
> file aren't at the same place...
> Of course, we can consider that the config file is specific to my context, but
> ...
I'm all ears for help on Tomcat installation.
So far, I haven't heard a complete!
------------------------- --------------------- | http://mail-archives.apache.org/mod_mbox/cocoon-dev/200005.mbox/%3C391802DD.310F9988@apache.org%3E | CC-MAIN-2017-22 | refinedweb | 203 | 73.47 |
This site works best with JavaScript enabled. Please enable JavaScript to get the best experience from this site.
public BodyPart[] initHead(ModelMinion model) {
return null;
}
public BodyPart[] initTorso(ModelMinion model) {
return null;
}
public BodyPart[] initLegs(ModelMinion model) {
return null;
}
public BodyPart[] initArmLeft(ModelMinion model) {
return null;
}
public BodyPart[] initArmRight(ModelMinion model) {
return null;
}
@Override
public BodyPart[] initLegs(ModelMinion model) {
float[] torsoPos = {-4F, -2F, -2F}; //we will get to this in a sec
BodyPart leg = new BodyPart(mobName, torsoPos, model, 0, 16); //mobName is what you put in your super constructor, the 0 and 16 are texture offsets
leg.addBox(0.0F, 0.0F, 0.0F, 1, 12, 1, 0.0F); //create a 1x12x1 cube at coördinate 0, 0, 0
return new BodyPart[] {leg}; //return our leg
}
@Override
public BodyPart[] initTorso(ModelMinion model) {
float[] headPos = {4.0F, -8.0F, 2.0F};
float[] armLeftPos = {-4F, 0.0F, 2.0F};
float[] armRightPos = {8F, 0.0F, 2.0F};
BodyPart torso = new BodyPart(mobName, armLeftPos, armRightPos, headPos, model, 16, 16);
torso.addBox(0.0F, 0.0F, 0.0F, 8, 12, 4, 0.0F);
return new BodyPart[] {torso};
}
@Override
public BodyPart[] initHead(ModelMinion model) {
BodyPart head = new BodyPart(mobName, model, 0, 0);
head.addBox(-4, 0, -4, 8, 8, 8, 0.0F);
return new BodyPart[] {head};
}
@Override
public BodyPart[] initArmLeft(ModelMinion model) {
BodyPart armLeft = new BodyPart(mobName, model, 40, 16);
armLeft.addBox(0.0F, 0.0F, -2.0F, 4, 12, 4, 0.0F);
armLeft.mirror = true;
return new BodyPart[] {armLeft};
}
@Override
public BodyPart[] initArmRight(ModelMinion model) {
BodyPart armRight = new BodyPart(mobName, model, 40, 16);
armRight.addBox(0.0F, 0.0F, -2.0F, 4, 12, 4, 0.0F);
return new BodyPart[] {armRight};
}
@Override
public void setRotationAngles(float par1, float par2, float par3, float par4, float par5, float par6, Entity par7Entity, BodyPart[] bodypart, String string) {
}
@Override
public void setRotationAngles(float par1, float par2, float par3, float par4, float par5, float par6, Entity par7Entity, BodyPart[] bodypart, String string) {
if(string.equals("head")) {
bodypart[0].rotateAngleY = par4 / (180F / (float)Math.PI);
bodypart[0].rotateAngleX = par5 / (180F / (float)Math.PI);
}
if(string.equals("armLeft")) {
bodypart[0].rotateAngleX = MathHelper.cos(par1 * 0.6662F) * 2.0F * par2 * 0.5F;
bodypart[0].rotateAngleZ = 0.0F;
}
if(string.equals("armRight")) {
bodypart[0].rotateAngleX = MathHelper.cos(par1 * 0.6662F + (float)Math.PI) * 2.0F * par2 * 0.5F;
bodypart[0].rotateAngleZ = 0.0F;
}
if(string.equals("legs")) {
bodypart[0].rotateAngleX = MathHelper.cos(par1 * 0.6662F) * 1.4F * par2;
bodypart[1].rotateAngleX = MathHelper.cos(par1 * 0.6662F + (float)Math.PI) * 1.4F * par2;
bodypart[0].rotateAngleY = 0.0F;
bodypart[1].rotateAngleY = 0.0F;
}
}
public NecroEntityExample() {
super("EXAMPLE");
headItem = new ItemStack(exampleMod.exampleHeadItem); // the head item
torsoItem = new ItemStack(exampleMod.exampleTorsoItem); // the torso item
armItem = new ItemStack(exampleMod.exampleArmItem); // the arm item
legItem = new ItemStack(exampleMod.exampleLegItem); // the leg item
// you use ItemStacks to support damagevalues
texture = "/mob/zombie.png";
//texture location
textureHeigth = 64;
//the zombie texture is not 32x32 but 32x64.
hasHead = true;
hasTorso = true;
hasArms = true;
hasLegs = true;
//you can set these to false if your mob doesn't have some bodyparts. Creepers don't have arms for instance
}
@Override
public void initRecipes() {
headRecipe = new Object[] {"SSSS", "SBFS", "SEES",
'S', new ItemStack(organs, 1, 4), //skin
'E', Item.spiderEye,
'F', Item.rottenFlesh,
'B', new ItemStack(organs, 1, 0)}; //brains
torsoRecipe = new Object[] {" LL ", "BHUB", "LEEL", "BLLB",
'L', new ItemStack(organs, 1, 4), //skin
'E', Item.rottenFlesh,
'H', new ItemStack(organs, 1, 1), //heart
'U', new ItemStack(organs, 1, 3), //lungs
'B', Item.bone};
armRecipe = new Object[] {"LLLL", "BMEB", "LLLL",
'L', new ItemStack(organs, 1, 4), //skin
'E', Item.rottenFlesh,
'M', new ItemStack(organs, 1, 2), //muscle
'B', Item.bone};
legRecipe = new Object[] {"LBBL", "LMML", "LEEL", "LBBL",
'L', new ItemStack(organs, 1, 4), //skin
'E', Item.rottenFlesh,
'M', new ItemStack(organs, 1, 2), //muscle
'B', Item.bone};
}
java.lang.IllegalArgumentException: Slot SOME_SLOT is already occupied by SOME_MOD.SOME_BLOCK when adding SOME_MOD.SOME_BLOCK
[center][url=""][img][/img][/url][/center]
/minion [set] [aggressive/passive]
set your minions to aggressive or to passive
/minion [friend] [*]
set a player as a friend
/minion [enemy] [*]
set a player as a friend
return (new Random().nextInt(2) == 0 ? "alive" : "dead");
Quote from Killjoy5252
really been looking forward to this mod, and I'm sure it will be worth the wait ^.^
Quote from Mrdude1234
It is already out
Another thing, you need some more info on the sewing machine I have no idea what I can do
Quote from Eruraion
no it was released for an out-of-date version of minecraft so unless you have an old folder you cant play it
so technically its not out yet
Quote from sirolf2009
SCREENSHOTS
Quote from AznaktaX
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHHHHHHHHHHHHHHHHHH!!!!!!!!!!!!!!!!!!!!!
KILL IT!!!!
KILL IT WITH FIRE!!!!!
Quote from Mrdude1234
I found a bug... If you shift click in the sewing machine it crashes the game
Quote from PsiQss
Great mod, pretty original Will you be adding more stuff to it in the future?
And by the way, shouldn't it be "Necronomicon" instead of "Necromicon"?
Quote from Mrdude1234
lol
sirolf how do you control the mob
please forgive any of my comments I was like nine at the time of posting those
I'm fourteen now
PLEASE
Exspectata amicus. respondebo tibi, quid opus sit vobis regnum regat
Introduction
This mod is all about necromancy. Also known as the art of reanimation. using this mod, you can reanimate slain foes and use your minions to rule the world! (of minecraftia).
Download
Download 1.5 for MC 1.6.4 (thnx to AtomicStryker!)
Download 1.4b for MC 1.6.2
AdFly Download 1.4b for MC 1.6.2
Browse all versions
you have the right to have access the source code of the mod,
you have the right to be able to edit/use parts (or all) of the source code provided that you provide proper credit to the original authour(s),
you have the right to distribute the source code and/or compiled versions of the source code
you have the right to use this mod in Lets Plays/YouTube videos however you see fit (monetization, for fun, etc) as long as you provide credit to the original authour(s)(a link back to this thread for example)
if you wind up using parts of my mod in your own, then create a really awesome mod so that i can be proud
Source code
Please read the copyright note before downloading the source code
Necro API
The API allows modders to implement their own mobs into the game, if this mod and their mod is installed. Keep in mind that you have to wait for the next necromancy version for this to work. That doesn't mean that you have to wait to add your mobs though.
Download API v2.
API Tutorial (intended for modders only)
Download the API from the link above and extract it to your src folder (MCP/src). You should now see MCP/src/com/sirolf2009/necroapi. Inside the necroapi folder are a couple of classes. NecroEntityZombie is an example class.
Start off by creating a new class. For the sake of organizing call it NecroEntityExample where Example is your mob name. Use your mobs name in the super constructor. If your model extends ModelBiped or ModelQuadruped, make the new class extend NecroEntityBiped or ModelQuadruped and skip the spoiler.
If your model does not extend ModelBiped, you'll have to assign the bodyparts. Create four new methods:
these all return an array of bodyparts. Let's start with legs. Let's say your mobs leg is a 1x12x1 cube. You would change initLegs to this:
But sirolf2009, what's that torsoPos about? The torso pos defines the position of the torso. But why can't you simply make your torso 2F higher? Because your torso can be put on creeper legs and ender legs. If you would make your torso 2F higher, it will float above creeper legs and float inside the ender legs. For that reason, try to make your bodyparts around 0, 0, 0. On to the torso
as you can see we now have 3 positions. One for the head and two for the arms. Just add them to the BodyPart constructor and you'll be fine. Also, note that the torso is created at 0, 0, 0. As you have read before, that is to ensure it fits on any type of legs.
finally, the head and arms
These don't have locations stored in them, that's because there is nothing connected to them.
congratulations, you now have your model. On to animating.
create a new method in your NecroEntityExample class
this looks a lot like your regular setRotationAngles method, but this one has two extra parameters. The bodypart array contains the bodyparts you have initialized, the string contains the type of bodypart that needs to get animated. I'll just show you the biped animation code:
As you can see you can use the last parameter to see what is being animated. The biped model contains 2 legs, therefore the bodypart array contains 2 bodyparts.
You have now created and animated a model!
and we need to add recipes
Those are the recipes for the zombieparts. As you can see the item organs is used. This item stores brains, hearts, muscles, lungs and skin. Their damage value is in that order. Do not make any reference to "organs" outside this method. If you do, it can crash the game when the necromancy mod is not installed.
You are now ready to distribute your mod. You need to compile, obfuscate and publish the API alongside your mod. If you do not do this and someone installs your mod without mine, their minecraft will crash.
RECIPES/GUIDE
For additional information, check the wiki.. If you're on a server you can also hit the other players to get their blood.
Next up, the Necronomicon.
With the necronomicon you can create yourself a Summoning Altar! Place 2 cobblestone and a plank in a row (in the world, not the crafting bench) and right click the plank. You still can't summon a minion yet though. You need to get some souls first. How? With a Scythe, a Blood Scythe.
Use this weapon to kill some mobs and make sure you have some glass bottles left in your inventory. If you use the Scythe to deliver the final blow, a bottle will be filled with a soul.
One more thing. You need a Sewing Machine to create bodyparts. It is crafted like so
Now this is where it gets complicated. There are a lot of recipes so i won't post them all, but i'll show you the basic recipes, or templates if you will
You need to start with getting some skin.
with the skin, you can create heads, torso's, legs and arms. You'll also need some organs, these can be obtained by killing mobs.
You'll notice that these recipes won't work and that they have holes in them. Like I said before, these are the template recipes. Let's say you want to create a spider head, you take the head template recipe and put some string next to the brain. If you want a zombie head you put some rotten flesh next to the brain.
Back to the Summoning Altar. You should have body parts now and you should see a couple of slots in the Altar. The left one is for blood, the right one is for souls. Place your body parts body parts. If you have The Harken Scythe mod installed, you can also use their souls instead of mine.
So what can you do with your minions? As of now, not much. They will follow and protect you. You can also saddle them by using a saddle on them. Keep in mind that this only works if you minion has a spider torso. Shift right click to mount the minion and right click again do dismount. If you want, you can craft yourself a Brain on a Stick to control them.
Happy Summoning!
HALL OF FAME
crew and stuffs
sirolf2009 main coder, idea's, models, textures
Mr_boness idea's
TheBlackPixel textures
HP. Lovecraft writer
donators
Deborah W. $5.00 first donater ever!
FAQ AND TROUBLESHOOT
Browse to appdata/Roaming/.minecraft/config/ there should be a file called necromancy.cfg, open it and look for the conflicting ID. once you've found it, change it to some other random number. note that this might screw up existing worlds.
My minecraft crashed!
There should be a log inside .minecraft/ForgeModLoader-client-0.txt post it or I can't help you
Can I include this mod in my modpack?
Yes, as long as you put up some clear credits to me and my team.
Will you be adding more mobs?
yes, maybe not all of them though. Slimes and blazes don't really have bodyparts and ghasts are a bit big to name a few
VIDEOS
The most recent review
Captain Sparklez review! aww yeah! i feel like a bigshot now.
Foreign mod reviews
Polak
Deutsch
Português
Français
SCREENSHOTS
INSTALLATION
Download this mod version for your Minecraft version.
Download Minecraft Forge for your Minecraft version.
Drag and drop Forge into the minecraft.jar
Drag and drop this mod into the mods folder.
BANNER
CHANGELOG
Necromancy mod
3/8/13 1.4
Updated to 1.6.2
Added: Thaumcraft API support.
Added: Attributes
Changed: The name of the altar for compatibility with the Aether mod.
10/3/13 1.4b
Fixed: Missing textures
Fixed: Soul harvesting
Added: A WIP block
20/6/13 1.3
Fixed: Crash when Minion owner is offline
Fixed: Sewing recipes
Fixed: Special scythes are rendered only for special people
Fixed: Changing body parts
Fixed(?): Buggy needles and blood harvesting
17/6/13 1.2
Added: Bone Scythe
Fixed: Unable to harvest souls in multiplayer
Fixed: non-opped players can now acces the minion command
Fixed: Weird scythe rendering
Changed: Needles now work with right mouse button
Removed: Minion spawn eggs
12/6/13 1.1
Added: Cemetery (spawns in villages)
Added: Necromantic villagers (spawn in cemeteries)
Added: New command:
Changed: Ghouls spawn in every biome
Changed: Minions have more health and deal more damage
Fixed: Crash when harvesting souls
Fixed: Crash when using skulls
7/6/13 1.0
updated to 1.5.2
Added: NecroApi support
Added: More bodyparts
Added: New mob: Ghoul (AKA Nightcrawler)
Added: Special scythes for special people
Added: New command: "/remodel". This will re-initialize every bodypart from every minion
Changed: BodyParts have their own tab in the creative menu
Changed: The appearance of the necronomicon
Changed: Rewrote the rendering system to support the NecroApi
Changed: mcmod.info appearance (the page in the mod list)
Changed: The appearance of the altar
Fixed: Lag spikes
22/12/12 open beta 4
updated to 1.4.6
recipe for the teddy bear
rideable minions
craftable Brain on a Stick
Nether Chalices now generate in the nether
liquid blood
blood buckets
16/12/12 open beta 3
better SMP support (it's still not perfect)
better algorithm to remove lag spikes
fully functional sewing machine
new mob: enderman
christmas hats (will automatically be activated on christmas, or when you set christmas hats to true in the config file)
24/11/12 open beta 2
Update to 1.4.5
Added Blood Scythe
Removed Minion eggs
New Necronomicon recipe
Necro API
3/8/13 1.2
Added: Enum BodyPartLocation. Several methods have adapted this as a parameter rather than a string that indicates the location.
Added: Attributes
3/3/13 1.1b
package changes; the classes have not changed
13/2/13 1.1
better documentation
2 new methods in NecroEntityBase: preRender and postRender (used for rotationg)
new class: NecroEntityQuadruped
new interface: ISaddleAble, contains 2 methods: getRiderHeight and getSaddleTex
changed the example class to not give errors
DONATION
This mod is free to use, donating is appreciated but not required.
FINAL NOTE
If you're wondering what that latin at the top means: Welcome friend. Let me tell you about my work, for you shall rule the world with it.
Another thing, you need some more info on the sewing machine I have no idea what I can do
nothing at the moment, in the future it will be used to craft bodyparts, which are required to summon minions
no it was released for an out-of-date version of minecraft so unless you have an old folder you cant play it
so technically its not out yet
Here is a good one It goes back to Alpha 1.0.7
And by the way, shouldn't it be "Necronomicon" instead of "Necromicon"?
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHHHHHHHHHHHHHHHHHH!!!!!!!!!!!!!!!!!!!!!
KILL IT!!!!
KILL IT WITH FIRE!!!!!
sirolf how do you control the mob
Cue song: "Don't Fear The Creeper...."
yeah... the sewing machine isn't really intended for use at this point
woops XD, i'll try to update this mod to 1.4.5 tomorrow, and remove that bug with it
you don't but i can probably fix something up real quick so that you can tell them to follow/stand still by shift clicking
please forgive any of my comments I was like nine at the time of posting those
I'm fourteen now
PLEASE | http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-mods/1286889-1-6-4-the-necromancy-mod-1-5-necro-api-1-2?cookieTest=1 | CC-MAIN-2016-40 | refinedweb | 2,886 | 73.68 |
I just read Cay Horstmann's complaints about MacOS X as a Java development environment, and was struck by just how differently we perceive the coding universe.
I am reluctant to disagree with Dr. Horstmann, given the amount I have learned from his columns and books over the years, but I really think he is off base. He feels that MacOS X is far inferior to Linux as a coding environment, while I have had the opposite experience.
My world revolves around biotech consulting and custom applications. I work both on the server side and the client, and while Java is not my only tool, it is in an important one for what I do. I tend to need Perl, ssh, Java, and the usual productivity tools. It is not enough for me to have a nice development environment, I also need support tools as well, and the MacOS X environment gives me the tools I want in an interface that is acceptable.
Cay gives six ways in which the Mac is inferior. Of these, the first two are quite real - Apple does have some problems with VM start time, and they do have differences in the graphics subsystem. The specific problem Cay mentioned with his UML editor Violet have been fixed in Panther, but the overall problem of having a different vendor on Apple than on Windows and Linux is real. Deficiencies are fixed over time, but as long as Sun is the sole vendor for Java on Linux, Windows, and Solaris, they form the baseline of how the system should perform. Even when Sun violates the contract of its APIs, there will be people who will find any other behavior wrong, and when the alternative behavior is clearly inferior, the people complaining about Apple's implementation have a strong case.
The other four seem to stem from not differentiating between the developer communities and the corporate office. Like most corporate office wonks, Apple trade show reps seem to have told him that the Apple way is the only way. This is annoying, incorrect, and regrettably par for the course from all too many vendors. I recall trying, and failing, to get support from RedHat and Dell for a hardware configuration problem one of my clients had. It was not pretty, and that was with a paid support contract. In my experience, Apple has responded better to support requests, but I still find vendor support pretty lousy across the industry. The Linux world is not winning any prizes here, at least in my experience.
The Mac developer and user community, on the other hand, tends to have solved the problems that face them, some with Apple software and hardware, and some without. They tend to have third party mice, a mixture of open source, closed source, and Apple software, and an overall problem solving attitude. In this regard, they are very like the Linux developer communities. I do see rather less software modification, and more configuration, but they are getting their work done.
As far as hardware goes, I have been happy with my decision to use a TiBook/667 for my sole computing environment. It has been a trooper, only failing when I dropped it on a floor from a height. My wife's TiBook/400 has had two problems that justified sending it back to Apple for repairs, which is not as good a record, but first revs of new hardware often have their little surprises. In the main, the people I know with TiBooks have had pretty good luck with the hardware. Again, a real concern, but I have not had nearly as many problems as Cay seems to have had. Different usage patterns, perhaps, or different luck of the draw.
I do worry about Apple's commitment to Java. Their new XCode dev environment does not handle Java very well, though it does work. I am hoping that they are going to push Java development in future releases, but I am concerned. A major test will be 1.5 time to market, as that depends on a lot of factors.
Thanks be to Eclipse, which does work well. I also find it encouraging that they are now using JBoss as the underlayer to WebObjects, which might mean that Apple is finally willing to play nice with others.
Scott
Still too flaky.
I recently tried an app I wrote on a G5 with Panther and there are two problems that have made me sceptical of Apple's commitment to Java.
Firstly, it seems possible to get the VM to hang. While this is possible on all Java implementations, on the Apple the problem is that the VM is shared; so a problem in one app is also every other Java application's problem. Of course, the VM can be bounced but it does make one queasy especially if you have an audience.
Secondly, the Swing performance is terrible. The G5 rendering of JTables is at least 10 times slower than an old P3. A simple test is to create a table with 50 columns and 500 rows and try and scroll - sit back and watch those pixels paint.
What scares me most is that these are not the usual edge cases that slip through the QA dragnet; the kind that can be easily worked around when you understand the error. These problems are terminal.
Regards,
Brendon McLean.
Posted by: brendonm on October 29, 2003 at 09:41 AM
Still too flaky.
Howdy, Brendon.
Thanks much for responding.
I have not run into any VM hangs, but I have, perhaps, been lucky. Certainly, a machine-wide hang would be a killer for an app. Out of curiosity, does it peg the cpu when it does this? Also, do you have a thread dump?
As far as extremely slow JTables, I know a number of slow repaint bugs were caught and killed between 1.4.1 update 1 and Panther. One of mine came from aggressive setfont calls - a free op on windows, and a very expensive one on Jaguar. It is better now. I see what you mean, though, about poor performance for a 50x500 table. The following code is glacial.
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.util.*;
public class Test {
TableModel dataModel1 = new AbstractTableModel() {
public int getColumnCount() { return 50; }
public int getRowCount() { return 500;}
public Object getValueAt(int row, int col) { return new Integer(row*col); }
};
TableModel dataModel2 = new AbstractTableModel() {
ArrayList data=new ArrayList();
{
for (int col=0; col<getColumnCount(); col++){
ArrayList oneCol=new ArrayList();
data.add(oneCol);
for (int row=0; row<getRowCount(); row++){
oneCol.add(new Integer(row*col));
}
}
}
public int getColumnCount() { return 50; }
public int getRowCount() { return 500;}
public Object getValueAt(int row, int col) {
ArrayList oneCol = (ArrayList)data.get(col);
return oneCol.get(row);
}
};
public Test() {
JTable table1 = new JTable(dataModel1);
JScrollPane scrollpane1 = new JScrollPane(table1);
JFrame frame1 = new JFrame("model 1");
table1.setPreferredScrollableViewportSize(new Dimension(500, 70));
frame1.getContentPane().add(scrollpane1, BorderLayout.CENTER);
frame1.pack();
frame1.setVisible(true);
JTable table2 = new JTable(dataModel2);
JScrollPane scrollpane2 = new JScrollPane(table2);
JFrame frame2 = new JFrame("model 2");
table2.setPreferredScrollableViewportSize(new Dimension(500, 70));
frame2.getContentPane().add(scrollpane2, BorderLayout.CENTER);
frame2.pack();
frame2.setVisible(true);
}
public static void main(String[] args) {
new Test();
}
}
I suggest filing a bug on this and the freeze you mentioned, as there is a chance that this is a regression that can be fixed fairly easily. (I intend to file one on the table drawing bug, but the more votes they get, the more likely they are to fix it.)
I know it sometimes seems that Apple is not listening, but they do actually respond. Whether they have enough people working on Java is a very valid question, and one that I do not know the answer to.
Posted by: scottellsworth on October 29, 2003 at 11:03 AM
Indenting?
Hey is that code syntactically correct? I tried piping that into Eclipse and its barfing all over the place.
Is it possible to use indenting? or spaces? as I am not familar with the AbstractTableModel syntax.
Thanks
Posted by: kingjr3 on October 29, 2003 at 12:15 PM
Indenting?
I have put it on my fuz@mac.com iDisk in the public/jtable folder. The indenting survived there.
Scott
Posted by: scottellsworth on October 29, 2003 at 01:32 PM
me too
i use OSX as my development environment too, on a large cross platform project, while my friend next door works on Windows. Although there are problems with the Apple java, my experience is that there are at least as many problems with the Windows one - they're just different problems.
I suspect that Windows developers have internalised the problems with the Windows Java, so they don't notice them anymore. We've certainly had to work around a hell of a lot of Windows problems - for instance Drag and Drop is flaky enough that some of our internal tools are unusable on Windows, but fine on the Mac.
Apple's swing is slower for many things, but then I find it's faster for others. Certainly Netbeans is a lot more usable on my 900mhz Mac than it appears to be on a 2Ghz Windows machine. The JTable problem you're having does sound pathological, and I'd tend to agree that it should probably be filed as a bug rather than being indicative of general performance. And Apple's Look and Feel certainly looks a hell of a lot beter than Metal.
Yes. XCode isn't good at Java development. But you can use netbeans, or eclipse, just as on Windows or Linux. Hopefully XCode will get better over time, though I doubt it will ever be as good as the dedicated java tools. But our project involves compiling a very large native code library, and an equally large chunk of java, pulling in several open source libraries and packaging it all together. XCode can build it all from scratch and package it into a double clickable app with a single click. I don't know of any other tool as good.
Which brings me to another point - Java really is a viable language for the development of desktop apps on OSX. Lot's of people actually do it, and people *actually use Java apps on their desktop*. OSX treats Java as a first class citizen - by and large there's no reason for an end user to know they're running a java app (and if you're willing to forego cross platform compatibility and use Cocoa instead of Swing). Java apps on Windows always seem a compromise - and the destop experience is generally dreadful (which is why people avoid Java for desktop development).
Posted by: jportway on October 29, 2003 at 04:08 PM
Still too flaky.
Thanks. I'll file the bug today.
Posted by: brendonm on October 31, 2003 at 12:50 AM
Another Mac convert
I have a 17" Powerbook and a dual G5. I am happy happy happy with the Java support!
Yes, there are a few quirks, for the most part my stuff is working like a champ without any changes.
Posted by: turbogeek on November 03, 2003 at 04:15 PM
Mine Too!
I run JBuilder and CVS on both my Mac laptop and my Wintel box and use CVS to move code between them quickly and easily.
I carry a 3 button scroll mouse with my mac which works great. The Appel hardware guys may not be willing to entertain the notion of mreo then one button but the OSX guys have made OSX do everything you'ld expect if you have one.
I'm not sure I "get' the start-up time issue. The Mac VM in unique among Java VMs currently in that it shares static data between versions of the VM. Thus IME once you have a first VM up launching subsequent ones is like greased lightening. Sicne my IDE is ALREADY runnign in a VM I've fulfilled that requriement by definition.
In short I think Apple's got a lot of support for their claim that they are the "best Java desktop environment around."
Posted by: jeffpk on November 07, 2003 at 02:23 PM
me too
I am using a 17" PowerBook with OS X 10.3.2 and I develop bioinformatic applications using Java and IntelliJ. I am glad that Apple is trying to make Java a first-class citizen on OS X. In fact, this is one of the main reasons I am using OS X after so many years of linux and windows. I can have Java and easily the best looking interface of any OS out there while maintaining the use of my UNIX utilities and the shell. I only hope that Apple will continue to push Java on OS X. So far, all my Java apps have run just fine without any major performance problems.
Posted by: sleepy on December 25, 2003 at 06:54 05:44
网络营销软件
网站推
Posted by: uuok999 on December 20, 2007 at 12:07 AM | http://weblogs.java.net/blog/scottellsworth/archive/2003/10/macos_x_is_my_j.html | crawl-002 | refinedweb | 2,189 | 70.94 |
Circle view for ui
i am trying to make a circular view/widget like we have for our pics in the forum. I think I am going about it the right way. I am using a custom ui.View class and overriding the draw method.
I can make a white circle that is clipped...Yeah 🎉🎉🎉
Not what I need though. I need to be able to invert my clipping so I get a keyhole effect. The idea is that this view would be placed on top of a image view, just showing the circular cut out of the image beneath.
I think the answer lies with the append_path method. For some reason, I can think through it. Any help appreciated.
import ui class CircularView(ui.View): def __init__(self): pass def draw(self): oval = ui.Path.oval(0,0, self.width, self.height) rect = ui.Path.rect(0,0, self.width, self.height) #rect.append_path(oval) ui.Path.add_clip(oval) ui.set_color('white') oval.fill() if __name__ == '__main__': cv = CircularView() cv.present('sheet')
Something like this should work as your
drawmethod:
def draw(self): oval = ui.Path.oval(*self.bounds) rect = ui.Path.rect(*self.bounds) oval.append_path(rect) oval.eo_fill_rule = True oval.add_clip() ui.set_color('white') rect.fill()
UPDATED: WORKS IN PYTHON 2 AND 3 ->
If what you're looking for is a cropped round image, this works
# coding: utf-8 #these are fillers for phhton 3 changes try: import cStringIO cStringIO.BytesIO = cStringIO.StringIO print("old cString") import urllib2 except ImportError: import io as cStringIO #from io import StringIO as cStringIO import urllib.request as urllib2 print("new stringIO") #ALSO WORKS INSTEAD OF TRY EXCEPT ABOVE FOR PYTHON 2 AND 3 #import io as cStringIO #import urllib2 import ui from PIL import Image, ImageOps, ImageDraw import io def grabImageFromURL(url): url=url #load image from url and show it imageDataFromURL = urllib2.urlopen(url).read() print("imageData from URL of Type: "+str(type(imageDataFromURL))) return imageDataFromURL def circleMaskViewFromImageData(imageData): imageDataFromURL=imageData #load image from url and show it #imageDataFromURL = urllib2.urlopen(url).read() file=cStringIO # pil <=> ui def pil2ui(imgIn): with io.BytesIO() as bIO: imgIn.save(bIO, 'PNG') imgOut = ui.Image.from_data(bIO.getvalue()) del bIO return imgOut def wrapper(func, *args, **kwargs): #console.clear()()
@omz , thanks. Works great. I searched the forum, could not find a reference to it. So surprised. I would have thought a lot would have been asking about this.
@Tizzy , hey thanks for your solution. I was actually looking for what @omz suggested. Hope you didn't waste your time.
But the above also maybe helpful for you as its light weight.
Once I make it into something reusable,I will post share
@Tizzy FYI,
io.StringIOexists on Python 2 and 3, and
urllib3is a third-party (not Python standard library) module, so it also exists on both versions. (The Python 3 version of
urllib2is called
urllib.) And if you do
from PIL import Image, you don't need to do
import Imageafterwards.
@Phuket2 No worries had this lying around.
@dgelessus thanks for the tip. Yeah I think I imported image separately because at one point it wasn't working..I'm not sure why (I don't remember) but maybe one of the betas? Goes to show my modus operandi - smack it with a hammer until it works. I'll go ahead and take it out. The reason I didn't do just
io.StringIOis because I was under the impressions that
cStringIOis faster, at least when in Python 2 - please correct me if I'm wrong.
I've amended the script above.
I thought I had this working in Python 3 but I guess not! As it currently stands in pythonista 3 I get the error
TypeError: initial_value must be str or None, not bytesat line 23 where
file=cStringIO.StringIO(urllib2.urlopen(url).read())
(Keep in mind I did
import io as cStringIOand
import urllib.request as urllib2for when it's in Python3 mode )
If you're dealing with Python 3 compatibility, you need to be very careful about what "string" types you're using. In Python 2, default
stris a byte string and
unicodeis (almost) full Unicode; in Python 3, default
stris full Unicode and
bytesis obviously a byte string. (In Python 2,
bytesis a valid alternate name for
str.)
In this case it looks like
urllib2.urlopen(url).read()returns
bytes, and you're feeding it into a
StringIO, which expects a text string. Python 2 is sloppy with the distinction and force-decodes
bytes/
strusing UTF-8 into
unicode, so everything works fine there. In Python 3, no automatic conversion happens, and
StringIOcomplains because you gave it
bytesinstead of a Unicode
str.
How to solve this:
- Simply
import iono matter what Python version you use. Then
io.StringIOworks with Unicode strings, and
io.BytesIOwith byte strings. (Also when working with local files, use
io.openrather than
open. On Python 2 this allows proper use of
unicode, and on Python 3
open == io.open.)
- In this case, always use
bytes, as you're working with binary image data. Use the name
bytesinstead of
str,
BytesIOinstead of
StringIO, and if you need to use literals, write
b"..."instead of
"...". (This of course only applies to cases where you want to use binary data. When working with text, you should use Unicode when possible.)
- When writing scripts that should work on Python 2 and 3, start in Python 3. There you will get errors when you mix up
bytesand
strby accident, instead of "magical" conversion like in Python 2. Once your code works on Python 3, try to run it on Python 2 and fix what doesn't work.
@dgelessus Thanks so much for imparting your knowledge on me. I've edited the above script such that the code is the same, but the namespace changes based on if it's python 2 or 3 (there's probably a reason this is not recommended but i set
cStringIO.BytesIO = cStringIO.StringIOfor the python 2 case, and it works in both now. ) I also broke out the getting an image from url and masking it parts into separate functions.
you mention
io.openinstead of
open.... do you mean instead of
Image.open()? Because that seems to be different? or did you mean in general, and not in this example?
about bytes - if i do
print(type(bytes(imageDataFromURL)))it still prints out as
<type "str">in python2.
Finally, I decided to test
cStringIO.StringIO()vs
io.BytesIOand Python2 vs 3 by using
timeit.Timer().timeit(number=1000)for 1000 operations each. (Done on an iPhone 6s +) Here are the results:
Pythonista 2 using cStringIO.StringIO():
396.739
Pythonista 2 using io.BytesIO:
397.933
397.154
Pythonista 3 using io.BytesIO():
383.361
As you can see the difference between
cStringIO.StringIO()and
io.BytesIO()seems to be negligible.
Pythonista 3 w/ io.BytesIO seems to outperform Pythonista 2 and io.BytesIO by average of about .0133 seconds per run which is a small but I believe notable gain especially if you do this operation over and over again.
So, in conclusion, there doesn't seem to be any reason to use cStringIO.StringIO() over io.BytesIO() in python2.
I'll post the simplified code to reflect that conclusion below.
# coding: utf-8 #import time import ui import io from PIL import Image, ImageOps, ImageDraw #Try except for python2 vs 3 try: import urllib2 print("pyth2") except ImportError: import urllib.request as urllib2 print("pyth3") def grabImageFromURL(url): url=url #load image from url and show it imageDataFromURL = urllib2.urlopen(url).read() print("imageData from URL of Type: ",type(bytes(imageDataFromURL))) return imageDataFromURL def circleMaskViewFromImageData(imageData): imageDataFromURL=imageData #imageDataFromURL = urllib2.urlopen(url).read() #broken out into separate function ^^^ file=io def pil2ui(imgIn): #pil image to ui image with io.BytesIO() as bIO: imgIn.save(bIO, 'PNG') imgOut = ui.Image.from_data(bIO.getvalue()) del bIO return imgOut def wrapper(func, *args, **kwargs): #wrapper function for timing with parameters()
Forget that with
io.openfor now - that is for reading local files (I forgot for a moment that you read the data from a URL, not a file).
io.openis Python 3's
openfunction backported to Python 2, which means that (among other things) Unicode is handled correctly.
On Python 2, there is no dedicated
bytestype. Because
stris a bytestring in Python 2,
bytesis simply an alias for
str. In pseudo-Python code:
class str(object): ... bytes = str
For reference, for anyone searching for this topic, why was this not done with
corner_radius? | https://forum.omz-software.com/topic/2902/circle-view-for-ui | CC-MAIN-2021-49 | refinedweb | 1,430 | 68.26 |
There are some computer games or applications where you need to repeatedly click on the same place on the screen many times. Imagine a game where you chop down a tree by clicking on it. Then a next tree appears on the same spot, so after a while, you need to click there again.
As we are human beings, we like to simplify boring tasks. As programmers, we can simplify this task by creating software to do it for us.
What do we need to do in the autoclicker? To keep things simple, we only set two things: where to click and how often to click. The point where to click can be stored in a variable of type Point, the interval will be set on our Timer.
Point
Timer
The first thing to do is to create a new Windows Form. Then we add our variable to hold the click location.
//this will hold the location where to click
Point clickLocation = new Point(0,0);
Next, we need to set the location for our clicking. One of the ways to do this is to start a countdown. While it is running, the user can point the mouse to the desired position and after the countdown ends, we get its coordinates.
We can do this by activating appropriately long timeout (for example 5 seconds) and then collecting the mouse location. So, we can add a button with following OnClick event handler:
OnClick
private void btnSetPoint_Click(object sender, EventArgs e)
{
timerPoint.Interval = 5000;
timerPoint.Start();
}
We also create a timer to help us get the mouse location. We can get the mouse location from the Position property of the Cursor class. The set location can be displayed for example on the window title.
Position
Cursor
So, let's create the second timer and add the following Tick handler to it:
Tick
private void timerPoint_Tick(object sender, EventArgs e)
{
clickLocation = Cursor.Position;
//show the location on window title
this.Text = "autoclicker " + clickLocation.ToString();
timerPoint.Stop();
}
Now we want to set the main timer interval (we can use the NumericUpDown control). Remember that the lower bound of its interval should be greater than zero, as we cannot set the timer interval to zero milliseconds.
NumericUpDown
Now to the clicking itself. In each time our main timer elapses (add another Timer control to the form), we want to click on a specified position. We cannot do this in pure managed code, we must use the import method SendInput of the user32.dll library. We will use it to synthesize the mouse click. Don't forget to place using System.Runtime.InteropServices; to the beginning of your code when you use DllImport.
SendInput
using System.Runtime.InteropServices;
DllImport
[DllImport("User32.dll", SetLastError = true)]
public static extern int SendInput(int nInputs, ref INPUT pInputs,
int cbSize);
The method SendInput uses three parameters:
nInputs
pInputs
pInputs
cbSize
To keep things simple, we will use only one INPUT structure. We will need to define this structure and some constants too:
INPUT
//mouse event constants
const int MOUSEEVENTF_LEFTDOWN = 2;
const int MOUSEEVENTF_LEFTUP = 4;
//input type constant
const int INPUT_MOUSE = 0;
public struct MOUSEINPUT
{
public int dx;
public int dy;
public int mouseData;
public int dwFlags;
public int time;
public IntPtr dwExtraInfo;
}
public struct INPUT
{
public uint type;
public MOUSEINPUT mi;
};
Each time our timer elapses, we want to click. We do it by moving the cursor to the memorized place, then setting up the INPUT structure and filling it with required values. Each click consists of pressing mouse button and releasing mouse button, so we need to send two messages - one for button down (press) and another for button up (release).
So add a handle to the Tick event of the main timer with this code:
private void timer1_Tick(object sender, EventArgs e)
{
//set cursor position to memorized location
Cursor.Position = clickLocation;
//set up the INPUT struct and fill it for the mouse down
INPUT i = new INPUT();
i.type = INPUT_MOUSE;
i.mi.dx = 0;
i.mi.dy = 0;
i.mi.dwFlags = MOUSEEVENTF_LEFTDOWN;
i.mi.dwExtraInfo = IntPtr.Zero;
i.mi.mouseData = 0;
i.mi.time = 0;
//send the input
SendInput(1, ref i, Marshal.SizeOf(i));
//set the INPUT for mouse up and send it
i.mi.dwFlags = MOUSEEVENTF_LEFTUP;
SendInput(1, ref i, Marshal.SizeOf(i));
}
Finally - we can use a button to start/stop the autoclicking feature. Let's create a button with the following handler:
private void btnStart_Click(object sender, EventArgs e)
{
timer1.Interval = (int)numericUpDown1.Value;
if (!timer1.Enabled)
{
timer1.Start();
this.Text = "autoclicker - started";
}
else
{
timer1.Stop();
this.Text = "autoclicker - stopped";
}
}
That's it. It's quite simple. How can we further improve this program?
We could...
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
[DllImport("User32.dll", SetLastError = true)]
public static extern int SendInput(int nInputs, ref INPUT pInputs,
int cbSize);
General News Suggestion Question Bug Answer Joke Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | http://www.codeproject.com/Articles/15406/Creating-a-Simple-Autoclicker | CC-MAIN-2015-22 | refinedweb | 847 | 65.32 |
Async and Await are extensions of promises. So if you are not clear about the basics of promises please get comfortable with promises before reading further. You can read my post on Understanding Promises in Javascript.
I am sure that many of you would be using async and await already. But I think it deserves a little more attention. Here is a small test : If you can’t spot the problem with the below code then read on.
for (name of ["nkgokul", "BrendanEich", "gaearon"]) {
userDetails = await fetch("" + name);
userDetailsJSON = await userDetails.json();
console.log("userDetailsJSON", userDetailsJSON);
}
We will revisit the above code block later, once we have gone through async await basics. Like always Mozilla docs is your friend. Especially checkout the definitions.
async and await
From MDN
An asynchronous function is a function which operates asynchronously via the event loop, using an implicit
Promiseto return its result. But the syntax and structure of your code using async functions is much more like using standard synchronous functions.
I wonder who writes these descriptions. They are so concise and well articulated. To break it down.
- The function operates asynchronously via event loop.
- It uses an implicit Promise to return the result.
- The syntax and structure of the code is similar to writing synchronous functions.
And MDN goes on to say
An
asyncfunction can contain an
awaitexpression that pauses the execution of the async function and waits for the passed
Promise‘s resolution, and then resumes the
asyncfunction’s execution and returns the resolved value. Remember, the
awaitkeyword is only valid inside
asyncfunctions.
Let us jump into code to understand this better. We will reuse the three function we used for understanding promises here as well.
A function that returns a promise which resolves or rejects after n number of seconds.
var promiseTRRARNOSG = (
promiseThatResolvesRandomlyAfterRandomNumnberOfSecondsGenerator= function() {
return new Promise(function(resolve, reject) {
let randomNumberOfSeconds = getRandomNumber(2, 10);
setTimeout(function() {
let randomiseResolving = getRandomNumber(1, 10);
if (randomiseResolving > 5) {
resolve({
randomNumberOfSeconds: randomNumberOfSeconds,
randomiseResolving: randomiseResolving
});
} else {
reject({
randomNumberOfSeconds: randomNumberOfSeconds,
randomiseResolving: randomiseResolving
});
}
}, randomNumberOfSeconds * 1000);
});
});
Two more deterministic functions one which resolve after n seconds and another which rejects after n seconds.
var promiseTRSANSG = (promiseThatResolvesAfterNSecondsGenerator = function(
n = 0
) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve({
resolvedAfterNSeconds: n
});
}, n * 1000);
});
});
var promiseTRJANSG = (promiseThatRejectsAfterNSecondsGenerator = function(
n = 0
) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
reject({
rejectedAfterNSeconds: n
});
}, n * 1000);
});
});
Since all these three functions are returning promises we can also call these functions as asynchronous functions. See we wrote asyn functions even before knowing about them.
If we had to use the function
promiseTRSANSG using standard format of promises we would have written something like this.
var promise1 = promiseTRSANSG(3);
promise1.then(function(result) {
console.log(result);
});
promise1.catch(function(reason) {
console.log(reason);
});
There is a lot of unnecessary code here like anonymous function just for assigning the handlers. What async await does is it improves the syntax for this which would make seem more like synchronous code. If we had to the same as above in async await format it would be like
result = await promiseTRSANSG(3);
console.log(result);
Well that look much more readable than the standard promise syntax. When we used
await the execution of the code was blocked. That is the reason that you had the value of the promise resolution in the variable
result. As you can make out from the above code sample, instead of the
.then part the result is assigned to the variable directly when you use
await You can also make out that the
.catch part is not present here. That is because that is handled using
try catch error handling. So instead of using
promiseTRSANS let us use
promiseTRRARNOSG Since this function can either resolve or reject we need to handle both the scenarios. In the above code we just wrote two lines to give you an easy comparison between the standard format and
async await format. The example in next section gives you a better idea of the format and structure.
General syntax of using
async
await
async function testAsync() {
for (var i = 0; i < 5; i++) {
try {
result1 = await promiseTRRARNOSG();
console.log("Result 1 ", result1);
result2 = await promiseTRRARNOSG();
console.log("Result 2 ", result2);
} catch (e) {
console.log("Error", e);
} finally {
console.log("This is done");
}
}
}
test();
From the above code example you can make out that instead of using the promise specific error handling we are using the more generic approach of using
try
catch for error handling. So that is one thing less for us to remember and it also improves the overall readability even after considering the try catch block around our code. So based on the level of error handling you need you can add any number of
catch blocks and make the error messages more specific and meaningful.
Pitfalls of using async and await
async await makes it much more easier to use promises. Developers from synchronous programming background will feel at home while using
async and
await. This should also alert us, as this also means that we are moving towards a more synchronous approach if we don’t keep a watch.
The whole point of javascript/nodejs is to think asynchronous by default and not an after though.
async await generally means you are doing things in sequential way. So make a conscious decision whenever you want to use to async await.
Now let us start analysing the code that I flashed at your face in the beginning.
for (name of ["nkgokul", "BrendanEich", "gaearon"]) {
userDetails = await fetch("" + name);
userDetailsJSON = await userDetails.json();
console.log("userDetailsJSON", userDetailsJSON);
}
This seems like a harmless piece of code that fetches the github details of three users
“nkgokul”, “BrendanEich”, “gaearon” Right. That is true. That is what this function does. But it also has some unintended consequences.
Before diving further into the code let us build a simple timer.
startTime = performance.now(); //Run at the beginning of the code
function executingAt() {
return (performance.now() - startTime) / 1000;
}
Now we can use
executingAt wherever we want to print the number of seconds that have surpassed since the beginning.
async function fetchUserDetailsWithStats() {
i = 0;
for (name of ["nkgokul", "BrendanEich", "gaearon"]) {
i++;
console.log("Starting API call " + i + " at " + executingAt());
userDetails = await fetch("" + name);
userDetailsJSON = await userDetails.json();
console.log("Finished API call " + i + "at " + executingAt());
console.log("userDetailsJSON", userDetailsJSON);
}
}
As you can find from the output, each of the await function is called after the previous function was completed. We are trying to fetch the details of three different users
“nkgokul”, “BrendanEich”, “gaearon” It is pretty obvious that output of one API call is in noway dependent on the output of the others.
The only dependence we have is these two lines of code.
userDetails = await fetch("" + name);
userDetailsJSON = await userDetails.json();
We can create the
userDetailsJSON object only after getting the
userDetails. Hence it makes sense to use await here that is within the scope of getting the details of a single user. So let us make an
async for getting the details of the single user.
async function fetchSingleUsersDetailsWithStats(name) {
console.log("Starting API call for " + name + " at " + executingAt());
userDetails = await fetch("" + name);
userDetailsJSON = await userDetails.json();
console.log("Finished API call for " + name + " at " + executingAt());
return userDetailsJSON;
}
Now that the
fetchSingleUsersDetailsWithStats is async we can use this function to fetch the details of the different users in parallel.);
}
When you want to run things in parallel, the thumb rule that I follow is
Create a promise for each async call. Add all the promises to an array. Then pass the promises array to Promise.all This in turn returns a single promise for which we can use await
When we put all of this together we get
startTime = performance.now(););
}
async function fetchSingleUsersDetailsWithStats(name) {
console.log("Starting API call for " + name + " at " + executingAt());
userDetails = await fetch("" + name);
userDetailsJSON = await userDetails.json();
console.log("Finished API call for " + name + " at " + executingAt());
return userDetailsJSON;
}
fetchAllUsersDetailsParallelyWithStats();
The output for this is
As you can make out from the output, promise creations are almost instantaneous whereas API calls take some time. We need to stress this as time taken for promises creation and processing is trivial when compared to IO operations. So while choosing a promise library it makes more sense to choose a library that is feature rich and has better dev experience. Since we are using
Promise.all all the API calls were run in parallel. Each API is taking almost 0.88 seconds. But since they are called in parallel we were able to get the results of all API calls in 0.89 seconds.
In most of the scenarios understanding this much should serve us well. You can skip to Thumb Rules section. But if you want to dig deeper read on.
Digging deeper into await
For this let us pretty much limit ourselves to
promiseTRSANSG function. The outcome of this function is more deterministic and will help us identify the differences.
Sequential Execution
startTime = performance.now();
var sequential = async function() {
console.log(executingAt());
const resolveAfter3seconds = await promiseTRSANSG(3);
console.log("resolveAfter3seconds", resolveAfter3seconds);
console.log(executingAt());
const resolveAfter4seconds = await promiseTRSANSG(4);
console.log("resolveAfter4seconds", resolveAfter4seconds);
end = executingAt();
console.log(end);
}
sequential();
Parallel Execution using Promise.all
var parallel = async function() {
startTime = performance.now();
promisesArray = [];
console.log(executingAt());
promisesArray.push(promiseTRSANSG(3));
promisesArray.push(promiseTRSANSG(4));
result = await Promise.all(promisesArray);
console.log(result);
console.log(executingAt());
}
parallel();
Concurrent Start of Execution
asynchronous execution starts as soon as the
promise is created.
await just blocks the code within the
async function until the promise is resolved. Let us create a function which will help us clearly understand this.
var concurrent = async function() {
startTime = performance.now();
const resolveAfter3seconds = promiseTRSANSG(3);
console.log("Promise for resolveAfter3seconds created at ", executingAt());
const resolveAfter4seconds = promiseTRSANSG(4);
console.log("Promise for resolveAfter4seconds created at ", executingAt());
resolveAfter3seconds.then(function(){
console.log("resolveAfter3seconds resolved at ", executingAt());
});
resolveAfter4seconds.then(function(){
console.log("resolveAfter4seconds resolved at ", executingAt());
});
console.log(await resolveAfter4seconds);
console.log("await resolveAfter4seconds executed at ", executingAt());
console.log(await resolveAfter3seconds);
console.log("await resolveAfter3seconds executed at ", executingAt());
};
concurrent();
From previous post we know that
.then is even driven. That is
.then is executed as soon as the promise is resolved. So let us use
resolveAfter3seconds.thenand
resolveAfter4seconds.then to identify when our promises are actually resolved. From the output we can see that
resolveAfter3seconds is resolved after 3 seconds and
resolveAfter4seconds is executed after 4 seconds. This is as expected.
Now to check how
await affects the execution of code we have used
console.log(await resolveAfter4seconds);
console.log(await resolveAfter3seconds);
As we have seen from the output of
.then
resolveAfter3seconds resolved one second before
resolveAfter4seconds . But we have the
await for
resolveAfter4seconds and then followed by
await for
resolveAfter3seconds
From the output we can see that though
resolveAfter3seconds was already resolved it got printed only after the output of
console.log(await resolveAfter4seconds); was printed. Which reiterates what we had said earlier.
await only blocks the execution of next lines of code in
async function and doesn’t affect the promise execution.
Disclaimer
MDN documentation mentions that
Promise.all is still serial and using
.then is truly parallel. I have not been able to understand the difference and would love to hear back if anybody has figured out their heard around the difference.
Thumb Rules
Here are a list of thumb rules I use to keep my head sane around using
async and
await
ayncfunctions returns a promise.
asyncfunctions use an implicit Promise to return its result. Even if you don’t return a promise explicitly
asyncfunction makes sure that your code is passed through a promise.
awaitblocks the code execution within the
asyncfunction, of which it(
await statement) is a part.
- There can be multiple
awaitstatements within a single
asyncfunction.
- When using
async awaitmake sure to use
try catchfor error handling.
- If your code contains blocking code it is better to make it an
asyncfunction. By doing this you are making sure that somebody else can use your function asynchronously.
- By making async functions out of blocking code, you are enabling the user who will call your function to decide on the level of asynhronicity he wants.
- Be extra careful when using
awaitwithin loops and iterators. You might fall into the trap of writing sequentially executing code when it could have been easily done in parallel.
awaitis always for a single promise. If you want to
awaitmultiple promises(Run this promises in parallel) create an array of promises and then pass it to the
Promise.allfunction.
- Promise creation starts the execution of asynchronous functionality.
awaitonly blocks the code execution within the
asyncfunction. It only makes sure that next line is executed when the
promiseresolves. So if an asynchronous activity has already started then
awaitwill not have an effect on it.
Please point out if I am missing something here or if something can be improved. If you liked this article and would like to read similar articles, don’t forget to clap. There is a limit of 50 claps on medium. Do check it out 😉
You can also read to know why clapping is important.
My learning Series
Last month I made a resolve to make some conscious changes to my learning rhythm. You can read it here — and have started this series as a part of that.
You can read the others articles from the series.
read original article here | https://coinerblog.com/understanding-async-await-in-javascript-hacker-noon/ | CC-MAIN-2020-24 | refinedweb | 2,232 | 58.18 |
A couple of programmers, much better than I, have looked at the code and declared it was poorly written. While that may be the case, it does what it is supposed to do. I am considering throwing it out as open source and hoping that some talented coders might adopt it and clean it up. But I need to figure out; if Perl programmers need this sort of library. If anybody is interested in working on it. Is there a checklist or process to follow to make this open source?
**UPDATE**
Created a github site for the initial cleanup and organizing to add into CPAN once namespace is resolved/approved. Perl-PDF-LIbrary (LI is capitalized as a shout out to the original programmer Joey Li)
Looking for any and all help, need some help with the POD, graphic handling, text flow, test scripts and if anyone has done this kind of thing before a mentor to help me roadmap and manage the project.
But I need to figure out; if Perl programmers need this sort of library.
That probably at least in part depends on what it does that isn't already supported by other Perl PDF libs, such as PDF::API2. Maybe it's worth integrating efforts, rather than publishing another lib with (likely) mostly overlapping functionality.
Other than that, if you own the rights, why not just do open source it, and let software evolution dynamics decide on its future?
Yes, it does things that PDF::API2 does not, the XML, the forms and it is well documented.
The reason I don't want to just throw it into open source is that I don't want to take resources that might be better served on a project that more people want, or that already has a head of steam. Maybe that is over thinking it.
I understand the concerns, but I think it's generally hard to predict whether open sourcing something will result in an unproductive division of resources (man power of volunteers), or whether it will ultimately be beneficial, e.g. by promoting positive competition, by making it possible to merge functionalities, or by simply having two good libs being developed independently... (like there are many good text editors or scripting languages out there, with each having their fan base).
So I'm not really sure what to advise, in particular as I don't even yet know the library in any reasonable detail...
Is there a checklist or process to follow to make this open source?
If you make this open source via CPAN, the checklist you're after is provided on this PAUSE (Perl Authors Upload Server) page.
-- Ken.
Used as intended
The most useful key on my keyboard
Used only on CAPS LOCK DAY
Never used (intentionally)
Remapped
Pried off
I don't use a keyboard
Results (441 votes),
past polls | http://www.perlmonks.org/?node_id=958299 | CC-MAIN-2015-11 | refinedweb | 480 | 66.98 |
#include <MFnContainerNode.h>
MFnContainerNode is the function set for creating, querying and editing containers.
Maya uses container nodes to bundle sets of related nodes together with a published attribute list that defined the primary interface to those nodes. This class allows you to query information about container nodes in the Maya scene.
Constructor.
Class constructor that initializes the function set to the given MObject.
Constructor.
Class constructor that initializes the function set to the given MObject.
Function set type.
Return the class type : MFn::kContainer
Reimplemented from MFnDependencyNode.
Class name.
Return the class name : "MFnContainerNode"
Reimplemented from MFnDependencyNode.
Return two arrays: the first contains the plugs that have been published on this container. The second contains that published names for those plugs. There is a one-to-one correspondence between the plugs in the first array and the strings in the second.
Return an array of the nodes included in this container.
Return an array of the container nodes included in this container.
Return the parent container, if there is one. Otherwise return an empty MObject | https://download.autodesk.com/us/maya/2009help/API/class_m_fn_container_node.html | CC-MAIN-2022-33 | refinedweb | 176 | 51.34 |
13. Yellow LED(EF05012)
13.1. Introduction
Yellow LED is usually used as the indicator.
13.2. Characteristic
Designed in RJ11 connections, easy to plug.
13.3. Specification
13.4. Outlook
13.5. Quick to Start
13.5.1. Materials Required and Diagram
Connect the Yellow LED to J1 port and the potentiaometer to J2 port in the Nezha expansion board as the picture shows.
13.6. MakeCode Programming
13.
13.6.2. Step 2
13.6.3. Code as below:
13.6.4. Link
Link:
You may also download it directly below:
13.6.5. Result
The brightness is adjusted by the potentiometer.
13.7. Python Programming
13.7.1. Step 1
Download the package and unzip it: PlanetX_MicroPython
Go to Python editor
We need to add enum.py and led.py for programming. Click “Load/Save” and then click “Show Files (1)” to see more choices, click “Add file” to add enum.py and led.py from the unzipped package of PlanetX_MicroPython.
13.7.2. Step 2
13.7.3. Reference
from microbit import * from enum import * from led import * led = LED(J1) while True: led.set_led(1,100) sleep(1000) led.set_led(1,50) sleep(1000) led.set_led(0,50) sleep(1000)
13.7.4. Result
LED lights on in 100% brightness for one second and 50% brightness for another sencond and lights off for one second after powering on and it continues working in this way. | https://www.elecfreaks.com/learn-en/microbitplanetX/Plant_X_EF05012.html | CC-MAIN-2022-27 | refinedweb | 240 | 71.31 |
I am writing a c script to parallelize pi approximation with OpenMp. I think my code works fine with a convincing output. I am running it with 4 threads now. What I am not sure is that if this code is vulnerable to race condition? and if it is, how do I coordinate the thread action in this code ?
the code looks as follows:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <omp.h>
double sample_interval(double a, double b) {
double x = ((double) rand())/((double) RAND_MAX);
return (b-a)*x + a;
}
int main (int argc, char **argv) {
int N = atoi( argv[1] ); // convert command-line input to N = number of points
int i;
int NumThreads = 4;
const double pi = 3.141592653589793;
double x, y, z;
double counter = 0;
#pragma omp parallel firstprivate(x, y, z, i) reduction(+:counter) num_threads(NumThreads)
{
srand(time(NULL));
for (int i=0; i < N; ++i)
{
x = sample_interval(-1.,1.);
y = sample_interval(-1.,1.);
z = ((x*x)+(y*y));
if (z<= 1)
{
counter++;
}
}
}
double approx_pi = 4.0 * counter/ (double)N;
printf("%i %1.6e %1.6e\n ", N, 4.0 * counter/ (double)N, fabs(4.0 * counter/ (double)N - pi) / pi);
return 0;
}
10 3.600000e+00 1.459156e-01
100 3.160000e+00 5.859240e-03
1000 3.108000e+00 1.069287e-02
10000 3.142400e+00 2.569863e-04
100000 3.144120e+00 8.044793e-04
1000000 3.142628e+00 3.295610e-04
10000000 3.141379e+00 6.794439e-05
100000000 3.141467e+00 3.994585e-05
1000000000 3.141686e+00 2.971945e-05
There are a few problems in your code that I can see. The main one is from my standpoint that it isn't parallelized. Or more precisely, you didn't enable the parallelism you introduced with OpenMP while compiling it. Here is the way one can see that:
The way the code is parallelized, the main
for loop should be executed in full by all the threads (there is no worksharing here, no
#pragma omp parallel for, only a
#pragma omp parallel). Therefore, considering you set the number of threads to be 4, the global number of iterations should be
4*N. Thus, your output should slowly converge towards 4*Pi, not towards Pi.
Indeed, I tried your code on my laptop, compiled it with OpenMP support, and that is pretty-much what I get. However, when I don't enable OpenMP, I get an output similar to yours. So in conclusion, you need to:
NumThreadsto get a "valid" approximation of Pi (or distribute your loop over
Nwith a
#pragma omp forfor example)
But that is if / when your code is correct elsewhere, which it isn't yet.
As BitTickler already hinted,
rand() isn't thread-safe. So you have to go for another random number generator, which will allow you to privatize it's state. That could be
rand_r() for example. That said, this still has quite a few issues:
rand()/
rand_r()is a terrible RNG in term of randomness and periodicity. While increasing your number of tries, you'll rapidly go over the period of the RNG and repeat over and over again the same sequence. You need something more robust to do anything remotely serious.
Anyway, bottom line is:
drand48_r()or
random_r()to be OK for toy codes on Linux)
This done (along with a few minor fixes), your code becomes for example as follows:
#include <stdlib.h> #include <stdio.h> #include <time.h> #include <math.h> #include <omp.h> typedef struct drand48_data RNGstate; double sample_interval(double a, double b, RNGstate *state) { double x; drand48_r(state, &x); return (b-a)*x + a; } int main (int argc, char **argv) { int N = atoi( argv[1] ); // convert command-line input to N = number of points int NumThreads = 4; const double pi = 3.141592653589793; double x, y, z; double counter = 0; time_t ctime = time(NULL); #pragma omp parallel private(x, y, z) reduction(+:counter) num_threads(NumThreads) { RNGstate state; srand48_r(ctime+omp_get_thread_num(), &state); for (int i=0; i < N; ++i) { x = sample_interval(-1, 1, &state); y = sample_interval(-1, 1, &state); z = ((x*x)+(y*y)); if (z<= 1) { counter++; } } } double approx_pi = 4.0 * counter / (NumThreads * N); printf("%i %1.6e %1.6e\n ", N, approx_pi, fabs(approx_pi - pi) / pi); return 0; }
Which I compile like this:
gcc -std=gnu99 -fopenmp -O3 -Wall pi.c -o pi_omp | https://codedump.io/share/wmFUnHNREakF/1/parallelization-for-monte-carlo-pi-approximation | CC-MAIN-2017-09 | refinedweb | 729 | 76.01 |
NAME
DSA_set_default_method, DSA_get_default_method, DSA_set_method, DSA_new_method, DSA_OpenSSL - select DSA method
SYNOPSIS
#include <openssl/dsa);
DESCRIPTION
A DSA_METHOD specifies the functions that OpenSSL uses for DSA operations. By modifying the method, alternative implementations such as hardware accelerators may be used. IMPORTANT:. This function is not thread-safe and should not be called at the same time as other OpenSSL functions.
DSA_get_default_method() returns a pointer to the current default DSA_METHOD. However, the meaningfulness of this result is dependent. See DSA_meth_new for information on constructing custom DSA_METHOD objects;.
RETURN VALUES
DSA_OpenSSL() and DSA_get_default_method() return pointers to the respective DSA_METHODs.
DSA_set_default_method() returns no value. structure.
SEE ALSO
DSA_new(3), DSA_new(3), DSA_meth_new(3)
Licensed under the Apache License 2.0 (the "License"). You may not use this file except in compliance with the License. You can obtain a copy in the file LICENSE in the source distribution or at. | https://www.openssl.org/docs/manmaster/man3/DSA_get_default_method.html | CC-MAIN-2018-51 | refinedweb | 144 | 59.8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.