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 |
|---|---|---|---|---|---|
#include <canna/RK.h> int RkMapRoma(romaji, dst, maxdst, src, srclen, flags, status) struct RkRxDic *romaji; unsigned char *dst; int maxdst; unsigned char *src; int srclen; int flags; int *status;
flags is a combination of the following Romaji-kana conversion flags connected by or:
The flags listed below specify the type of characters stored in src. These specified code conversion to be performed on the character string derived from the Romaji-kana conversion table. These flags can use one by one.
status is set to the byte length of the character string set in the area dst. A negative value means that there is no matching Romaji character string. | http://www.makelinux.net/man/3/R/RkMapRoma | CC-MAIN-2015-40 | refinedweb | 109 | 58.82 |
mustache4dart2 0.1.0
Mustache.
Partials #]')); #.
Developing #
CHANGELOG #
2.1.1 (2018-04-14) #
2.1.0 (2017-06-21) #
2.0.0 (2017-06-13) #
As part of the MustacheContext rework, a couple of simplifications have been made. Most
notable one is the drop support of mirroring methods starting with
get as it does not make any
sense with dart. Use a getter instead.
1.1.0 (2017-05-10) #
1.0.12 (2017-03-17) #
- Maintenance release
1.0.11 (2017-03-02) #
- Fixed issue with default value of boolean arguments
- Compile method now returns type annotation issue
1.0.10 (2015-03-15) #
1.0.9 (2015-02-13) #
- throw exception on missing property (helps debugging and tracking down errors) issue
- introduced assumeNullNonExistingProperty (the difference between a null field and a non-existent field) issue
- Provide lambdas with the current nested context when they have two parameters (lambdas can now render their contents when inside of a loop) issue
1.0.8 (2015-02-01) #
Use this package as a library
1. Depend on it
Add this to your package's pubspec.yaml file:
dependencies: mustache4dart2: ^0.1.0
2. Install it
You can install packages from the command line:
with pub:
$ pub get
Alternatively, your editor might support
pub get.
Check the docs for your editor to learn more.
3. Import it
Now in your Dart code, you can use:
import 'package:mustache4dart2/mustache4dart2.dart';
We analyzed this package on Jan 16, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using:
- Dart: 2.7.0
- pana: 0.13.4
Health suggestions
Fix
lib/src/tokens.dart. (-16.09 points)
Analysis of
lib/src/tokens.dart reported 35 hints, including:
line 3 col 1: Prefer using /// for doc comments.
line 21 col 14: Unnecessary new keyword.
line 24 col 14: Unnecessary new keyword.
line 31 col 14: Unnecessary new keyword.
line 33 col 14: Unnecessary new keyword.
Fix
lib/src/tmpl.dart. (-10.89 points)
Analysis of
lib/src/tmpl.dart reported 23 hints, including:
line 9 col 13: Unnecessary new keyword.
line 11 col 25: Unnecessary new keyword.
line 44 col 12: Unnecessary new keyword.
line 72 col 8: Don't explicitly initialize variables to null.
line 72 col 22: Use
= to separate a named parameter from its default value.
Fix
lib/src/mirrors.dart. (-7.24 points)
Analysis of
lib/src/mirrors.dart reported 15 hints, including:
line 3 col 21: Avoid const keyword.
line 5 col 39: Use
= to separate a named parameter from its default value.
line 7 col 12: Unnecessary new keyword.
line 10 col 12: Unnecessary new keyword.
line 14 col 10: Unnecessary new keyword.
Fix
lib/mustache_context.dart. (-4.89 points)
Analysis of
lib/mustache_context.dart reported 10 hints, including:
line 15 col 61: Use
= to separate a named parameter from its default value.
line 37 col 12: Unnecessary new keyword.
line 44 col 10: Unnecessary new keyword.
line 49 col 23: Unnecessary new keyword.
line 58 col 8: Don't type annotate initializing formals.
Fix
lib/src/mustache.dart. (-2.96 points)
Analysis of
lib/src/mustache.dart reported 6 hints, including:
line 6 col 17: Use
= to separate a named parameter from its default value.
line 8 col 32: Use
= to separate a named parameter from its default value.
line 9 col 39: Use
= to separate a named parameter from its default value.
line 18 col 57: Use
= to separate a named parameter from its default value.
line 20 col 17: Unnecessary new keyword.
Maintenance suggestions
The package description is too short. (-7
mustache4dart2.dart. Packages with multiple examples should provide
example/README.md.
For more information see the pub package layout conventions. | https://pub.dev/packages/mustache4dart2 | CC-MAIN-2020-05 | refinedweb | 622 | 61.43 |
Conversion to text format with character strings. More...
#include <char_strings.hpp>
Conversion to text format with character strings.
This class uses a character buffer for the character strings that it generates. If your buffer is not long enough, this will just truncate the output to fit the buffer.
Definition at line 644 of file char_strings.hpp.
Initialises with an external buffer.
Definition at line 656 of file char_strings.hpp.
Initialises with an internal buffer.
Definition at line 669 of file char_strings.hpp.
Reimplemented in ecl::Converter< char *, void >.
Definition at line 678 of file char_strings.hpp.
Convert the specified double to int.
Converts an double to a char string held in the converter's buffer. I'd like to one day have my own (perhaps faster?) or refined implementation of snprintf but it will do for now.
Definition at line 694 of file char_strings.hpp.
Definition at line 720 of file char_strings.hpp. | http://docs.ros.org/en/noetic/api/ecl_converters/html/classecl_1_1Converter_3_01char_01_5_00_01float_01_4.html | CC-MAIN-2021-49 | refinedweb | 153 | 62.95 |
Pure Python CBOR (de)serializer with extensive tag support
Project description
This library provides encoding and decoding for the Concise Binary Object Representation (CBOR) (RFC 7049) serialization format.
Usage
from cbor2 import * #)
String/bytes handling on Python 2
The str type is encoded as binary on Python 2. If you want to encode strings as text on Python 2, use unicode strings instead.
Date/time handling
CBOR does not support naïve datetimes (that is, datetimes where tzinfo is missing). When the encoder encounters such a datetime, it needs to know which timezone it belongs to. To this end, you can specify a default timezone by passing a datetime.
Cyclic (recursive) data structures
By default, both the encoder and decoder support cyclic data structures (ie. containers that contain references to themselves). When serializing, this requires some extra space in the data stream. If you know you won’t have cyclic structures in your data, you can save a little bit of space by turning off the value sharing feature by passing the value_sharing=False option to dump()/dumps().
Customizing encoding/decoding
The encoder allows you to specify a mapping of types to callables that handle the encoding of some otherwise unsupported type. The decoder, on the other hand, allows you to specify a mapping of semantic tag numbers to callables that implement custom transformation logic for tagged values.
Custom encoder and decoder hooks can also be made to support value sharing. For encoder hooks, wrapping them with @cbor2.shareable_encoder is enough. Decoder hooks are slightly more complex. In order to support cyclic references, the decoder must construct a “raw” instance of the target class (usually using __new__()) and then separately decoding and applying the object’s state.
See the docstrings of cbor2.CBOREncoder, cbor2.CBORDecoder and @cbor2.shareable_encoder for details.
Tag support
In addition to all standard CBOR tags, this library supports many extended tags:
Project links
Project details
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/cbor2/3.0.1/ | CC-MAIN-2018-47 | refinedweb | 343 | 56.25 |
Python is a beautiful language. Simple to use yet powerfully expressive. But are you using everything that it has to offer?
Originally published by George Seif at Towardsdatascience
The advanced features of any programming language are usually discovered through extensive experience. You’re coding up a complicated project and find yourself searching for something on stackoverflow.:
x = lambda a, b : a * b print(x(5, 6)) # prints '30'
x = lambda a : a*3 + 3 print(x(3)) # prints '12'
See how easy that was! We performed a bit of basic math without the need for defining a full on function. This is one of the many features of Python that makes it a clean and simplistic programming language to use.
Map() is a built-in Python function used to apply a function to a sequence of elements like a list or dictionary. It’s a very clean and most importantly readable way to perform such an operation.
def square_it_func(a):
return a * a
x = map(square_it_func, [1, 4, 7]) print(x) # prints '[1, 16, 47]' def multiplier_func(a, b): return a * b x = map(multiplier_func, [1, 4, 7], [2, 5, 8]) print(x) # prints '[2, 20, 56]'
Check out the example above! We can apply our function to a single list or multiple lists. In face, you can use a map with any python function you can think of, as long as it’s compatible with the sequence elements you are operating on.
The Filter built-in function is quite similar to the Map function in that it applies a function to a sequence (list, tuple, dictionary). The key difference is that filter() will only return the elements which the applied function returned as True.
# Our numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
# Function that filters out all numbers which are odd def filter_odd_numbers(num): if num % 2 == 0: return True else: return False filtered_numbers = filter(filter_odd_numbers, numbers) print(filtered_numbers) # filtered_numbers = [2, 4, 6, 8, 10, 12, 14]
Not only did we evaluate True or False for each list element, the filter()function also made sure to only return the elements which matched as True. Very convenient for handling to two steps of checking an expression and building a return list.!
from itertools import *
# Easy joining of two lists into a list of tuples for i in izip([1, 2, 3], ['a', 'b', 'c']): print i # ('a', 1) # ('b', 2) # ('c', 3) # The count() function returns an interator that # produces consecutive integers, forever. This # one is great for adding indices next to your list # elements for readability and convenience for i in izip(count(1), ['Bob', 'Emily', 'Joe']): print i # (1, 'Bob') # (2, 'Emily') # (3, 'Joe') # The dropwhile() function returns an iterator that returns # all the elements of the input which come after a certain # condition becomes false for the first time. def check_for_drop(x): print 'Checking: ', x return (x > 5) for i in dropwhile(should_drop, [2, 4, 6, 8, 10, 12]): print 'Result: ', i # Checking: 2 # Checking: 4 # Result: 6 # Result: 8 # Result: 10 # Result: 12 # The groupby() function is great for retrieving bunches # of iterator elements which are the same or have similar # properties a = sorted([1, 2, 1, 3, 2, 1, 2, 3, 4, 5]) for key, value in groupby(a): print(key, value), end=' ') # (1, [1, 1, 1]) # (2, [2, 2, 2]) # (3, [3, 3]) # (4, [4]) # (5, [5]).
# (1) Using a for loop
numbers = list()
for i in range(1000): numbers.append(i+1) total = sum(numbers) # (2) Using a generator def generate_numbers(n): num, numbers = 1, [] while num < n: numbers.append(num) num += 1 return numbers total = sum(generate_numbers(1000)) # (3) range() vs xrange() total = sum(range(1000 + 1)) total = sum(xrange(1000 + 1))
Follow me on twitter where I post all about the latest and greatest AI, Technology, and Science! Connect with me on LinkedIn too!
-------------------------------------------------- | https://morioh.com/p/7b4e75f49f44 | CC-MAIN-2020-05 | refinedweb | 653 | 54.05 |
You might come across a scenarios where you received a UI where the buttons are rounded, and you might wonder how to do that? So here we will see how to make corners of a button round.
We will be seeing both the ways to make the button rounded, one using Storyboard and another programmatically.
Let’s get started! First we will make the corners of button rounded using Storyboard.
Step 1 − Open Xcode → New Projecr → Single View Application → Let’s name it “RoundedButton”
Step 2 − Open Main.storyboard and add a button as show below
Step 3 − Now select the button and tap on Utility area and update the User Defined Runtime Attributes to below value.
Now this value you can modify i.e increase or decrease based on requirement.
In the second method we are going to make the corner rounded Programmatically.
From the Main.storyboard get the @IBOutlet in ViewController.swift and name it “doButtonRounded” and update the same property layer.cornerRadius.
Use the below code for complete reference.
import UIKit class ViewController: UIViewController { @IBOutlet var doButtonRounded: UIButton! override func viewDidLoad() { super.viewDidLoad() doButtonRounded.layer.cornerRadius = 20 } } | https://www.tutorialspoint.com/how-to-make-the-corners-of-a-button-round-in-ios | CC-MAIN-2019-35 | refinedweb | 190 | 60.01 |
When developing applications for the .NET Framework, you’ll most likely use an IDE like Visual Studio, Visual Studio Express, SharpDevelop or MonoDevelop. These tools make it easy to write code and really boost productivity. But you should know that you could write code without any of these tools.
First, let’s download the latest version of .NET from Microsoft’s website if you don’t have it yet. Latest version is Microsoft .NET 4. The installation is simple.
When you install the .NET Framework runtime, the Software Development Kit (SDK) comes included. If you look in the directory C:\WINDOWS\Microsoft.NET\Framework\v<version number>, you’ll find the following programs:
- csc.exe – C# compiler
- vbc.exe – VB.NET compiler
- aspnet_compiler.exe – ASP.NET compilation tool
A compiler and your favorite text editor is all you need to start writing apps for the .NET Framework. With several of the IDE’s I mentioned before being free, there’s really no reason for you to write code “by hand” in a text editor. Still, it’s a good exercise to understand what your IDE is doing in the backend.
Write Your First Program
We’re going to write a little hello program and compile it with the .NET SDK. Open you favorite text editor and type the following code. We’ll use C# for this sample.
// Include the System namespace using System; // This class will contain the entry point of the program class MyFirstApp { // This is the entry point of the program public static void Main() { // Write something Console.WriteLine("Hello World!"); } }
That’s it. Save the file somewhere in your computer as MyFirstApp.cs. I saved mine to C:\Blog\Code\NET\MyFirstApp\MyFirstApp.cs.
Breaking Down the Code
We start the program importing the classes that we’ll use in the program. The using keyword specifies the namespace containing the classes that we wish to import. We can import as many namespaces as we need. We’ll discuss namespaces in another post.
Next we define a class. C# is object oriented, and classes are the core of object-oriented programming. All code in C# needs to be contained in methods, and methods need to belong to a class.
Now we define the entry point of the program. The compiler expects a method called Main and marked with public and static.
Next line just writes a string to the console. We invoke the WriteLine method from the Console class.
Compile and Run the Program
So we’re ready to compile our code into an executable file for Windows. Open a command prompt (Start –> All Programs–> Accessories –> Command Prompt) and navigate to C:\Windows\Microsoft.NET\Framework\v<version number> folder. I’ll use .NET 4 here.
Now we just need to call the compiler and feed it with the target file we want to create (MyFirstApp.exe) and the file with out source code. The compiler doesn’t give any feedback if the operation was successful, other than the copyright information of the compiler. If there was a problem, we’ll receive information about the error.
Now all we need to do is navigate to the target path and execute our little app. You can also open the folder and double-click on the file.
And there it is, our message on the console. Please leave a comment if you had any issue or if you have any question. | http://blog.oscarscode.com/dot-net/introduction-to-net-framework-sdk/ | CC-MAIN-2019-09 | refinedweb | 571 | 68.36 |
Details
- Type:
New Feature
- Status: Open
- Priority:
Major
- Resolution: Unresolved
- Affects Version/s: None
- Fix Version/s: None
- Component/s: None
- Labels:None
- Environment:
Ubuntu 9.10 64bit
- Skill Level:Committers Level (Medium to Hard)
Description
It would be nice if CouchDB had a comprehensive offering for varying levels of access to documents and databases.
Here are some ideas:
o User lists are stored in the database, per database.
o Roles and role membership are stored in the database, per database.
o ACLs are stored in the database, per database.
o CouchDB can use ACLs to store and simplify permissions for internal functionality (manage the db, manage users, add roles, add users to roles, etc...)
o CouchApps can take advantage of the ACLs to support login/logout and arbitrary business rules as needed.
o A simple API can be made to conduct role, ACL and ownership checks.
I suppose there is some theory and discussion behind determining whether users, roles or both are stored in ACL rules. Also, something worth discussing is whether the checks are automatically performed by couchdb, or if views are to be performing checks prior to emitting data. Or both...
Building all this into CouchDB would mean that it has a mechanism for complex applications to be developed. Ones that mandate privacy and other visibility concerns.
Activity
- All
- Work Log
- History
- Activity
- Transitions
I'd like to see authorization based replication - i.e. only being able to replicate parts of the database for which the user is authorized.
We already have this, in the sense that replication uses the normal HTTP API. So if a user is not and admin, they will not be able to replicate _design documents to the target.
Similarly, if the target has a validation function that says all docs must have a foo field, than any docs that are missing a foo field will not be replicated.
Because CouchDB has not read-authorization model, there isn't the same thing for reads. When we add the ability to control read-access to databases, users will only be able to replicate from databases they can read.
The first part of this note is an aside which could be separated out into another discussion or issue if desired...
It's important not to conflate the functionality of reading the DB from an application point of view (JSON request coming from a browser) and reading the DB as a function of infrastructure (a scheduled replication).
I should note that I see the use in allowing replications to happen in the context of a user per database, but not per server. This allows for local copies of DB for higher availability, but they are only populated with data the user can see.
Ultimately, replications and DBs will have to function in different contexts. Control over what replications a server performs is still a system-wide administrative task to be done with absolute authority.
Example:
1. is running couchdb.
2. I make a user there.
3. I start to populate my CD collection and share information with others.\
4. I'm going on a plane and want my CD collection list with me.
5. I install CouchDB on my favorite OS via my favorite means.
6. As I am an administrator on my laptop, I elect to replicate.
7. requires that I authenticate so that it can filter my replication.
I think you can see how incredibly neat that ends up being...Of course then some people will want ways to obfuscate the _design docs... But that's getting into the nitty gritties.
Replication should function with indifference towards the DBs, users and CouchApps being replicated and have little to nothing to do with them. It should function behind the scenes as part of a broader, more general systems design.
That's why things like per-DB roles and users may be nessecary to prevent the server and the databases from bleeding into each other.
To me, replication is not something my users should even have to know about. You write one app and if you need to scale out, you simply set up replication.
=
Anyway...
This issue that I have made here is over the permissions of authenticated users of the DB and what data they can and cannot read:
Right now, there is no way to secure a request to on CouchDB without involving cumbersome workarounds. I am loathe to think of the impact on the project if this is not addressed.
See also
0. Summary
Convention + Filtered views + intersections = access control.
Start with a standardised-by-convention honour-system access control scheme, which can be
implemented client-side as an honour system, or enforced by a proxy. Add a system view
which gives the sd for each document.
Add filtered views to (COUCHDB-707) provide server-side support. Then add intersections
(joins) with other filtered views so access control information is indexed.
Finally add ability to optionally apply access control filters transparently to all views.
1. Honour System access control.
Extend the _security document to name additional groups than admin and member.
Specifically add "reader" (implicit read of all non-system documents) and "restricted"
(no implicit access), and allow adding any number of arbitrary groups.
Extend the userCtx to contain the property "principals" being a list of DB groups the user is in.
The user and the roles generate the list of principals at request time. Therefore only principals
need to be consulted for
access control.
e.g. the{ "db":"mailbox", "name":"bob", "roles":[ "cartographers" ], "principals":[ "user:bob", "role:cartographers", "group:project X Admins" "db:non-admin", "db:restricted" ] }
Each document can have a new system property, _sd. This can be consulted to discover desired access.
An absent _sd means anyone may access. An empty _sd means only admins. Otherwise as described by the sd.
Levels are read-only, and full access (including delete).
_sd:{ "user:bob":"rw", "role:cartographers":"r", "group:project X Admins":"rw" }
We now have a client-side honour system access control.
2. Allow filter functions to be used for views and for document reads.
This would allow users to specify a filter function which implemented
access control to see only parts of the view they wish to see.
The filter function would be applied before the reduce step. Queries without
a filter function would proceed as at present. Queries with a filter function
will
On the honour system, this would be slow for views because it requires
reading the document to retrieve the sd, unless the sd were output in the value.
Need to ensure multiple filter functions can be used together.
3. Allow intersection queries when querying views. (Yes, a bit like a join.)
Specify multiple views (potentially each with their own filter).
The output of the first view is the only one returned, but it is filtered by only accepting the document IDs
which are produced by the other views.
4. Create a new system view _doc_sd which emits an entry for each document _sd entry.
If the _sd is empty, it will emit the implicit equivalents
"documentID","db:readers","r"
5. Now we can (if configured) implement access control by implicitly querying _doc_sd
for intersection with the usrCtx.groups as keys.
6. Write access control can, as now, be implemented by the validation function.
7. Protection of namespaces from pollution by downlevel users can be provided by
validation functions. These would consult a _namespace_sd document which would contain
prefix to _sd mappings.
The current update authorization model is very solid, and probably won't be changing.
There are some good ideas in the ticket regarding read authorization.
Our big missing piece is per-database reader ACLs. It's not clear if these should be stored in local docs (non-replicating) or normal docs (so they replicate.)
My guess is that we want them to replicate, as many app installations will span nodes.
We probably want them in a document that only admins can edit, and I don't think we want the ACLs in _design documents. So maybe we need a new type of document. How does _security/foo sound?
Currently the db_admins role list is checked against the userCtx roles as well as username. Which means we are dealing with a flat namespace. I've got some notes about the account branch that deal with this stuff that I'll be post soon as well. | https://issues.apache.org/jira/browse/COUCHDB-615?focusedCommentId=12797609&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel | CC-MAIN-2015-48 | refinedweb | 1,401 | 64.71 |
Cookies vs. Tokens: The Definitive Guide
Cookies vs. Tokens: The Definitive Guide
Cookies or tokens? That is the question.
Join the DZone community and get the full member experience.Join For Free
We will be writing an Angular 2 app that uses JWT for authentication. Grab the Github repo if you would like to follow along.
Our last article comparing cookie to token authentication was over two years ago. Since then, we've written extensively on how to integrate token authentication across many different languages and frameworks.
The rise of single page applications (SPAs) and decoupling of the front-end from the back-end is in full force. Frameworks like Angular, React, and Vue allow developers to build bigger, better, and more performant single page applications than ever before. Token-based authentication goes hand in hand with these frameworks.
"Token-based authentication goes hand in hand with SPA frameworks like Angular, React and Vue."
TWEET THIS
Cookie vs. Token Authentication - Recap
Before we dive further, let's quickly recap how these two authentication systems work. If you are already familiar with how cookie and token authentication works, feel free to skip this section, otherwise read on for an in-depth overview.
This diagram is a great introduction and simplified overview of the difference between cookie and token approaches to authentication.
Cookie-Based Authentication
Cookie-based authentication has been the default, tried-and-true method for handling user authentication for a long time.
Cookie-based authentication is stateful. This means that an authentication record or session must be kept both server and client-side. The server needs to keep track of active sessions in a database, while on the front-end a cookie is created that holds a session identifier, thus the name cookie based authentication. Let's look at the flow of traditional cookie-based authentication:
- User enters their login credentials.
- Server verifies the credentials are correct and creates a session which is then stored in a database.
- A cookie with the session ID is placed in the users browser.
- On subsequent requests, the session ID is verified against the database and if valid the request processed.
- Once a user logs out of the app, the session is destroyed both client-side and server-side.
Token-Based Authentication
Token-based authentication has gained prevalence over the last few years due to the rise of single page applications, web APIs, and the Internet of Things (IoT). When we talk about authentication with tokens, we generally talk about authentication with JSON Web Tokens (JWTs). While there are different ways to implement tokens, JWTs have become the de-facto standard. With this context in mind, the rest of the article will use tokens and JWTs interchangeably.
Token-based authentication is stateless. The server does not keep a record of which users are logged in or which JWTs have been issued. Instead, every request to the server is accompanied by a token which the server uses to verify the authenticity of the request. The token is generally sent as an addition Authorization header in the form of
Bearer {JWT}, but can additionally be sent in the body of a POST request or even as a query parameter. Let's see how this flow works:
- User enters their login credentials.
- Server verifies the credentials are correct and returns a signed token.
- This token is stored client-side, most commonly in local storage - but can be stored in session storage or a cookie as well.
- Subsequent requests to the server include this token as an additional Authorization header or through one of the other methods mentioned above.
- The server decodes the JWT and if the token is valid processes the request.
- Once a user logs out, the token is destroyed client-side, no interaction with the server is necessary.
Advantages of Token-Based Authentication
Understanding how something works is only half the battle. Next, we'll cover the reasons why token authentication is preferable over the traditional cookie-based approach.
Stateless, Scalable, and Decoupled
Perhaps the biggest advantage to using tokens over cookies is the fact that token authentication is stateless. The back-end does not need to keep a record of tokens. Each token is self-contained, containing all the data required to check it's.
Cross Domain and CORS
Cookies work well with singular domains and sub-domains, but when it comes to managing cookies across different domains, it can get hairy. In contrast, a token-based approach with CORS enabled makes it trivial to expose APIs to different services and domains. Since the JWT is required and checked with each and every call to the back-end, as long as there is a valid token, requests can be processed. There are a few caveats to this and we'll address those in the Common Questions and Concerns section below.
Store Data in the JWT
With a cookie based approach, you simply store the session id in a cookie. JWT's, on the other hand, allow you to store any type of metadata, as long as it's valid JSON. The JWT spec specifies different types of claims that can be included such as reserved, public and private. You can learn more about the specifics and the differences between the types of claims on the jwt.io website.
In practice, what this means is that a JWT can contain any type of data. Depending on your use case you may choose to make the minimal amount of claims such as the user id and expiration of the token, or you may decide to include additional claims such as the user's email address, who issued the token, scopes or permissions for the user, and more.
Performance
When using the cookie-based authentication, the back-end has to do a lookup, whether that be a traditional SQL database or a NoSQL alternative, and the round trip is likely to take longer compared to decoding a token. Additionally, since you can store additional data inside the JWT, such as the user's permission level, you can save yourself additional lookup calls to get and process the requested data.
For example, say you had an API resource
/api/orders that retrieves the latest orders placed via your app, but only users with the role of admin have access to view this data. In a cookie based approach, once the request is made, you'd have one call to the database to verify that the session is valid, another to get the user data and verify that the user has the role of admin, and finally a third call to get the data. On the other hand, with a JWT approach, you can store the user role in the JWT, so once the request is made and the JWT verified, you can make a single call to the database to retrieve the orders.
Mobile Ready
Modern APIs do not only interact with the browser. Written properly a single API can serve both the browser and native mobile platforms like iOS and Android. Native mobile platforms and cookies do not mix well. While possible, there are many limitations and considerations to using cookies with mobile platforms. Tokens, on the other hand, are much easier to implement on both iOS and Android. Tokens are also easier to implement for Internet of Things applications and services that do not have a concept of a cookie store.
Common Questions and Concerns
In this section, we'll take a look at some common questions and concerns that frequently arise when the topic of token authentication comes up. The key focus here will be security but we'll examine use cases concerning token size, storage and encryption.
JWT Size
The biggest disadvantage of token authentication is the size of JWTs. A session cookie is relatively tiny compared to even the smallest JWT. Depending on your use case, the size of the token could become problematic if you add many claims to it. Remember, each request to the server must include the JWT along with it.
Where to Store Tokens?
With token-based auth, you are given the choice of where to store the JWT. Commonly, the JWT is placed in the browser's local storage and this works well for most use cases. There are some issues with storing JWTs in local storage to be aware of. Unlike cookies, local storage is sandboxed to a specific domain and its data cannot be accessed by any other domain including sub-domains.
You can store the token in a cookie instead, but the max size of a cookie is only 4kb so that may be problematic if you have many claims attached to the token. Additionally, you can store the token in session storage which is similar to local storage but is cleared as soon as the user closes the browser.
XSS and XSRF Protection
Protecting your users and servers is always a top priority. One of the most common concerns developers have when deciding on whether to use token-based authentication is the security implications. Two of the most common attack vectors facing websites are Cross Site Scripting (XSS) and Cross-Site Request Forgery (XSRF or CSRF).
Cross Site Scripting) attacks occur when an outside entity is able to execute code within your website or app. The most common attack vector here is if your website allows inputs that are not properly sanitized. If an attacker can execute code on your domain, your JWT tokens are vulnerable. Our CTO has argued in the past that XSS attacks are much easier to deal with compared to XSRF attacks because they are generally better understood. Many frameworks, including Angular, automatically sanitize inputs and prevent arbitrary code execution. If you are not using a framework that sanitizes input/output out-of-the-box, you can look at plugins like caja developed by Google to assist. Sanitizing inputs is a solved issue in many frameworks and languages and I would recommend using a framework or plugin vs building your own.
Cross Site Request Forgery attacks are not an issue if you are using JWT with local storage. On the other hand, if your use case requires you to store the JWT in a cookie, you will need to protect against XSRF. XSRF are not as easily understood as XSS attacks. Explaining how XSRF attacks work can be time-consuming, so instead, check out this really good guide that explains in-depth how XSRF attacks work. Luckily, preventing XSRF attacks is a fairly simple matter. To over-simplify, protecting against an XSRF attack, your server, upon establishing a session with a client will generate a unique token (note this is not a JWT). Then, anytime data is submitted to your server, a hidden input field will contain this token and the server will check to make sure the tokens match. Again, as our recommendation is to store the JWT in local storage, you probably will not have to worry about XSRF attacks.
One of the best ways to protect your users and servers is to have a short expiration time for tokens. That way, even if a token is compromised, it will quickly become useless. Additionally, you may maintain a blacklist of compromised tokens and not allow those tokens access to the system. Finally, the nuclear approach would be to change the signing algorithm, which would invalidate all active tokens and require all of your users to log in again. This approach is not easily recommended, but is available in the event of a severe breach.
Tokens Are Signed, Not Encrypted
A JSON Web Token is comprised of three parts: the header, payload, and signature. The format of a JWT is
header.payload.signature. If we were to sign a JWT with the HMACSHA256 algorithm, the secret 'shhhh' and the payload of:
{ "sub": "1234567890", "name": "Ado Kukic", "admin": true }
The JWT generated would be:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFkbyBLdWtpYyIsImFkbWluIjp0cnVlLCJpYXQiOjE0NjQyOTc4ODV9.Y47kJvnHzU9qeJIN48_bVna6O0EDFiMiQ9LpNVDFymM
The very important thing to note here is that this token is signed by the HMACSHA256 algorithm, and the header and payload are Base64URL encoded, it is not encrypted. If I go to jwt.io, paste this token and select the HMACSHA256 algorithm, I could decode the token and read its contents. Therefore, it should go without saying that sensitive data, such as passwords, should never be stored in the payload.
If you must store sensitive data in the payload or your use case calls for the JWT to be obscured, you can use JSON Web Encryption (JWE). JWE allows you to encrypt the contents of a JWT so that it is not readable by anyone but the server. JOSE provides a great framework and different options for JWE and has SDKs for many popular frameworks including NodeJS and Java.
Token-Based Authentication in Action with Auth0
Here at Auth0, we've written SDKs, guides, and quickstarts for working with JWTs for many languages and frameworks including NodeJS, Java, Python, GoLang, and many more. Our last "Cookies vs. Tokens" article used the AngularJS framework, so it's fitting to use Angular 2 for our code samples today.
You can download the sample code from our GitHub repo. Downloading the code samples is preferable as Angular 2 requires a lot of initial setup to get going. If you haven't already, sign up for a free Auth0 account so you can do the implementation yourself and experiment with different features and options. Let's get started.
Setting Up the Back-end Server
We'll first set up our server. We'll build our server with NodeJS. The server will expose two APIs:
/ping and
/secured/ping. The first will be publicly available any anyone can access it, while the second requires you to be authenticated to call it. The implementation is below:
// Include the modules needed for our server. var http = require('http'); var express = require('express'); var cors = require('cors'); var app = express(); var jwt = require('express-jwt'); // Set up our JWT authentication middleware // Be sure to replace the YOUR_AUTH0_CLIENT_SECRET and // YOUR_AUTHO_CLIENT_ID with your apps credentials which // can be found in your management dashboard at // var authenticate = jwt({ secret: new Buffer('YOUR_AUTH0_CLIENT_SECRET', 'base64'), audience: 'YOUR_AUTH0_CLIENT_ID' }); app.use(cors()); // Here we have a public route that anyone can access app.get('/ping', function(req, res) { res.send(200, {text: "All good. You don't need to be authenticated to call this"}); }); // We include the authenticate middleware here that will check for // a JWT and validate it. If there is a token and it is valid the // rest of the code will execute. app.get('/secured/ping', authenticate, function(req, res) { res.send(200, {text: "All good. You only get this message if you're authenticated"}); }) var port = process.env.PORT || 3001; // We launch our server on port 3001. http.createServer(app).listen(port, function (err) { console.log('listening in:' + port); });
This is a pretty standard Node/Express setup. The only unique thing we did was implement the
express-jwt middleware which will validate a JWT. Since we are doing this integration with Auth0, we'll let Auth0 handle the process of generating and signing tokens. If we did not want to use Auth0, we could create and sign our own tokens with the
jsonwebtoken module. Let's see an example of how this can be accomplished.
// Import modules ... var jwt = require('jsonwebtoken'); var token = jwt.sign({ sub : "1234567890", name : "Ado Kukic", admin: true }, 'shhhh'); app.get('/token', function(req, res){ res.send(token); });
If we were to write this code, launch the server, and navigate to
localhost:3001/token we would see a signed token containing the three claims we made. The
jsonwebtoken module can also be used to verify and decrypt the tokens. To learn more about it, check out its repo. As we won't be generating tokens on our server, we can remove this code.
Implementing the Front-end
Next, we'll implement our Angular 2 app. If you are following along from our GitHub repo, you'll see two options for the front-end. One uses systemjs while the other Webpack for loading and managing our modules. As the preferred way to write Angular 2 apps is with TypeScript, we'll build our sample app with TypeScript. For our demo, we'll be working out of the systemjs directory. Additionally, we'll be using the
angular2-jwt library which provides helper methods for making requests with the correct headers and also checking to see if a valid token exists.
First things first. We need an entry point into our app and that is
index.html.
<html> <head> <base href="/"> <title>Angular 2 Playground</title> <meta charset="UTF-8"> <link rel="stylesheet" href=""> <!-- We'll include the Auth0 Lock widget to handle authentication --> <script src="//cdn.auth0.com/js/lock-9.0.min.js"></script> <script src="node_modules/es6-shim/es6-shim.min.js"></script> > <app>Loading...</app> </body> </html>
Next, we'll define the entry point of our Angular 2 application. This will be done in a file called
main.ts.
import { bootstrap } from '@angular/platform-browser-dynamic'; import {provide} from '@angular/core'; import {LocationStrategy, HashLocationStrategy} from '@angular/common'; import {RouteConfig, ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from '@angular/router-deprecated'; import {HTTP_PROVIDERS} from '@angular/http'; // Here we load the angular2-jwt library import {AUTH_PROVIDERS} from 'angular2-jwt'; import { App } from './app.component'; bootstrap(App, [ HTTP_PROVIDERS, ROUTER_PROVIDERS, AUTH_PROVIDERS, provide(LocationStrategy, { useClass: HashLocationStrategy }) ])
We'll build the
auth.service.ts next. This service will provide methods for logging users in and out of our application. Be sure to replace the
YOUR_CLIENT_ID and
YOUR_DOMAIN with your apps settings from your Auth0 management dashboard.
import {Injectable, NgZone} from '@angular/core'; import {Router} from '@angular/router-deprecated'; import {AuthHttp, tokenNotExpired} from 'angular2-jwt'; // Avoid name not found warnings declare var Auth0Lock: any; @Injectable() export class Auth { // Replace YOUR_CLIENT_ID and YOUR_DOMAIN with your credentials lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_DOMAIN'); refreshSubscription: any; user: Object; zoneImpl: NgZone; constructor(private authHttp: AuthHttp, zone: NgZone, private router: Router) { this.zoneImpl = zone; this.user = JSON.parse(localStorage.getItem('profile')); } public authenticated() { // Check if there's an unexpired JWT return tokenNotExpired(); } public login() { // Show the Auth0 Lock widget this.lock.show({}, (err, profile, token) => { if (err) { alert(err); return; } // If authentication is successful, save the items // in local storage localStorage.setItem('profile', JSON.stringify(profile)); localStorage.setItem('id_token', token); this.zoneImpl.run(() => this.user = profile); }); } public logout() { localStorage.removeItem('profile'); localStorage.removeItem('id_token'); this.zoneImpl.run(() => this.user = null); this.router.navigate(['Home']); } }
Now that we have the foundation complete. We can start building our application. We'll build our root component in a file called
app.component.ts.
import {Component} from '@angular/core'; import {RouteConfig, ROUTER_PROVIDERS, ROUTER_DIRECTIVES} from '@angular/router-deprecated'; import {HTTP_PROVIDERS} from '@angular/http'; import {AUTH_PROVIDERS} from 'angular2-jwt'; import {Home} from './home.component'; import {Ping} from './ping.component'; import {Profile} from './profile.component'; import {Auth} from './auth.service'; @Component({ selector: 'app', providers: [ Auth ], directives: [ ROUTER_DIRECTIVES ], templateUrl: 'src/app.template.html', styles: [`.btn-margin { margin-top: 5px}`] }) @RouteConfig([ { path: '/home', name: 'Home', component: Home, useAsDefault: true }, { path: '/ping', name: 'Ping', component: Ping }, { path: '/profile', name: 'Profile', component: Profile } ]) export class App { constructor(private auth: Auth) {} }
You may notice from our directive metadata that we will be loading an external template called
app.template.html. Angular 2 templates can be inlined or reference an external file and since our template is on the longer side, we'll place it in an external file.
<nav class="navbar navbar-default"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="#">Auth0 - Angular 2</a> <button class="btn btn-primary btn-margin" [routerLink]=" ['Home'] ">Home</button> <button class="btn btn-primary btn-margin" [routerLink]=" ['Ping'] ">Ping</button> <button class="btn btn-primary btn-margin" [routerLink]=" ['Profile'] " *Profile</button> <button class="btn btn-primary btn-margin" (click)="auth.login()" *Log In</button> <button class="btn btn-primary btn-margin" (click)="auth.logout()" *Log Out</button> </div> </div> </nav> <main class="container"> <router-outlet></router-outlet> </main>
From our
app.template.html file, we see that we will end up having three routes: Home, Ping, and Profile. Additionally, there are two more buttons, Log In and Log Out. The
*ngIf directive conditionally displays some routes based on whether the user is authenticated or not. Let's build out the three routes.
Home Component
The home component is the default route loaded. It is publicly accessible.
import {Component} from '@angular/core'; @Component({ selector: 'home', template: ` <h1>Welcome to auth0-angular2</h1> <p> This repo shows you how to set up authentication in your Angular 2 apps with Auth0. Get started by providing your Auth0 client ID and domain in the Auth0Lock widget in <code>auth/auth.service.ts</code>. </p> ` }) export class Home { constructor() {} }
Ping Component
The ping component interacts with our NodeJS server that we built earlier. The Node server will need to be running for you to access these routes.
import {Component} from '@angular/core'; import {Http} from '@angular/http'; import {AuthHttp} from 'angular2-jwt'; import {Auth} from './auth.service'; import 'rxjs/add/operator/map'; @Component({ selector: 'ping', template: ` <h1>Send a Ping to the Server</h1> <p *Log In to Get Access to a Secured Ping</p> <button class="btn btn-primary" (click)="ping()">Ping</button> <button class="btn btn-primary" (click)="securedPing()" *Secured Ping</button> <h2></h2> ` }) export class Ping { API_URL: string = ''; message: string; constructor(private http: Http, private authHttp: AuthHttp, private auth: Auth) {} ping() { this.http.get(`${this.API_URL}/ping`) .map(res => res.json()) .subscribe( data => this.message = data.text, error => this.message = error._body ); } securedPing() { this.authHttp.get(`${this.API_URL}/secured/ping`) .map(res => res.json()) .subscribe( data => this.message= data.text, error => this.message = error._body ); } }
Profile Component
The profile component displays user data for the currently logged in user. This component can only be accessed by a logged in user.
import {Component} from '@angular/core'; import {CanActivate} from '@angular/router-deprecated'; import {tokenNotExpired} from 'angular2-jwt'; import {Auth} from './auth.service'; @Component({ selector: 'profile', template: ` <h1>Profile</h1> <img [src]="auth.user.picture"> <h2></h2> <span></span> ` }) @CanActivate(() => tokenNotExpired()) export class Profile { constructor(private auth: Auth) {} }
With the three components built, we are ready to launch our app. If you are using the provided GitHub repo, you can simply run
gulp play and your code will be transpiled into JavaScript and the application will launch at
localhost:9000. If you did not use the GitHub repo, you will need to transpile the typescript or change the systemjs configuration to load typescript files instead.
Navigating to
localhost:9000 will load our the UI for app which will look like:
You can navigate to the Ping tab and click the "Ping" button to make a call to your Node API and it will display the correct message. If you click on the Login button you will be prompted to log in using the Auth0 Lock widget. Upon successfully authenticating, you will be able to view your Profile, log out, and have the ability to call a Secured Ping from the Ping tab.
Progressive Web Apps
The last topic I want to cover before we close out this article is Progressive Web Apps. Progressive Web Apps allow your web based application to behave more like a native mobile iOS or Android app. Progressive Web Apps bring many advantages including increased performance, are "installable" on mobile devices, and can work offline.
Angular 2, through its Mobile Toolkit, makes it easy to transform your Angular 2 app into a Progressive Web App. There are many components that can make your app more progressive, the one we'll look at today is the webapp manifest. This manifest is simply a file, similar to
package.json for example, where you define specifics for your application. When your website is accessed on a mobile device, this manifest can be read and based on the information inside certain actions taken like setting the app name or setting the orientation of the app. Let's look at an app manifest, which is titled
manifest.webapp and see which options we can set:
{ "name": "Auth0 Angular 2 App", "short_name": "A0 Angular 2 App", "icons": [ { "src": "/android-chrome-36x36.png", "sizes": "36x36", "type": "image/png", "density": 0.75 }, { "src": "/android-chrome-48x48.png", "sizes": "48x48", "type": "image/png", "density": 1 }, { "src": "/android-chrome-72x72.png", "sizes": "72x72", "type": "image/png", "density": 1.5 }, { "src": "/android-chrome-96x96.png", "sizes": "96x96", "type": "image/png", "density": 2 }, { "src": "/android-chrome-144x144.png", "sizes": "144x144", "type": "image/png", "density": 3 }, { "src": "/android-chrome-192x192.png", "sizes": "192x192", "type": "image/png", "density": 4 } ], "theme_color": "#000000", "background_color": "#e0e0e0", "start_url": "/index.html", "display": "standalone", "orientation": "portrait" }
Conclusion
In today's article we compared the differences between cookie- and token-based authentication. We highlighted the advantages and concerns of using tokens and also wrote a simple app to showcase how JWT works in practice. There are many reasons to use tokens and Auth0 is here to ensure that implementing token authentication is easy and secure. Finally, we introduced Progressive Web Apps to help make your web applications feel more native on mobile devices. Sign up for a free account today and be up and running in minutes.
Published at DZone with permission of Adnan Kukic , 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/cookies-vs-tokens-the-definitive-guide?utm_campaign=n00b_news&utm_medium=email&utm_source=Revue%20newsletter | CC-MAIN-2020-34 | refinedweb | 4,235 | 54.83 |
How to Generate Signed Amazon S3 URLs in Node.js
July 2nd, 2021
What You Will Learn in This Tutorial
Access private content in an Amazon S3 bucket using short-term, signed URLs.
Table of Contents
Getting started
To sped up our work, we're going to use the CheatCode Node.js Boilerplate as a starting point for our work. To begin, let's clone a copy of that project:
Terminal
git clone
Next, we need to install the boilerplate's dependencies:
Terminal
cd nodejs-server-boilerplate && npm install
After this, we need to install the
aws-sdk package from NPM which will give us access to the Amazon S3 API for Node.js:
Terminal
npm i aws-sdk
Finally, start up the development server:
Terminal
npm run dev
With that running, we're ready to begin.
Writing a function for generating signed URLs
Fortunately, the
aws-sdk library gives us a simple function as part of the
S3 constructor for generating signed URLs. What we're going to do is write a function that wraps around this and initializes our connection to Amazon S3.
();
After we've imported
aws-sdk up top as
AWS, we set the global
AWS.config value equal to a new instance of the
AWS.Config class (notice the subtle difference between the lowercase
cd on the global we're setting and the capital
C on the constructor function).
To that class, we pass an object with a few different settings. First, we want to pay attention to the
accessKeyId and
secretAccessKey properties. These are set to the keys that we obtain from AWS that associate our calls to S3 with our AWS account.
While obtaining these keys is out of the scope of this tutorial, if you don't already have them, read this official guide on how to create them via AWS IAM (Identity Access Management).
Once you have your keys you can continue with the tutorial.
In the code above, we're not pasting our keys directly into our code. Instead, we're using the
settings feature that's built-in to the boilerplate we're using. It's set up to load the settings for our app on a per-environment basis (i.e., load different keys for our
development environment versus our
production environment).
The file we import here (located at
/lib/settings.js) is responsible for deciding which settings file needs to be loaded when our app starts up (the process kicked off by the
npm run dev command that we ran earlier). By default, the boilerplate includes a
settings-development.json file at the root of the project which is intended to contain our development environment keys (keeping your keys separated by environment prevents unnecessary errors and security issues).
Opening that file up, we want to add the AWS keys you obtained like this:
/settings-development.json
{ [...] "aws": { "akid": "", "sak": "" }, [...] }
Here, we add a new property alphabetically to the JSON object at the root of the file called
aws (because we're in a
.json file, we need to use double-quotes). Set to that property is another object containing our keys from AWS. Here,
akid should have its value set to your Access Key ID for your IAM user and
sak should have its value set to your Secret Access Key.
();
Back in our file, with
settings imported, now we can point to our keys with
settings.aws.akid and
settings.aws.sak. The
settings && settings.aws && settings.aws.akid (the
settings?.aws?.akid we see above is equivalent to this).
?inbetween each property above is a short-hand technique that helps us to avoid writing out
With our keys set, next, we make sure to set the
region where our Amazon S3 bucket lives. Creating an S3 bucket is also out of the scope of this tutorial, so if you haven't already set one up, give this guide from AWS a read and then continue with this tutorial once you've completed it. Make sure to note the region where you create your bucket (if you can't find the dashed version of the region, check this list to find the proper code to pass to
region above that
looks-like-this).
Next, with your
region set, we add
signatureVersion, setting it to
v4 (this is the latest version of the AWS signature protocol).
Finally, to round out the snippet above, once we've passed all of our settings to
AWS.Config, we create a variable
const s3 and set it equal to a new instance of the
AWS.S3() class.
/lib/generateSignedS3URL.js
import AWS from "aws-sdk"; import settings from "./settings"; AWS.config = new AWS.Config({ ... }); const s3 = new AWS.S3(); export default ({ bucket, key, expires }) => { const signedUrl = s3.getSignedUrl("getObject", { Key: key, Bucket: bucket, Expires: expires || 900, // S3 default is 900 seconds (15 minutes) }); return signedUrl; };
Like we hinted at earlier, the
aws-sdk library makes generating a signed URL fairly simple. Here, we've added a function that we're setting as a default
export. We expect that function to take in a single argument as a JavaScript object with three properties on it:
bucket- The S3 bucket that holds the file ("object" in AWS-speak) we want to retrieve a signed URL for.
key- The path to the file or "object" in our S3 bucket.
expires- How long in seconds we want the URL to be accessible (after this duration, subsequent attempts to use the URL will fail).
Inside of the function, we create a new variable
const signedUrl which we expect to contain our
signedUrl, here, what we expect to get back from calling
s3.getSignedUrl(). Something that's unique about the
.getSignedUrl() method here is that it's synchronous. This means that when we call the function JavaScript will wait for it to return a value to us before evaluating the rest of our code.
To that function, we pass two arguments: the S3 operation we want to perform (either
getObject or
putObject) and an options object describing what file we want to retrieve a signed URL for.
The operation here should be explained. Here,
getObject is saying that "we want to get a signed URL for an existing object in our S3 bucket." If we were to change that to
putObject, we could simultaneously create a new object and get back a signed URL for it. This is handy if you always need to get back a signed URL (as opposed to getting one after a file has already been uploaded).
For the options object, here, we just copy over the properties from the argument passed to our wrapper function. You'll notice that the properties on the object passed to
.getSignedUrl() are capitalized, whereas the ones passed to our wrapper function are lowercase. In the
aws-sdk, capital letters are used for options passed to functions in the library. Here, we use lowercase for our wrapper function to keep things simpler.
To be safe, for the
Expires option, if we haven't passed a custom
expires value into our wrapper function, we fall back to
900 seconds, or, 15 minutes (this means the URL we get back from Amazon will only be accessible for 15 minutes before it's a dud).
Finally, to wrap up our function, we return
signedUrl. Next, to test this out, we're going to set up a simple Express.js route where we can call to the function.
Wiring up an Express route to test URL generation
As part of the CheatCode Node.js Boilerplate we're using for this tutorial, we're provided with an Express.js server pre-configured. That server is created inside of
/index.js at the root of the project. In there, we create the Express
app and then—to stay organized—pass that
app instance into a series of functions where we define our actual routes (or extend the Express HTTP server).
/api/index.js
import getSignedS3URL from "../lib/getSignedS3URL"; import graphql from "./graphql/server"; export default (app) => { graphql(app); app.use("/s3/signed-url", (req, res) => { const signedUrl = getSignedS3URL({ bucket: "cheatcode-tutorials", key: "panda.jpeg", expires: 5, // NOTE: Make this URL expire in five seconds. }); res.send(` <html> <head> <title>AWS Signed URL Test</title> </head> <body> <p>URL on Amazon: ${signedUrl}</p> <img src="${signedUrl}" alt="AWS Signed URL Test" /> <script> setTimeout(() => { location = "${signedUrl}"; }, 6 * 1000); </script> </body> </html> `); }); };
Here, inside of the
api() function that's called from the
/index.js file we just discussed, we take in the Express
app instance as an argument. By default, the boilerplate sets up a GraphQL server for us and here, we seperate the creation of that server off into its own function
graphql(), passing in the
app instance so it can be referenced internally.
Next, the part we care about for this tutorial, we create a test route at
/s3/signed-url in our app (with our server running, this will be available at
In the callback for that route, we can see a call being made to our
getSignedS3URL() function (to be clear, our wrapper function). To it, we pass the single options object we've anticipated with
bucket,
key, and
expires.
Here, as a demo, we're passing the
cheatcode-tutorials bucket (used for testing in our tutorials), a file that already exists in our bucket
panda.jpeg as the
key, and
expires set to
5 (meaning, expire the URL we get back and store in
const signedUrl here after five seconds).
We set this fairly low to showcase what happens when a URL is accessed past its expiration time (you will most likely want to set this much higher depending on your use case). To show off how these URLs work, we call to
res.send() to respond to any request to this route with some dummy HTML, displaying the full
signedUrl that we get back from Amazon and—because we know it's a
.jpeg file—rendering that URL in an
<img /> tag.
Beneath that, we've added a short script with a
setTimeout() method that redirects the browser to our signedUrl after six seconds. Assuming our
expires value of 5 seconds is respected, when we visit this URL, we expect it to be inaccessible:
In our demo, we can see that when we load the page we get our URL back (along with our panda picture). After six seconds, we redirect to the exact same URL (no changes to it) and discover that AWS throws an error telling us our "request has expired." This confirms that our signed URL behaved as expected and expired five seconds after its creation.
Wrapping up
In this tutorial, we learned how to generate a signed, temporary URL for an S3 object using the
aws-sdk package. We learned how to write a wrapper function that both establishes a connection to AWS and generates our signed URL.
To demonstrate our function, finally, we wired up an Express.js route, returning some HTML with an image tag rendering our signed URL and then redirecting after a few seconds to verify the signed URL expires properly.
Get the latest free JavaScript and Node.js tutorials, course announcements, and updates from CheatCode in your inbox.
No spam. Just new tutorials, course announcements, and updates from CheatCode. | https://cheatcode.co/tutorials/how-to-generate-signed-amazon-s3-urls-in-node-js | CC-MAIN-2022-21 | refinedweb | 1,889 | 62.17 |
In this tutorial we will check how to control a DC motor using the micro:bit board and MicroPython.
Introduction
In this tutorial we will check how to control a DC motor using the micro:bit board and MicroPython.
Since we can’t use the micro:bit to directly power the DC motor, we will use a ULN2803A integrated circuit for that. So, the micro:bit will be responsible for controlling the ULN2803A which, in turn, will allow the motor to be powered or not.
You can check the datasheet of the ULN2803A here. You can also check this previous tutorial, which explains in more detail how to use this integrated circuit to control a DC motor.
The electric diagram
Since the pins of the micro:bit can only source a maximum current of 5 mA [2], we cannot directly connect the device to a DC motor.
Thus, as already mentioned, we will be using a ULN2803A integrated circuit to provide the current for the motor to operate. The micro:bit will only control if the ULN2803A is providing current to the motor or not.
The connection diagram between the devices can be seen in figure 1. Note that I’m using a 5 V DC motor.
In sum, the ULN2803A will act as a switch, which will turn on / off the connection of the motor to GND, depending if the voltage applied to pin ln 1 is either high or low, respectively.
So, if pin 0 of the micro:bit is in a high level, the ULN2803A will connect the DC motor to GND and thus it will run. If pin 0 of the micro:bit is in a low level, then the ULN2803A disconnects the motor from GND and it will be stopped.
The code
The first thing we will do is importing all the functionalities from the microbit module. With this, we will have access to the objects that will allow us to control the state of the pins, as we will see below.
from microbit import *
We will write the rest of our code inside an infinite loop, so we can turn on and off the motor in a pattern that will repeat as long as the program is running.
while True: #loop code
In MicroPython, each pin of the micro:bit is represented by an object called pinX, where X is the number of the pin [1]. As previously hinted, these objects representing the pins can be imported from the microbit module, like we already did.
Note that, in our case, we have the pin 0 of the micro:bit board connected to the ULN2803A, which means that we will interact with the object named pin0.
In order to set the digital level of a pin, we simply need to call the write_digital method on the pin object, passing as input the value 1 to set it to high, or 0 to set it to low.
So, we will start by setting the digital pin to a high level, thus turning the motor on.
pin0.write_digital(1)
After this, we will delay the execution 4 seconds, so the motor stays on a bit. We will do it by calling the sleep method, which receives as input the number of milliseconds to wait.
This function also belongs to the microbit module. Since we imported all the content from this module in the first line of our code, then we can use the sleep function. You can read more about it here.
sleep(4000)
To finalize, we will now turn the motor off by calling again the write_digital method, passing as input the value 0. This will set the digital level of the pin to low.
We will also delay the execution 4 seconds, in order for the motor to stay off during some time.
pin0.write_digital(0) sleep(4000)
Note that since we have written the previous 4 lines of code inside an infinite while loop, the motor will keep turning on and off as long as the program is running. The final code can be seen below.
from microbit import * while True: pin0.write_digital(1) sleep(4000) pin0.write_digital(0) sleep(4000)
Testing the code
To test the code, simply run it on your micro:bit board, after all the connections shown in figure 1 are done. I’ll be using uPyCraft, a MicroPython IDE, to run the previous code on my device.
After the script starts running, the motor should start moving and then stopping in 4 seconds intervals, like shown in the video below.
References
[1]
[2] | https://techtutorialsx.com/2019/04/07/microbit-micropython-controlling-a-dc-motor/ | CC-MAIN-2019-35 | refinedweb | 764 | 68.7 |
Code should execute sequentially if run in a Jupyter notebook
- See the set up page to install Jupyter, Python and all necessary libraries
- Please direct feedback to contact@quantecon.org or the discourse forum
We’re now ready to start learning the Python language itself.
The level of this and the next few lectures will suit those with some basic knowledge of programming.
But don’t give up if you have none—you are not excluded.
You just need to cover a few of the fundamentals of programming before returning here.
Good references for first time programmers include:
- The first 5 or 6 chapters of How to Think Like a Computer Scientist.
- Automate the Boring Stuff with Python.
- The start of Dive into Python 3.
Note: These references offer help on installing Python but you should probably stick with the method on our set up page.
You’ll then have an outstanding scientific computing environment (Anaconda) and be ready to move on to the rest of our course.:
We’ll do this in several different ways.
import numpy as np import matplotlib.pyplot as plt %matplotlib inline x = np.random.randn(100) plt.plot(x) plt.show()
Import Statements¶
The first two lines of the program import functionality...
Here’s another example
import numpy as np np.sqrt(4)
2.0
We could also just write
import numpy numpy.sqrt(4)
2.0
But the former method is convenient and more standard.
Why all the Imports?¶
Remember that Python is a general-purpose language.
The core language is quite small so it’s easy to learn and maintain.
When you want to do something interesting with Python, you almost always need to import additional functionality.
Scientific work in Python is no exception.
Most of our programs start off with lines similar to the
import statements seen above.
Packages¶
As stated above, NumPy is a Python package.
Packages are used by developers to organize a code library..6/site-packages/numpy
import numpy as np np.sqrt(4)
2.0
Here’s another way to access NumPy’s square root function
from numpy import sqrt sqrt(4)
2.
Alternative Versions¶
Let’s try writing some alternative versions of our first program.
Our aim in doing this is to illustrate some more Python syntax and semantics.
The programs below are less efficient but
- help us understand basic constructs like loops
- illustrate common data types like lists
ts_length = 100 ϵ_values = [] # Empty list for i in range(ts_length): e = np.random.randn() ϵ_values.append(e) plt.plot(ϵ_values) plt.show()
In brief,
- The first pair of lines
importfunctionality as before.
- The next line sets the desired length of the time series.
- The next line creates an empty list called
ϵ_valuesthat will store the $ \epsilon_t $ values as we generate them.
-.
x = [10, 'foo', False] # We can include heterogeneous data inside a list type(x)
list
The first element of
x is an integer, the next is a string and the third is a Boolean value.
When adding a value to a list, we can use the syntax
list_name.append(some_value)
x
[10, 'foo', False]
x.append(2.5) x
[10, 'foo', False, 2.5]
[10, 'foo', False, 2.5]
x.pop()
2.5
x
[10, 'foo', False]
x
[10, 'foo', False]
x[0]
10
x[1]
'foo'")
The plural of dog is dogs The plural of cat is cats The plural of bird is birds.
Code Blocks.
Tabs vs Spaces¶
One small “gotcha” here is the mixing of tabs and spaces, which often leads to errors.
(Important: Within text files, the internal representation of tabs and spaces is not the same)
You can use your
Tab key to insert 4 spaces, but you need to make sure it’s configured to do so.
If you are using a Jupyter notebook you will have no problems here.
Also, good text editors will allow you to configure the Tab key to insert spaces instead of tabs — trying searching online.()
User-Defined Functions¶
Now let’s go back to the
for loop, but restructure our program to make the logic clearer.
To this end, we will break our program into two parts:
- A user-defined function that generates a list of random variables.
The main part of the program that
- calls this function to get data
- plots the data
This is accomplished in the next program
def generate_data(n): ϵ_values = [] for i in range(n): e = np.random.randn() ϵ_values.append(e) return ϵ_values data = generate_data(100) plt.plot(data) plt.show()
Let’s go over this carefully, in case you’re not familiar with functions and how they work.
We have defined a function called
generate_data() as follows
defis a Python keyword used to start function definitions.
def generate_data(n):indicates that the function is called
generate_dataand that it has a single argument
n.
- The indented code is a code block called the function body—in this case, it creates an IID list of random draws using the same logic as before.
- The
returnkeyword indicates that
ϵ_valuesis the object that should be returned to the calling code.
This whole function definition is read by the Python interpreter and stored in memory.
When the interpreter gets to the expression
generate_data(100), it executes the function body with
n set equal to 100.
The net result is that the name
data is bound to the list
ϵ_values returned by the function.
def generate_data(n, generator_type): ϵ_values = [] for i in range(n): if generator_type == 'U': e = np.random.uniform(0, 1) else: e = np.random.randn() ϵ_values.append(e) return ϵ_values data = generate_data(100, 'U') plt.plot(data) plt.show()
Hopefully, the syntax of the if/else clause is self-explanatory, with indentation again delimiting the extent of the code blocks.
Notes
- We are passing the argument
Uas a string, which is why we write it as
'U'.
Notice that equality is tested with the
==syntax, not
=.
- For example, the statement
a = 10assigns the name
ato the value
10.
- The expression
a == 10evaluates to either
Trueor
False, depending on the value of
a.
Now, there are several ways that we can simplify the code above.
For example, we can get rid of the conditionals all together by just passing the desired generator type as a function.
To understand this, consider the following version.
def generate_data(n, generator_type): ϵ_values = [] for i in range(n): e = generator_type() ϵ_values.append(e) return ϵ_values data = generate_data(100, np.random.uniform) plt.plot(data) plt.show()
Now, when we call the function
generate_data(), we pass
np.random.uniform
as the second argument.
This object is a function.
When the function call
generate_data(100, np.random.uniform) is executed, Python runs the function code block with
n equal to 100 and the name
generator_type “bound” to the function
np.random.uniform.
- While these lines are executed, the names
generator_typeand
np.random.uniformare “synonyms”, and can be used in identical ways.
This principle works more generally—for example, consider the following piece of code
max(7, 2, 4) # max() is a built-in Python function
7
m = max m(7, 2, 4)
7
Here we created another name for the built-in function
max(), which could then be used in identical ways.
In the context of our program, the ability to bind new names to functions means that there is no problem passing a function as an argument to another function—as we did above.
List Comprehensions¶
We can also simplify the code for generating the list of random draws considerably by using something called a list comprehension.
List comprehensions are an elegant Python tool for creating lists.
Consider the following example, where the list comprehension is on the right-hand side of the second line
animals = ['dog', 'cat', 'bird'] plurals = [animal + 's' for animal in animals] plurals
['dogs', 'cats', 'birds']
Here’s another example
range(8)
range(0, 8)
doubles = [2 * x for x in range(8)] doubles
[0, 2, 4, 6, 8, 10, 12, 14]
With the list comprehension syntax, we can simplify the lines
ϵ_values = [] for i in range(n): e = generator_type() ϵ_values.append(e)
into
ϵ_values = [generator_type() for i in range(n)]
Exercise 1¶
Recall that $ n! $ is read as “$ n $ factorial” and defined as $ n! = n \times (n - 1) \times \cdots \times 2 \times 1 $.
There are functions to compute this in various modules, but let’s write our own version as an exercise.
In particular, write a function
factorial such that
factorial(n) returns $ n! $
for any positive integer $ n $.
Exercise 2¶
The binomial random variable $ Y \sim Bin(n, p) $ represents the number of successes in $ n $ binary trials, where each trial succeeds with probability $ p $.
Without any import besides
from numpy.random import uniform, write a function
binomial_rv such that
binomial_rv(n, p) generates one draw of $ Y $.
Hint: If $ U $ is uniform on $ (0, 1) $ and $ p \in (0,1) $, then the expression
U < p evaluates to
True with probability $ p $.
import numpy as np
Your hints are as follows:
- If $ U $ is a bivariate uniform random variable on the unit square $ (0, 1)^2 $, then the probability that $ U $ lies in a subset $ B $ of $ (0,1)^2 $ is equal to the area of $ B $.
- If $ U_1,\ldots,U_n $ are IID copies of $ U $, then, as $ n $ gets large, the fraction that falls in $ B $, converges to the probability of landing in $ B $.
- For a circle, area = pi * radius^2.
Exercise 5¶
Your next task is to simulate and plot the correlated time series$$ x_{t+1} = \alpha \, x_t + \epsilon_{t+1} \quad \text{where} \quad x_0 = 0 \quad \text{and} \quad t = 0,\ldots,T $$
The sequence of shocks $ \{\epsilon_t\} $ is assumed to be IID and standard normal.
In your solution, restrict your import statements to
import numpy as np import matplotlib.pyplot as plt
import numpy as np import matplotlib.pyplot as plt x = [np.random.randn() for i in range(100)] plt.plot(x, label="white noise") plt.legend() plt.show()
Now, starting with your solution to exercise 5, plot three simulated time series, one for each of the cases $ \alpha=0 $, $ \alpha=0.8 $ and $ \alpha=0.98 $.
In particular, you should produce (modulo randomness) a figure that looks as follows
(The figure nicely illustrates how time series with the same one-step-ahead conditional volatilities, as these three processes have, can have very different unconditional volatilities.)
Use a
for loop to step through the $ \alpha $ values.
Important hints:
If you call the
plot()function multiple times before calling
show(), all of the lines you produce will end up on the same figure.
- And if you omit the argument
'b-'to the plot function, Matplotlib will automatically select different colors for each line.
The expression
'foo' + str(42)evaluates to
'foo42'.
def factorial(n): k = 1 for i in range(n): k = k * (i + 1) return k factorial(4)
24
from numpy.random import uniform def binomial_rv(n, p): count = 0 for i in range(n): U = uniform() if U < p: count = count + 1 # Or count += 1 return count binomial_rv(10, 0.5)
5
Exercise 3¶
Consider the circle of diameter 1 embedded in the unit square.
Let $ A $ be its area and let $ r=1/2 $ be its radius.
If we know $ \pi $ then we can compute $ A $ via $ A = \pi r^2 $.
But here the point is to compute $ \pi $, which we can do by $ \pi = A / r^2 $.
Summary: If we can estimate the area of the unit circle, then dividing by $ r^2 = (1/2)^2 = 1/4 $ gives an estimate of $ \pi $.
We estimate the area by sampling bivariate uniforms and looking at the fraction that falls into the unit circle
n = 100000 count = 0 for i in range(n): u, v = np.random.uniform(), np.random.uniform() d = np.sqrt((u - 0.5)**2 + (v - 0.5)**2) if d < 0.5: count += 1 area_estimate = count / n print(area_estimate * 4) # dividing by radius**2
3.14228
from numpy.random import uniform payoff = 0 count = 0 for i in range(10): U = uniform() count = count + 1 if U < 0.5 else 0 if count == 3: payoff = 1 print(payoff)
0
α = 0.9 ts_length = 200 current_x = 0 x_values = [] for i in range(ts_length + 1): x_values.append(current_x) current_x = α * current_x + np.random.randn() plt.plot(x_values) plt.show()
αs = [0.0, 0.8, 0.98] ts_length = 200 for α in αs: x_values = [] current_x = 0 for i in range(ts_length): x_values.append(current_x) current_x = α * current_x + np.random.randn() plt.plot(x_values, label=f'α = {α}') plt.legend() plt.show() | https://lectures.quantecon.org/py/python_by_example.html | CC-MAIN-2019-35 | refinedweb | 2,101 | 64.91 |
Hi,
I am trying to check my code (python 2.7 and Pycharm 2017.3.3) with unittests and in one test I get a the following error:
-----------
Traceback (most recent call last):
File "/home/vagrant/.pycharm_helpers/pycharm/_jb_unittest_runner.py", line 35, in <module>
main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING)
File "/usr/lib/python2.7/unittest/main.py", line 95, in __init__
self.runTests()
File "/usr/lib/python2.7/unittest/main.py", line 232, in runTests
self.result = testRunner.run(self.test)
File "/home/vagrant/.pycharm_helpers/pycharm/teamcity/unittestpy.py", line 304, in run
return super(TeamcityTestRunner, self).run/case.py", line 393, in __call__
return self.run(*args, **kwds)
File "/usr/lib/python2.7/unittest/case.py", line 370, in run
result.stopTest(self)
File "/home/vagrant/.pycharm_helpers/pycharm/teamcity/unittestpy.py", line 260, in stopTest
output = sys.stdout.getvalue()
AttributeError: 'file' object has no attribute 'getvalue'
-----------
I don't know why it happens and could not find any solution or similar issue on that topic. I hope someone can help me out ;-)
Cheers,
Niko
Hello.
Does it happen to all tests or just some of them? Do you redirect unittest to file somehow or do you monkeypatch stdout?
I have only tested two unittests in our software so far, and one works perfectly fine, test complets with ok, and the other one runs through, doing what it is supposed to do, but then throws the mentioned error. Both unittests are built in a similar way: only one function with testdata is run.
I haven't touched stdout. With redirect unittest to file, do you mean to log the output? That I do not.
Hi Nikodem Bienia! Is it possible to share the failing test code with us? You can create a ticket in our bug tracker with visibility level of pycharm-developers to ensure privacy.
This fails in the same way when run through IntelliJ's "Run Unittests for ..." feature.
```
import random
import unittest
import numba
import numpy as np
@numba.njit
def is_contiguous(begin1, end1, begin2, end2):
if begin1 > begin2: return is_contiguous(begin2, end2, begin1, end1)
return end1 + 1 >= begin2
class RangeTests(unittest.TestCase):
def test_contiguous(self):
import sys
print sys.stdout, type(sys.stdout) # TeamCity somethingthing
assert not is_contiguous(3, 8, 0, 1)
assert is_contiguous(3, 8, 1, 2)
if __name__ == '__main__':
unittest.main()
```
Fails here:
.../config/plugins/python-ce/helpers/pycharm/teamcity/unittestpy.py
def stopTest(self, test):
test_id = self.get_test_id(test)
if getattr(self, 'buffer', None):
# Do not allow super() method to print output by itself
self._mirrorOutput = False
output = sys.stdout.getvalue() << syst.stdout has no getvalue method
Hi Stuart! Which PyCharm version do you use? This code example works fine for me on 2018.1.4.
It failed for my with a new install of PyCharm 2018.1.4, them worked after updating the plugins.
I take it, back, it still fails.
Here's another example:
Also see
Probably, you unittest runner shouldn't assume reload(sys) is not called, but instead cached the original sys.stderr, sys.stdout.
Since setting JB_DISABLE_BUFFERING is a poor fix and solvable in your libraries, can we reopen this?
Same issue on :.13.6
It gets solved by resetting `
`
but a better solution is needed
Hi Alisa,
Please see
The comment is pretty fresh, thus I suspect the information regarding plans to support it is correct.
This big is absolutely solveble without needed to define an environment variable to disable functionality. You shouldn’t expect environment variables be an acceptable solution for any app launched from a UI dock, or expect the user to define the variable for each test config.
Pycharm should simply keep a reference to the string IO it’s runner created. Where it is referenced at shut down, simply retrieve it instead of assuming sys.stdio is the object you assigned to it at the start and breaking every program that overrides it. | https://intellij-support.jetbrains.com/hc/en-us/community/posts/360000019990-Unittest-Error-AttributeError-file-object-has-no-attribute-getvalue- | CC-MAIN-2019-13 | refinedweb | 656 | 60.51 |
In this tutorial, you train a simple model to predict the species of flowers, using the Iris dataset. After you train and save the model locally, you deploy it to AI Platform and query it to get online predictions.
You can deploy and serve scikit-learn pipelines on AI Platform. The Pipeline module in scikit-learn enables you to apply multiple data transformations before training with an estimator. This encapsulates multiple steps in data processing and ensures that the same training data is used in each step.
This tutorial requires Python 2.7. To use Python 3.5, see how to get online predictions with XGBoost or how to get online predictions with scikit-learn.
Overview
In this introductory tutorial, you complete the following steps:
- Use a scikit-learn pipeline to train a model on the Iris dataset.
- Save the model locally.
- Upload the saved model to Cloud Storage.
- Create an AI Platform model resource and model version.
- Get online predictions for two data instances..
Set up your environment
Choose one of the options below to set up your environment locally on macOS or in a remote environment on Cloud Shell.
For macOS users, we recommend that you set up your environment using the MACOS tab below. Cloud Shell, shown on the CLOUD SHELL tab, is available on macOS, Linux, and Windows. Cloud Shell provides a quick way to try AI Platform, but isn’t suitable for ongoing development work.
macOS
Check Python installation
Confirm that you have Python installed and, if necessary, install it.
python -V
Check
pipinstallation
pipis Python’s package manager, included with current versions of Python. Check if you already have
pipinstalled by running
pip --version. If not, see how to install
pip.
You can upgrade
pipusing the following command:
pip install -U pip
See the pip documentation for more details.
Install
virtualenv
virtualenvis a tool to create isolated Python environments. Check if you already have
virtualenvinstalled by running
virtualenv --version. If not, install
virtualenv:
pip install --user --upgrade virtualenv
To create an isolated development environment for this guide, create a new virtual environment in
virtualenv. For example, the following command activates an environment named Console
Click the Activate Google.
Configure the
gcloudcommand:
Train and export your model
You can export
Pipeline objects
using
joblib
or
pickle, similarly to how you export
scikit-learn estimators. The following example sets up a pipeline that uses a
RandomForestClassifier to
train a model on the Iris dataset.
joblib
Set up the pipeline, train the model, and use
joblib to export the
Pipeline object:
from sklearn import datasets from sklearn import svm from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 from sklearn.ensemble import RandomForestClassifier from sklearn.pipeline import Pipeline from sklearn.externals import joblib # joblib.dump(pipeline, 'model.joblib')
pickle
Set up the pipeline, train the model, and use
pickle to export the
Pipeline object:
from sklearn import datasets from sklearn import svm from sklearn.feature_selection import SelectKBest from sklearn.feature_selection import chi2 from sklearn.ensemble import RandomForestClassifier from sklearn.pipeline import Pipeline import pickle # with open('model.pkl', 'wb') as model_file: pickle.dump(pipeline, model_file)
Model file naming requirements
The saved model file that you upload to Cloud Storage must be named
either
model.pkl or
model.joblib, depending on which library you used. This
restriction ensures that AI Platform uses the same pattern to
reconstruct the model on import as was used during export.
For future iterations of your model, organize your Cloud Storage bucket so that each new model has a dedicated directory.
Store your model in Cloud Storage
This section shows you how to create a new bucket. You can use an existing bucket, but it must be in the same region where you plan on running AI Platform jobs. Additionally, if it is not part of the project you are using to run services.
For example, the following code creates
REGIONand sets it to
us-central1:
REGION=us-central1
Create the new bucket:
gsutil mb -l $REGION gs://$BUCKET_NAME
Upload the exported model file to Cloud Storage
Run the following command to upload your saved pipeline file to your bucket in Cloud Storage:
gsutil cp ./model.joblib gs://$BUCKET_NAME/model.joblib
You can use the same Cloud Storage bucket for multiple model files. Each model file must be within its own directory inside the bucket.
Format input for prediction
gcloud
Create an
input.json file with each input instance on a separate line:
).
REST API
Create an
input.json file formatted as a simple list of floats, with each
input instance on a separate line:
{ "instances": [ ).
See more information on formatting your input for online prediction..
runtimeVersion: a runtime version based on the dependencies your model needs. If you're deploying a scikit-learn model or an XGBoost model, this must be at least 1.4.]"
Create the version:
gcloud ai-platform versions create $VERSION_NAME \ --model $MODEL_NAME \ --origin $MODEL_DIR \ --runtime-version=1.14 \ --framework $FRAMEWORK \ --python-version=3.5:
MODEL_NAME="pipeline" Model is deployed. model (str): model name. instances ([[float]]): List of input instances, where each input instance is a list of floats. version: str, version of the model to target. Returns: Mapping[str: any]: dictionary of prediction results defined by the model. """ # Create the AI Platform prediction input parameters in the AI Platform API for prediction input.
What's next
- See how to do preprocessing with scikit-learn pipelines in the scikit-learn notebook on GitHub.
- See more example applications for scikit-learn on GitHub. | https://cloud.google.com/ml-engine/docs/scikit/using-pipelines | CC-MAIN-2019-43 | refinedweb | 914 | 50.12 |
third (of 3) in the series is now available:
John Miller
Technology Services
School of Education
University of Michigan
On Tuesday, November 19, 2002, at 03:19 PM, Rimon Barr wrote:
> This release includes:
>
> - new links page, for spyce related info on the web
Spyce v1.2.8 released on 19 includes:
- VIM syntax highlighting file update
- new links page, for spyce related info on the web
- include module improvements
- 'vars' field added
- included file can return value
- documentation updated, specifically regarding use of 'context'
Spyce v1.2.8 should be quite stable, since Spyce v1.2.7 was extensively
tested and no problems were reported. This release does not contain any
engine changes, and only a minor update to include module code.
Regarding this list and announcements... Based on initial user response,
it seems that a spyce-announce list is desired. It has been created. The
spyce-annouce list will contain only release annoucements and other
information of importance to the Spyce community. It is not open to
general message posting. This list will no longer contain annoucements
(after this one) that are posted to the spyce-annouce list, and will be
used for general Spyce-related questions, answers and discussions. Users
who wish to receive both kinds of email are advised to subscribe to
spyce-announce. You may do so via the following link:
Enjoy,
Rimon.
---
Partial Change Log:
v1.2.8
links page added
spyce VIM syntax file updated; deals with spyce lambdas
include module improvements
- 'vars' field added
- included file can return value
- documentation updated, specifically regarding use of 'context'
v1.2
file-based spyce caching, with config option
performance improvements
Tiberius,
Other interested Spyce users,
cc: Guido (perhaps you can comment on how to turn off the local variable
lookup optimization)
I found your email (see below) in my mailbox unanswered. I don't know why
it stayed there for so long. The namespace problem that you mention was
also spotted by Mr. Petreley in his recent article:
Please read to the end of this message, because I propose a number of
solutions.
A short recap... Think of the static include as a #define in C. You just
paste the included file into the location of the directive, even before
compilation. You can define site-wide constants there, etc. The string
parameter for this tag is a static string (since it is handled
statically).
The dynamic include is more like a function call. It has its own local
namespace, which is destroyed when the function returns. You can pass a
context to the include. The include can modify this context value, and
will do so by reference if it is a reference type (ie. object, list or
dictionary). You can pass back information to the caller this way. The
include can also (as of v1.2.8) return a value. But, the include and the
"includer" do not share the same namespace, and this is by design.
?
I do not believe that #1 is the correct/obvious behaviour. If you would
like to personally manage file paths, then you can go ahead and do so
yourself at runtime. The current behaviour of including a file relative to
the current file seems to be the correct behaviour of the directive. Of
course, this means that you would not be able to use the static include
directive for your needs, but it certainly was not intended to do anything
as fancy as what you propose. Treat it as #define. Its power is the very
fact that it is processed before compilation, and that it treats the text
as if it existed in place of the directive. It does not make sense to me
to paste the code dynamically. At runtime, you would just make a function
call. That means you would either dynamically include a file using the
include module, or use the new Spyce lambdas language construct.
You certainly *could* have the behaviour that you wanted in #2 (and as you
discussed below), with the following syntax:
[[ include.spyce('inc-a.spy', locals()) ]]
The emphasis is on the word 'could', because this does NOT actually work.
The reason is that the locals() dictionary of methods are optimized by the
Python interpretter (and, if you recall, your entire Spyce code sits
inside a single method called spyceProcess). Local variable lookup is done
by Python via a special locals array and updating the locals() dictionary
does not update this array, nor create new variable entries as needed.
This is a Python optimization (benefit or limitation, depending on your
perspective), and there's nothing that I can do about it from within
Spyce, short of putting the entire generated code in an exec statement,
which would force that specific optimization off. Of course, doing this
would slow everything down considerably, as it requires a re-parse of the
generated Python code for each request.
I chose the more conservative (higher performance) approach, because I can
always "add" features to the runtime without breaking existing code.
Namely, I can make locals() work properly by exec'ing the entire generated
code. However, I do not anticipate doing this in the future. It seems too
high a price to pay just to circumvent a Python optimization. In fact,
recompiling Python code, just to get around local variable lookup in
methods sounds more like a tragedy! If Pythonites can live without write
access to locals(), then I conclude the Spycers will make do as well.
Perhaps Guido will add a mechanism to turn this optimization off...
Therefore, you do the following
[[ include.spyce('inc-a.spy', context) ]]
where context is some dictionary, perhaps even the locals() dictionary.
You can access the contents of this dictionary inside the included file,
via the include.context. As of v1.2.8, you'll even have an include.vars
field available in the included file. See:
Using this field it is very convenient (syntactically) to access and
modify the variables that you passed in. And, most importantly, those
modifications will be available to the caller in the context variable,
when the include is complete.
So, I agree with you that it might be nice to pass in parameters by
reference, and update them in the caller. It would be nice, yes, but it is
not possible automatically, because of the way that Python treats the
locals() of a function. To make this concrete, here is a piece of code
that shows the problem:
def foo():
x = 1
print locals()
locals()['x'] = 2
print locals()
print x
If you call the foo() function, the output is:
{'x': 1}
{'x': 1}
1
!!!
Now, if you really, really want to share the local namespace
'transparently', here an idea you might like:
File rim.spy:
[[.import name=include]]
[[\
x = 0
newlocals = include.spyce('rim.spi', locals())
for i in newlocals.keys():
exec '%s = newlocals[%s]' % (i, repr(i))
del newlocals
print x
print y
]]
File rim.spi:
[[\
for i in include.context.keys():
exec '%s = include.context[%s]' % (i,repr(i))
x = x + 1
y = 2
return locals()
]]
The output is, as you might expect:
1
2
Note that there two things going on here, each of which can be performed
independently:
1. I pass locals() to rim.spi, and exec each of the variables into the
namespace of the included file.
2. I return locals() from rim.spi, and exec each of the variables back in
to the namespace of the including file.
That seems to work for me. (Remember to use the latest version of Spyce
v1.2.8). I hope that this addressed your question.
All the best,
Rimon.
On Wed, 18 Sep 2002, Teng Tiberius wrote:
>I'm now beginning writing a forum system in Spyce, named SpyceBB (hope
>there's nobody doing same work as me ;) and encountered some problems ...
>
>I want a flat namespace like it in PHP, so I mostly use
>[[.include="somefile"]] to load my (forum-specific) libraries. By using
>'debug' module, I had a happy time developing and planned that after I
>finished writing the project, I simply removes that 'debug' to make my
>forum fly. I realize that it's memory-consuming (each file will have their
>own copy of compiled libraries) but I think that's fine with me.
>
>I encountered the problem when I want to make a 'configuration' file. Such
>file would change by the forum administration script itself and have to be
>reloaded when it changes. If I use [[.include]] style, it won't be reloaded
>if I remove 'debug' module. But if I use include.spyce() to load it, then I
>can't hardcode nor easily determine it's relative path to current file.
>Because I made every script to share a common main-include file by
>[[.include]] and I put that line inside the main-include file, therefore
>include.spyce() will think the current path is "the path contained the file
>which is including the main-include file", not "the path contained the
>main-include file". Since I can't import a python file in the same path of
>a .spy file, and I don't want to put something into user's Python22/Lib
>folder, so reload() won't work.
>
>Rather long story ^^; I'll summerize it:
>1. in main.spy, [[.include="inc-a.spy"]] will make statements inside
>inc-a.spy think it's in the same folder as main.spy, which is causing
>problems.
>2. in main.spy using [[include.spyce("inc-a.spy")]] can't make inc-a.spy
>share the same namespace as main.spy without further really dirty works.
>
?
>
>Hope this problem can be solved, Thanks in advance.
Dear Spyce users list members,
On the Spyce webpage I mentioned that this list would have 1-2 message per
week. Since Spyce has grown increasingly popular, I do not think that will
ever be true again.
Is there an interest on this list in creating an annoucements list? In
other words, are there people on here that would prefer to receive only
the Spyce release annoucements and other infrequent messages of
importance?
Please respond in private.
Thanks,
Rimon.
Hi James,
>I will have to overide the init method of the spyceModule class to do
>this won't I? I see the session module does this:
Exactly. The module.init method gets called at the point of the
[[.import]] directive, with any arguments and keyword argments. In fact,
if the [[.import]] looks like:
[[.import name=foo args="1, 2, 3"]]
then you will get a call:
foo.init(1, 2, 3)
All the Spyce compiler does is take the args string and insert it inside:
foo.init(...).
The rest is done by Python, including the syntax checking and the
parameter at runtime!
Moving onto the specific example:
...
Yes, and a little bit more. It's able to deal with something like the
following (taken from examples/autosession.spy):
[[.import name=session args="'session_dir', '/tmp', auto=10"]]
The handler is session_dir. The '/tmp' parameter (but it could also be
more than one parameter) is passed to initialize session_dir handler.
And the auto parameter (or parameters, that's the tricky part), if it
exists is/are passed to the autoSession() method. Now, auto could either
be just an integer, or a tuple (sec, [method], [name]). If it's just an
integer, I wrap it up as a tuple first, before passing it on. Basically,
lots of junk that specific to the flexible syntax that I came up with for
import the session module. You don't have to worry about all that.
Just know that the args string is pasted verbatim inside a call to
module.init(...). And, if there is a syntax error, due to mismatched
parameters and such, Python will pick it up. The standard Python parameter
assignment rules apply. Hence we get the *, ** functionality for free, and
it's useful in creating flexible init methods. Note that in the case of
[[.import name=foo]]
you WILL get a call:
foo.init()
The default method that is inherited from spyceModule will accept any
number of arguments and does nothing. I hope that helps.
All the best,
Rimon.
Thanks Rimon,
I must have some kind of weirdness then:
OS X Jaguar 10.2 (ah, yes the bumpy upgrade, but otherwise my Spyce on
X experience has been good too.... FYI)
spyce v1.2.7, by Rimon Barr: Python Server Pages, I just upgrade today,
but I had a similar problem on 1.2.4
Python 2.2 (#1, 07/14/02, 23:25:09), the 10.2 supplied python, though,
just to confuse the issue I have 2.1 installed under FInk (open source
debian style packages for OS X, but I am 99% sure that has nothing to
do with it, 2.1 is actaully called python2.1
cheetah -v 0.9.14
I have it setup with the proxy configuration, I didn't want to tackle
ModPython on OS X.
I must have something messed in Cheetah or something... I am not really
familiar enough with Cheetah either, but I do like the ability to use
both Cheetah and Spyce output.
jms.
On Monday, November 18, 2002, at 10:27 PM, Rimon Barr wrote:
>
>,
Another question: I am trying to get back at a rewrite of the user
module I posted a while back and one of the suggestions was that some
of the things I was hard coding be passed in via keyword arguments when
initializing the module.
I will have to overide the init method of the spyceModule class to do
this won't I? I see the session module does this:...
(Sorry Rimon, you might have even given me some suggestions about how
to this a couple of weeks ago but I lost about weeks mail on a bumpy
upgrade to my main computer, part of the reason why it has taken me a
bit to get at this...)
jms..
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/spyce/mailman/spyce-users/?viewmonth=200211&viewday=19 | CC-MAIN-2017-09 | refinedweb | 2,366 | 65.83 |
The QTextList class provides a decorated list of items in a QTextDocument. More...
#include <QTextList>
Inherits QTextBlockGroup.ListFormat and QTextCursor.
Makes the given block part of the list.
Returns the number of items in the list.
See also isEmpty().
Returns the list's format.
See also setFormat().
Returns true if the list has no items; otherwise returns false.
See also count().
Returns the i-th text block in the list.
See also count() and itemText().
Returns the index of the list item that corresponds to the given block.
Returns the text of the list item that corresponds to the given block.
Removes the given block from the list.
Removes the item at item position i from the list.
Sets the list's format to format.
See also format(). | http://doc.trolltech.com/4.0/qtextlist.html | crawl-001 | refinedweb | 128 | 81.39 |
About a week ago I had written a tutorial around using the HERE Weather API in a NativeScript with Angular application. This was an extension to my popular tutorial which focused on strictly Angular with the HERE Weather API. However, if you’re a NativeScript developer, you probably know that Angular isn’t the only way to do business.
In this tutorial we’re going to explore using the HERE Weather API in NativeScript, but this time using Vue.js and simple JavaScript.
To get an idea of what we want to accomplish, take a look at the following image:
In the above image you’ll notice a nicely formatted list view with the 7 day local forecast. This is an application that works on both Android and iOS because of NativeScript, however it was made possible with Vue.js and the HERE Weather API.
Create a New NativeScript with Vue.js Project
The first step towards being successful with this project is to create the project and install any of the dependencies. Assuming that you’ve got the Vue CLI installed as well as the NativeScript CLI, execute the following:
vue init nativescript-vue/vue-cli-template ns-vue-project
The above command will create a new project. When asked, go ahead and choose the defaults.
After creating the project, we technically don’t need anything else. However, in an effort to make our application as slick as possible, we’re going to download a dependency to format our date and time information.
Navigate into your project directory and execute the following command:
npm install moment --save
The above Moment.js library is pretty much the standard when it comes to working with dates and times in JavaScript. Again, it isn’t absolutely necessary, but it will help us in the future.
Now we can start adding our code to interact with the HERE Weather API.
Communicate with the HERE Weather API using HTTP
Because of how Vue.js works, we’re able to have all of our component code in the same file. Rather than introducing new complexity, we’re going to leverage a component that already exists rather than create a new one.
Open the project’s app/components/App.vue file and add the following boilerplate code:
<template> <Page> <ActionBar title="TRACY, CA"/> <GridLayout columns="*" rows="*"> </GridLayout> </Page> </template> <script > import * as http from "http"; import * as moment from "moment"; export default { data() { return { weather: [] } }, mounted() { }, methods: { }, filters: { } } </script> <style scoped> ActionBar { background-color: #53ba82; color: #ffffff; } .message { vertical-align: center; text-align: center; font-size: 20; color: #333333; } </style>
In the above code you can see that we’ve imported the NativeScript HTTP module which we’ll be using for consuming data from the REST API. We’re also importing Moment.js which we’ll use later.
The goal here is to get weather information and store it in a
weather array to be used in the
<template> area. To do this, let’s focus on creating some
methods with Vue.js.
Since the HERE Weather API requires quite a few query parameters, instead of just concatenating them directly, we’re going to create a helper function for the job:
encodeQueryParameters(params) { const encodedParameters = []; for(const key in params) { if(params.hasOwnProperty(key)) { encodedParameters.push(key + "=" + encodeURIComponent(params[key])); } } return "?" + encodedParameters.join("&"); }
If you’ve used JavaScript for a while, you’ve probably seen some variation of the above function a thousand times. We’re just accepting an object and encoding it to be compatible query parameters.
We can create a
getWeather method that makes use of it:); }); },
We’re constructing our parameters object based on the HERE Weather API documentation. When we have our object, we are encoding it to query parameters and using it in a
getJSON request. A lot of information comes back, but we’re only storing the forecast information.
To get an idea of what our methods look like completed, they might look like this:
methods: {); }); }, encodeQueryParameters(params) { const encodedParameters = []; for(const key in params) { if(params.hasOwnProperty(key)) { encodedParameters.push(key + "=" + encodeURIComponent(params[key])); } } return "?" + encodedParameters.join("&"); } },
We probably want to load the weather information when our application loads. To do this, we can make use of the
mounted lifecycle event in Vue.js. To make use of this event, include the following:
mounted() { this.getWeather("APP-ID-HERE", "APP-CODE-HERE", { latitude: 37.7397, longitude: -121.4252 }); },
Notice in the
mounted event we are only calling the
getWeather function that we had previously created. Make sure to swap the app id and app code values with those found in your HERE Developer Portal.
In theory, we now have weather information to work with. It is time we actually render it on the screen. We’ll want to create a
ListView in our
<template> block like this:
<template> <Page> <ActionBar title="TRACY, CA"/> <GridLayout columns="*" rows="*"> <ListView for="item in weather" class="list-group"> <v-template> <GridLayout class="list-group-item" rows="auto, auto" columns="50, *"> <Image : <Label row="0" col="1">{{ item.highTemperature }}C</Label> <Label : </GridLayout> </v-template> </ListView> </GridLayout> </Page> </template>
There are a few things to notice in the above XML. First you’ll notice that we are only including three pieces of data from our response. We’re displaying the weather icon, the highest temperature of the day and the timestamp. Second you’ll notice that we are adding formatting to our list rows with a
GridLayout component.
If we were to run the application, it would work, but the timestamp wouldn’t look too attractive. Also, if you’re in the United States like I am, you’re probably more familiar with Fahrenheit as the measurement. We can fix this.
Transform API Responses with Vue.js Filters
The best way to do transformations in the XML is to make use of Vue.js
filters which act as pipes in other technologies. Essentially, we provide a value to the filter and it is transformed into another value.
Let’s take a look at the following two
filters:
filters: { fahrenheit(value) { return ((value * (9 / 5)) + 32).toFixed(2); }, pretty(value) { return moment(value).format("MMMM DD, YYYY"); } }
In the above code we have a
fahrenheit filter and a
pretty filter. The
fahrenheit filter will apply a formula to convert the temperature to fahrenheit and the
pretty filter will use Moment.js to format our date into something more human readable.
To use our filters, we can make some adjustments to the XML:
<GridLayout class="list-group-item" rows="auto, auto" columns="50, *"> <Image : <Label row="0" col="1">{{ item.highTemperature }}C / {{ item.highTemperature | fahrenheit }}F</Label> <Label : </GridLayout>
In the above code, notice that we are using a pipe character and the filter name. When we do this, we are taking the original value, piping it into our filter, then displaying the result of the transformation.
Conclusion
You just saw how to use the HERE Weather API in a NativeScript project that used Vue.js as the core framework. The HERE Weather API does a lot more than just 7 day forecast information, even though it was the focus of this example. As long as your computer is properly configured, you’ll be able to build your project for both Android and iOS with NativeScript.
If you’re more familiar with Angular, you can check out my NativeScript with Angular version here. | https://developer.here.com/blog/show-the-weather-forecast-in-a-nativescript-with-vue.js-ios-and-android-application | CC-MAIN-2019-35 | refinedweb | 1,237 | 55.74 |
Extend built-in Python collections with LINQ-for-objects style methods
Extend built-in Python collections with LINQ-for-objects style methods
Description
The library extends built-in Python collections with methods from Robert Smallshire’s asq. Adding methods to built-ins isn’t officially allowed, but it’s possible to do this in CPython (both 2.x and 3.x) using a hack described in the corresponding section below.
For example:
>>> import dontasq >>> >>> [1, 2, 3].select_many(lambda x: (x, x ** 2)).to_tuple() (1, 1, 2, 4, 3, 9) >>> 'oh brave new world'.split() \ ... .where(lambda word: len(word) >= 5) \ ... .select(str.capitalize) \ ... .to_list() ['Brave', 'World']
In some cases, this style helps to write functional-esque code that is more clear than code with map, filter and generator expressions: there’s no confusion with brackets, and methods are applied in the natural order.
Warning! dontasq uses undocumented CPython features. It’s not guaranteed that this features will be maintained in the future Python versions.
Details
During import, dontasq looks for classes in the built-ins namespace, collections and itertools modules. If a class is an iterable and isn’t a metaclass, the library will append all public methods of asq.queryables.Queryable to it in such a way that a method call:
>>> instance.select(lambda x: x * 2)
Will be equal to:
>>> Queryable(instance).select(lambda x: x * 2)
So the methods will be added to classes such as list, str, collections.OrderedDict, or itertools.count. You can find a list of all Queryable methods and their description in asq documentation.
If a class already contains an attribute with a coinciding name (e.g. str.join and list.count), this attribute won’t be replaced.
Of course, you’re able to import other asq modules when using dontasq:
>>> import dontasq >>> from asq.predicates import * >>> >>> words = ['banana', 'receive', 'believe', 'ticket', 'deceive'] >>> words.where(contains_('ei')).to_list() ['receive', 'deceive']
If you want to patch classes from another library, you can use methods dontasq.patch_type and dontasq.patch_module:
>>> import bintrees >>> import dontasq >>> >>> dontasq.patch_type(bintrees.AVLTree) >>> >>> dictionary = {1: 'Anton', 2: 'James', 3: 'Olivia'} >>> bintrees.AVLTree(dictionary).select(lambda x: x * 2).to_list() [2, 4, 6]
You can find other examples in “tests” directory.
Adding methods to built-ins
The following approach is found in this question on StackOverflow.
Officially, you can get only a protected (read-only) instance of built-ins’ __dict__. The trick is that in CPython this instance contains a reference to an original (modifiable) dictionary that can be tracked with gc.get_referents function.
For example, we can add select method to built-in list (unlike dontasq, it’s non-lazy in this example):
>>> import gc >>> gc.get_referents(vars(list))[0]['select'] = lambda self, func: list(map(func, self)) >>> >>> [1, 2, 3].select(lambda x: x * 2) [2, 4, 6]
Another possible way is to use forbiddenfruit library that interacts with ctypes.pythonapi module. The both approaches stably work on both Python 2 and 3, but restricted to CPython only.
Installation
You can install the library using pip:
sudo pip install dontasq
Or install a previously downloaded and extracted package:
sudo python setup.py install
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/dontasq/ | CC-MAIN-2017-34 | refinedweb | 546 | 59.19 |
Local History Operations for Subversion
References:
Shelving and Checkpointing Dev
Shelving Command-Line UI Design
issue SVN-3625 "Commit shelving"
issue SVN-3626 "Commit checkpointing"
SavePoints wiki page
The Problem
This is the problem we are looking to solve. We will use this to determine the scope of design and implementation.
Shelving
While developing one change, you need to stop and work on an urgent fix or you want to commit a quick and easy change or try a different approach in the same code. You need to store the unfinished work and return to it later. Existing options: server-based branches, patch files, extra Working Copies.
Priorities: fast, offline.
Checkpointing
While developing a change, you reach a state which you want to save. A test passes or a subtask is complete, and the next thing you do might break it. If so, you will want to roll back to this state. When the work is finished, you will commit it as usual, or if it did not work out you may discard it all.
Priorities: fast, offline.
Future extension possibilities:
roll back and forth (undo/redo) along the series, e.g. to "bisect" for a bug
checkpoint automatically, e.g. before 'update' (like auto-versioning, auto-save, undo systems)
view your working state as a diff against the last checkpoint, instead of against the original base version
The Solution
Shelving
One-click patch management on top of 'svn diff' and 'svn patch'.
similar to "git stash"
backward-compatible extension to WC format
(old clients still work, just not seeing the shelves)
supports exactly the same kinds of change as 'svn patch' and 'svn diff'
we will extend these later to cover currently missing kinds of change
Functions:
shelve: save a WC diff as a patch and revert it from WC
unshelve: apply specified patch to WC and delete the patch
list shelves and the files that they affect
delete a shelf
Compared to manual patch management:
one-click simplicity
don't need to choose a filename or remember where it is
still can't save & restore WC base state (in v1)
Future upgrades:
checkpointing, by storing multiple versions of each shelf
supporting the initially unsupported kinds of change (e.g. binary content, copies, moves, directories)
integration with the "changelist" feature
A note about "reliability". 'svn diff' and 'svn patch' have historically been incomplete with well known omissions (for example: binary content, copies, moves, directories) and incompatibilities. Developing a 'shelving' feature based on diff and patch will force us to adopt the mindset that diff and patch must interoperate reliably, and so fix those deficiencies. The result will be that using 'svn diff' and 'svn patch' manually will then be a reliable solution on its own for those who have reason to continue using it. The additional 'shelving' user interface will remain an added convenience.
Checkpointing
Simple management of a series of versions of a patch. Each patch version captures the WC state relative to the original WC base revision. The kind of checkpointing initially described in issue SVN-3626 "Commit checkpointing". Accessed by new 'svn' commands.
Aim: to streamline the manual method, which I use myself, of using 'svn diff' and 'svn patch' to develop successive versions of a patch, named 'feature-v1.patch', 'feature-v2.patch', etc.
Main functionality:
save the WC modifications as a new version of a shelf (don't revert);
roll back to an intermediate state and re-work from there;
discard all versions of the patch.
To roll back to an intermediate state, the user will first 'revert' the modifications currently in the WC and then use a 'restore' command to apply a chosen version of the patch.
The user can use the regular 'commit' functionality to commit the final version of the work, or can restore an earlier version and commit that.
Existing features (such as diff) will not directly act on checkpoints. All existing commands operate against the original base revision. Especially:
'commit' commits current WC local mods as usual
('commit' offers to discard all the checkpoints?)
'update' updates the WC as usual
'update' does not rebase or do anything special to checkpoints
'revert' reverts to the original base
Key points:
key benefit: roll back to a checkpoint
key drawback: cannot (initially) view current work against last checkpoint
backward-compatible extension to WC format
(old clients still work, just not seeing the checkpoints)
Feature/Benefit Matrix; Comparison with Existing Options
* Note: "incremental re-build" means it touches only the relevant source files in the working copy, so in a typical compiled language build system only the modified files would be re-compiled.
* Note: "Automatic checkpoint" is called "Destructive command rollback" in "Design: SavePoints" [5].
Role Models
With Shelving, we are catching up with a feature that most current VCSs already provide. We should make it easy for users to apply what they have learnt in those systems, and avoid needless differences. We should also support Subversion's unique characteristics such as directories being versioned objects.
Headings are linked to corresponding documentation.
Stashing can also be achieved in a DVCS, in general, by creating a local branch and committing the local change there and then switching back to the previous branch; later being able to merge the change or switch back to it and (depending on the system) throw away that commit.
The Design: Shelving & Checkpointing (for Subversion 1.11?)
(For earlier versions, see Shelving-v1 in Svn-1.10.)
A shelf is like a set of changes moved out of the WC into a special "shelf" storage area.
Saving a checkpoint is like creating a new shelf that is related to a previous one, having the same name and a different version number.
Supports working on multiple independent change-sets at the same time, by specifying the WC path(s) to be saved, as long as each WC path only belongs to one change-set at a time.
Functionality
Shelving operations:
shelve
move selected changes from WC to a named shelf
reverts the successfully shelves from the WC
unshelve
copy changes from specified (or newest) shelf to WC
can apply to any revision or branch
list shelves
delete a shelf
Checkpointing operations:
save a new checkpoint
svn shelf-save NAME [PATH...]
similar to 'shelve' except doesn't revert the working copy
restore an older checkpoint, discarding all newer versions
svn shelf-restore NAME [VERSION]
assumes the working copy has already been reverted
similar to 'unshelve' except can specify an older version
list the versions of a shelf
svn shelf-log NAME
output a shelf version as a patch
svn shelf-diff NAME [VERSION]
Other:
- optional log message (and other revprops) per shelf
- shelves stored in WC metadata dir '.svn/shelves/'
(The command-line syntax shown here is just for illustration.)
Implementation
- in libsvn_client
- supported in 'svn' command-line UI
- supported in TortoiseSVN (for Windows), Cornerstone (for Mac)
Kinds of change that can be shelved
Shelving and Checkpointing Commands
Command-Line UI Design:
- see Shelving Command-Line UI Design [2]
Shelving and Checkpointing together have the following generic interface. X is a shelf name.
Commit Log Message
A log message, and any other revision properties, can be attached to a shelf (not to each version).
Discussion
Ability to include a short description, or a longer commit log message, could be helpful both per shelf and per checkpoint.
In some situations a user will want to attach a carefully written log message to a shelf. In other cases, a user will want to quickly shelve or checkpoint their current working state without thinking about a description. For checkpointing, this would be rather like auto-save in a word processor -- and in a GUI could be performed automatically based on time intervals or before/after certain events, even as far as checkpointing before/after every svn mkdir/delete/move/copy, etc.
We need to be prepared to support both styles of working. A shelf may very well contain both some carefully constructed checkpoints (with log messages) and many of the auto-save kind (without, or with simple auto-generated messages). Therefore we should allow a log message but also make it easy for the user to distinguish checkpoints where no message was given. To help with the latter, we can display metadata such as the date (or age) of the checkpoint and a short summary of what changes it contained. (The command-line client prototype currently does that.)
If a user stores a big, carefully written log message in a shelf, then they will want an easy way to transfer this to the final commit log message. Until that is made easy, the UI should perhaps encourage the user to write only a short message.
Path spec [PATH...]
- applies only to 'save' commands (shelve, checkpoint save)
- defaults to "." like in most svn commands
- is restrictive (restricts operation to PATH...)
- is not tracked (the shelf doesn't remember what top-level path(s) you specified, or other associated inputs, it only remembers which individual paths had changes)
- clashes (same path in more than one applied patch) are not managed
Extensions to Consider
These possible extensions are not supported initially.
allow showing a shelf's content -- like 'svn log [-v] [--diff]', 'svn status', 'svn diff [--summarize]'
shelve: if no name given, automatically generate a name (so more like 'git stash')
use shelf's log message when committing
see the "Commit Log Message" discussion section above
consider allowing restricting paths on 'apply' commands
when checkpointing, warn if PATH... excludes any paths that were in the previous version
- once the base state is recorded: warn or otherwise try to avoid accidentally unshelving to a different branch or unrelated path
Roll Forward, as in Undo/Redo
As a starting point, rollback is destructive, deleting versions newer than the target version. As an enhancement, it could be made to keep the newer versions and allow rolling forward to them. It could operate like the 'undo stack' model commonly found in editing applications, where roll-forward (often named 'redo') is possible up until a different change is saved to the stack, at which time the possibility is lost.
Rebasing Checkpoints
There are cases where it is potentially desirable to be able to rebase a series of checkpoints when updating (pulling in new changes from the repository). One case where this would be useful is if the user updates, goes offline, then wishes to roll back to a checkpoint saved before the update. Another is if the user wishes to make separate commits from several checkpoints in the series, some of which were saved before the last update; but that scenario is not a supported use case in this design.
In trunk-based development usually other people's changes have to be pulled before we can commit. In branch-based work flows that is uncommon.
Whenever we try to restore a checkpoint that was made against an older base, there is a chance that the patch application will run into conflicts. If and when we upgrade from traditional patch application to 3-way merge, conflicts would be reduced, but still possible. Rebasing a series of checkpoints would involve merging once into each checkpoint, with the possibility of conflicts at each step.
As conflicts require tedious manual recovery, these scenarios are best avoided as far as possible.
Rebasing a single checkpoint needs no special support. It is achieved by applying the checkpoint to the WC and then running 'svn update'. The result can then be saved as a new checkpoint or committed.
Therefore this potential extension is low priority.
Integrate Shelving with Changelists
I hate to add complexity without simplifying something at the same time. Considering the relationship between shelves and changelists:
a changelist is a named set of file-paths in the WC
a shelf is a named set of changes that is not currently applied to the WC
Integrate them like this:
shelves and changelists share the same namespace
shelving means converting a changelist to a shelf of the same name
- or, if the desired changes are not already managed in a changelist, specify them explicitly
unshelving means converting a shelf to a changelist of the same name
Benefits
- managing shelves is easier:
- after unshelve, even if there are other changes elsewhere in the WC, a changelist will remember which changes belonged to that shelf, so you can later shelve or "checkpoint" it without having to specify which files to include
clear and simple relationship with no overlap
changelists remain backwards-compatible
Main issues
a changelist can include unmodified paths:
should a shelf also include unmodified paths?
a path can appear in multiple shelves, but only in one changelist:
what to do when unshelving if a path clashes?
any extensions should apply uniformly to both shelving and changelists
if a shelf supports a log msg, a changelist should support a log msg too; this would be a good enhancement for changelists anyway even without shelving
Role models
changelists in IntelliJ IDEA (are unified across svn, git, hg, etc.)
changelists in Perforce (are new or pending or shelved or submitted)
Extensions / Not Supported Initially
When committing changeset X, Subversion could (offer to) delete the shelf X.
[with roll forward, as in undo/redo] Automatically save a new checkpoint before rollback.
GUI Considerations
GUI priorities tend to be a little different from a CLI.
APIs that do the job simply and reliably
progress indication and cancel, for any long-running ops
hopefully we won't have any long-running ops
ability to undo
we don't have to implement undo, just provide enough hooks so caller can
Complete WC State Shelving
A key concern will be to have APIs that do the job simply and reliably. Such as: ability to shelve a WC state whatever state it's in (all the odd states like unresolved conflicts, etc.) and restore to exactly the same state.
We should have two complementary APIs:
a "shelve" API should visit the WC reporting absolutely everything about the state, in such a way that the caller can capture that state;
a "diff" API should report the subset of this that is committable;
an "unshelve" API should be able to recreate any such state, using input entirely provided by the caller
a "patch" API should accept the subset of this that is committable.
To what extent do such APIs exist?
We should write automatic round-trip testing for diff-&-patch and for status-&-modify.
For states that we can't shelve, a GUI wants to know in advance that this is the case (to grey-out the button), rather than the operation to error out part way through. So we want:
an API to efficiently tell whether the WC state can be shelved (or why not)
Existing Issues to Overcome
... are tracked in "commit shelving".
Glossary of Terms
shelf: a place of storage, within WC metadata, for: a time-ordered series of change-sets; and metadata that applies to the shelf as a whole, modifiable at any time, including a "log message"
save: to copy a change-set from WC working state to a shelf (reverting it from the working state)
shelve: to move a change-set from WC working state to a shelf (reverting it from the working state)
unshelve: to copy a change-set from a shelf into the WC working state; implies choosing the newest version of the change-set on that shelf but can take any version
restore: to copy a change-set from a shelf into the WC working state; implies choosing an older version of the change-set on that shelf but can take any version
version: one of the change-sets in a shelf; versions are assumed to be different (e.g. improving) implementations with the same intended purpose
change-set: a set of changes that Subversion could potentially record in a single revision (changes to files, directories, properties); sometimes refers also to associated revision metadata (log message, other revision properties).
A change-set may be shelved, unshelved, presented as a diff (patch file), etc.
patch: similar to change-set; implies formatted as a patch file
change: loose term, referring to a change-set or any change that a change-set could contain
changelist: similar to change-set; implies the existing 'svn changelist' feature
Subversion's existing 'changelist' should grow into the full 'change-set' concept.
checkpoint, savepoint: non-preferred term for (noun) "version", (verb) "save"
'savepoint' may be a little better than 'checkpoint' -- better associated with the command verb 'save' and does not share the prefix 'check' of 'checkout' nor the abbreviation 'cp' of 'copy'.
Julian Foad, Assembla, 2017 | https://cwiki.apache.org/confluence/display/SVN/Shelving+and+Checkpointing+Dev | CC-MAIN-2021-04 | refinedweb | 2,766 | 53.65 |
Azure PowerShell :: Managing Blob Storage
Have you turned into a skeleton, waiting for an object-oriented shell on Linux, that is easy to use, but is incredibly powerful and extensible? Have you been waiting to run PowerShell on Linux? Do you love Docker software containers? If so, then don't miss this awesome introduction to building your own custom Docker container image, that runs PowerShell natively on Ubuntu Linux!
The new, native PowerShell on Linux solution is called PowerShell Core, and sits on top of the Microsoft .NET Core framework that was released on June 27th this year!
During this information-packed video, we will:
Download the Dockerfile from the video, and build your own PowerShell Core Docker image!
Cheers,
Trevor Sullivan
Microsoft MVP
Docker Captain
Rebuilding the docker image with --tag creates yet another image taking up more space on the hard drive. Is there a way to build with --tag on the first build pass?
Hello Trevor,
Great video as always! I was wonder if you have played around yet with PowerShell for Linux and tried importing the Azure modules? While I am fully aware of Azure CLI, it is nice to be able to have options available in Linux.
-Lance
Can I use Vim instead of Visual Studio Code?
@lavermil: The Azure modules are demonstrated here Managing Azure using PowerShell on Linux
Great video! Thank you for sharing.
Forgive my ignorance... but does this give me a portable version of PowerShell that I can run anywhere, say on WES2009?
If not, how can I make PowerShell portable so that I can run it without installing anything else on WES2009?
Thank you.
@garrirt: Hi there -- I'm not familiar with WES2009. What is that? The purpose of this video is to show how to run PowerShell natively inside Docker containers on Linux.
PowerShell hasn't really been "portable" until just recently, so the chances of porting it to different operating systems is fairly restricted at present. As the .NET Core framework evolves, PowerShell will evolve along with it, and will be able to run on more and more platforms.
Cheers,
Trevor Sullivan
WES2009 = Windows Embedded Standard 2009 = Embedded WinXP SP3
Would like to run PowerShell w/out installing the supporting environment.
Any ideas?
If you are getting a key error when using the docker file it is likely that you are behind a firewall.
Replacing this line:
&& apt-key adv --keyserver apt-mo.trafficmanager.net --recv-keys 417A0893 \
With this line:
&& apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 417A0893 \
Will allow your request to com on port 80.
Thanks for the awesome video and build process.
Excellent overview! Great job putting it together, and thanks for providing the source for the dockerfile.
I just found a good article by Jessica Deen on running AzureRM modules on Ubuntu here ()...
It works inside PowerShellCore, and makes for a nice additional step at the end of your tutorial.
Thanks!
bliz
@Jacobjs01: So the question is whether the syscalls that Docker needs (for chroot and namespaces, among other things) were implemented or not. The answer is to that is likely "no". Docker requires fairly sophisticated (and Linux-specific) functionality for process and resource management, and process isolation. While it is probably possible to replicate all this on Windows, it would be a lot of work, and since the goal of this Windows feature seems to be running Linux userspace programs, it seems unlikely they did all the work (and kept it secret). | https://channel9.msdn.com/Shows/msftazure/Run-PowerShell-Natively-on-Linux-with-Docker | CC-MAIN-2018-30 | refinedweb | 584 | 64 |
Related
Tutorial
Passing Multiple Props to a Vue.js developers using component-based architectures, such as Vue’s and React’s, know that creating reusable components is hard, and most of the time you end up having a lot of props in order to make it easier to control and customize a component from the outside.
That’s not bad, but it’s true that passing lots of props can get a bit cumbersome and ugly. However, there’s a way for every Vue.js component style to cope with it.
Let’s take as an example the vuetify’s button component, one of the simplest ones. Say that we want to pass the same bunch of props in most cases:
<v-btn color='primary' href='' small outline block ripple > Hello Meat </v-btn>
It could make sense to have them in a separate file, let’s call it props.js:
export const buttonProps = { color: 'primary', small: true, outline: true, block: true, ripple: true, href: '' }
JSX and Render Functions
Since they give you more power and flexibility when it comes to rendering, it’s fairly easy to pass multiple props at once.
In a render function:
import { buttonProps as props } from './props.js'; export default { render: h => h( 'v-btn', { props }, 'Hello Meat' ) };
And in JSX:
import { buttonProps as props } from './props.js'; const data = { props } export default { render: h => <v-btn {...data}>Hello Meat</v-btn> };
Using a Vue.js template
What about using the Vue.js DSL (or template)? No worries, that’s also possible. All you need to do is to use the
v-bind directive. Given an object that you must define in the
data option of your component it will bind all props:
<template> <v-btn Hello Meat </v-btn> </template> <script> import { buttonProps } from './props.js'; export default { data: () => ({ buttonProps }) } </script>
With this trick you won’t need to fill your template with repeated props at several places in your app, while still being able to use the beloved template tag.
Wrapping Up
Passing multiple props to a component can be simplified using the examples mentioned in this article. This is especially useful for presentational and third party components that have lots of props.
Keep in mind that the examples used here are merely educational. If you want to stay DRY (Don’t Repeat Yourself) there could be better approaches depending on the specific case, such as creating your own wrapper components. | https://www.digitalocean.com/community/tutorials/vuejs-passing-multiple-properties | CC-MAIN-2020-34 | refinedweb | 408 | 62.58 |
This is the mail archive of the gdb@sourceware.org mailing list for the GDB project.
The Python scripting prototype is now available from the 'python' branch of the git repository at git://repo.or.cz/gdb.git and you can browse the code/changes at:;h=python At present, it allows to customize how the -var-evaluate-expression gets the string, for example, if 'v' is a variable in the program, of std::vector type, one can do: (gdb) -var-create V * v ^done,name="V",numchild="1",value="{...}",type="std::vector<int,std::allocator<int> >" (gdb) -var-set-pretty-printer V format_vector ^done (gdb) -var-evaluate-expression V ^done,value="[1,2]" (gdb) Here, format_vector is a name of Python function, which is defined in .gdbinit, like follows: python def format_vector (v): impl = gdb.value_element (v, '_M_impl') start = gdb.value_element (impl, '_M_start') finish = gdb.value_element (impl, '_M_finish') result = '[' current = start first = 1 while not gdb.value_equal (current, finish): if not first: result = result + ',' first = 0 result = result + gdb.value_string(gdb.value_dereference(current)) current = gdb.value_increment (current, 1) result = result + ']' return result def list_vector_children (v): return [("first", gdb.value_from_int(1)), ("second", gdb.value_from_int(15))] end here, 'python' is a new command that executes python code, and any function defined remain in python's namespace, and are available for use. The current problems: 1. The code exposing gdb values to python leaks like crazy. 2. The Python interface for values in procedural, and should be object-oriented -- with class 'value' that one can add, subscribe, etc. Internally, we now use integers to represent value*, and we should use properly define a new class in C. 3. The linking to python is basically hardcoded in makefile.in 4. The code for dynamically computing the children of varobj is incomplete. To build the code, you might need to change python2.5 and python25 strings hardcoded in Makefile.in to whatever version of Python you have. I don't expect the current code to be very useful, but since I've promised to publish it, here it goes. I intend to improve on points (1-4) above, and then it will be suitable for submission, hopefully soon. - Volodya | http://sourceware.org/ml/gdb/2008-02/msg00140.html | crawl-002 | refinedweb | 365 | 58.89 |
pty — Pseudo-terminal utilities¶
Source code: Lib/pty.py:
pty.
fork()¶).
pty.
openpty()¶
Open a new pseudo-terminal pair, using
os.openpty()if possible, or emulation code for generic Unix systems. Return a pair of file descriptors
(master, slave), for the master and the slave end, respectively.
pty.
spawn(argv[, master_read[, stdin_read]])¶
Spawn a process, and connect its controlling terminal with the current process’s standard io. This is often used to baffle programs which insist on reading from the controlling terminal. It is expected that the process spawned behind the pty will eventually terminate, and when it does spawn will return.
The functions master_read and stdin_read are passed a file descriptor which they should read from, and they should always return a byte string. In order to force spawn to return before the child process exits an
OSErrorshould be thrown.
The default implementation for both functions will read and return up to 1024 bytes each time the function is called. The master_read callback is passed the pseudoterminal’s master file descriptor to read output from the child process, and stdin_read is passed file descriptor 0, to read from the parent process’s standard input.
Returning an empty byte string from either callback is interpreted as an end-of-file (EOF) condition, and that callback will not be called after that. If stdin_read signals EOF the controlling terminal can no longer communicate with the parent process OR the child process. Unless the child process will quit without any input, spawn will then loop forever. If master_read signals EOF the same behavior results (on linux at least).
If both callbacks signal EOF then spawn will probably never return, unless select throws an error on your platform when passed three empty lists. This is a bug, documented in issue 26228.
Changed in version 3.4:
spawn()now returns the status value from
os.waitpid()on the child process.
Example¶
The following program acts like the Unix command script(1), using a pseudo-terminal to record all input and output of a terminal session in a “typescript”.
import argparse import os import pty import sys import time parser = argparse.ArgumentParser() parser.add_argument('-a', dest='append', action='store_true') parser.add_argument('-p', dest='use_python', action='store_true') parser.add_argument('filename', nargs='?', default='typescript') options = parser.parse_args() shell = sys.executable if options.use_python else os.environ.get('SHELL', 'sh') filename = options.filename mode = 'ab' if options.append else 'wb' with open(filename, mode) as script: def read(fd): data = os.read(fd, 1024) script.write(data) return data print('Script started, file is', filename) script.write(('Script started on %s\n' % time.asctime()).encode()) pty.spawn(shell, read) script.write(('Script done on %s\n' % time.asctime()).encode()) print('Script done, file is', filename) | https://docs.python.org/3.7/library/pty.html | CC-MAIN-2021-43 | refinedweb | 457 | 60.51 |
#include <hdate.h>
int hd_day
int hd_mon
int hd_year
int gd_day
int gd_mon
int gd_year
int hd_dw
int hd_size_of_year
int hd_new_year_dw
int hd_year_type
int hd_jd
int hd_days
int hd_weeks
libhdate Hebrew date struct
The number of day in the hebrew month (1..31).
The number of the hebrew month 1..14 (1 - tishre, 13 - adar 1, 14 - adar 2).
The number of the hebrew year.
The number of the day in the month. (1..31)
The number of the month 1..12 (1 - jan).
The number of the year.
The day of the week 1..7 (1 - sunday).
The length of the year in days.
The week day of Hebrew new year.
The number type of year.
The Julian day number
The number of days passed since 1 tishrey
The number of weeks passed since 1 tishrey
Generated automatically by Doxygen for libhdate C language from the source code. | http://www.makelinux.net/man/3/H/hdate_struct | CC-MAIN-2015-40 | refinedweb | 149 | 86.5 |
Stop the HAM
#include <ha/ham.h> int ham_stop( void ); int ham_stop_nd( int nd); int ham_stop_node( const char *nodename);
libham
The ham_stop() function instructs the HAM to terminate. The ham_stop_nd(), and ham_stop_node() functions are used to terminate remote HAMs. These are the only proper ways to stop the HAM.
The nd specified to ham_stop_nd() is the node identifier of the remote node at the time the ham_stop_nd() call is made.
The ham_stop_node() function takes as a parameter a fully qualified node name (FQNN). The ham_stop_node() function is used when a nodename is used to specify a remote HAM instead of a node identifier (nd).
Since the HAM and its "clone" the Guardian monitor each other, and re-spawn should the other fail, the HAM must first terminate the Guardian before it terminates itself.
In addition to the above, the HAM returns any error it encounters while servicing the request to terminate. | http://www.qnx.com/developers/docs/6.6.0.update/com.qnx.doc.ham/topic/hamapi/ham_stop.html | CC-MAIN-2018-09 | refinedweb | 151 | 71.75 |
Hot questions for Using Vapor in kitura
Question:
I know the question has been asked before and I agree with most answers that claim it is better to follow the way requests are made async with URLSession in Swift 3. I haver the following scenario, where async request cannot be used.
With Swift 3 and the ability to run swift on servers I have the following problem.
- Server Receives a request from a client
- To process the request the server has to send a url request and wait for the response to arrive.
- Once response arrives, process it and reply to the client
The problem arrises in step 2, where URLSession gives us the ability to initiate an async data task only. Most (if not all) server side swift web frameworks do not support async responses. When a request arrives to the server everything has to be done in a synchronous matter and at the end send the response.
The only solution I have found so far is using DispatchSemaphore (see example at the end) and I am not sure whether that will work in a scaled environment.
Any help or thoughts would be appreciated.
extension URLSession { func synchronousDataTaskWithURL(_ url: URL) -> (Data?, URLResponse?, Error?) { var data: Data? var response: URLResponse? var error: Error? let sem = DispatchSemaphore(value: 0) let task = self.dataTask(with: url as URL, completionHandler: { data = $0 response = $1 error = $2 as Error? sem.signal() }) task.resume() let result = sem.wait(timeout: DispatchTime.distantFuture) switch result { case .success: return (data, response, error) case .timedOut: let error = URLSessionError(kind: URLSessionError.ErrorKind.timeout) return (data, response, error) } } }
I only have experience with kitura web framework and this is where i faced the problem. I suppose that similar problems exist in all other swift web frameworks.
Answer:
Your three-step problem can be solved via the use of a completion handler, i.e., a callback handler a la Node.js convention:
import Foundation import Kitura import HeliumLogger import LoggerAPI let session = URLSession(configuration: URLSessionConfiguration.default) Log.logger = HeliumLogger() let router = Router() router.get("/test") { req, res, next in let datatask = session.dataTask(with: URL(string: "")!) { data, urlResponse, error in try! res.send(data: data!).end() } datatask.resume() } Kitura.addHTTPServer(onPort: 3000, with: router) Kitura.run()
This is a quick demo of a solution to your problem, and it is by no means following best Swift/Kitura practices. But, with the use of a completion handler, I am able to have my Kitura app make an HTTP call to fetch the resource at, wait for the response, and then send the result back to my app's client.
Link to the relevant API: | http://thetopsites.net/projects/vapor/kitura.shtml | CC-MAIN-2020-45 | refinedweb | 442 | 58.08 |
Write a recursive function that returns the number of 1's in the binary representation of N? I am not looking for code but what is the math equation or a hint of what I am trying to do mathmatically?
Write a recursive function that returns the number of 1's in the binary representation of N? I am not looking for code but what is the math equation or a hint of what I am trying to do mathmatically?
[Hint]
consider a function that checks a specified bit. That function can recursivley check all bits.
[/Hint]
How does this code work? Especially this line return (x & 1) + Power(x/2); What does this character do &?
#include<iostream>
using namespace std;
int Power(int);
int main()
{
int number;
cin>> number;
cout<< Power(number);
return 0;
}
int Power(int x)
{
if(x == 0)
return 0;
else
return (x & 1) + Power(x/2);
}[CODE]
>> What does this character do &?
& is the bitwise 'and', it will 'and' every bit individually...
ex)
1001 & 0011 == 0001
>> Especially this line return (x & 1) + Power(x/2)
this will return x & 1 (as described above) plus the result of calling Power(x/2). At some point x/2 will equal 0 and 0 will be returned to end the recursive cycle.
the code using Iteration is:
Code:/*assume the binary representation of the number will take M bits so we have an array called unsigned num[M]*/ #include <iostream.h> #define M 10 unsigned num[M]; void convert(unsigned) { for(int i=0;i<M;i++) { num[i]=(My_Number%2==1); My_Number/=2; } } int count(unsigned *a) { int x=0; for(int i=0;i<M;i++) if(num[i]==1) x++; return x; } int main() { unsigned r; cin >>r; for(i=0;i<M;i++) num[i]=0; convert(r); int xcount=count(num); cout <<xcount<<endl; return 0; }
There is some good information on bitwise operators in the Programming FAQ.
BITWISE HINTS:
Programmers will usually use hexadecimal when dealing with binary numbers / bit patterns. It's easier (for humans) to do binary-hex conversions than binary-decimal. C++ can use hex natively... binary takes a few more steps. And, it gets difficult (for humans) to read binary numbers when they get longer than 8-bits.
You can use the built-in Windows calculator to do decimal, binary, octal, and hex conversions.
Start -> Programs -> Accessories -> Calculator -> View -> Scientific | https://cboard.cprogramming.com/cplusplus-programming/43689-recursion.html | CC-MAIN-2017-13 | refinedweb | 402 | 54.83 |
Stephan van Hulst wrote:Probably because your default time zone is an hour ahead of Greenwich mean time. . . .
Mike Simmons wrote:Daylight savings certainly can be used inside the toString() method of Date - but any time zone labeled as GMT has absolutely no business using daylight savings time. Ever. So something is pretty screwed up there in how the JDK is printing the localized time.
Campbell Ritchie wrote:It was not called GMT, but BST = British Standard Time, back then.
Thu Jan 01 01:00:00 CET 1970
1970-01-01 00:00:00 GMT (+0000)
1970-01-01 00:00:00 UTC (+0000)
Campbell Ritchie wrote:
Stephan van Hulst wrote:Probably because your default time zone is an hour ahead of Greenwich mean time. . . .
I remember the epoch. I was around to watch. It was in fact at 1.00am, not midnight, because we had summer time (daylight saving time) all winter that year. It was pretty unpleasant, so in1971 we went back to GMT in winter.
Jesper de Jong wrote:Indeed strange that the hour is off by one while the time zone is GMT.
I tried the following on my system (JDK 1.7.0 update 3, 64-bit, on Ubuntu 11.10):
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Epoch {
public static void main(String[] args) {
Date zero = new Date(0L);
System.out.println(zero);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z (Z)");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(df.format(zero));
df.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(df.format(zero));
}
}
Output exactly as I'd expect (my local time zone is CET):
Thu Jan 01 01:00:00 CET 1970
1970-01-01 00:00:00 GMT (+0000)
1970-01-01 00:00:00 UTC (+0000)
1970-01-01 00:00:00 +00:00 (+0000)
Guy Hayward wrote: . . .
Apologies for being thick, but is this an explanation for the Date(0) being an hour wrong, or is it just banter?
. . . | http://www.coderanch.com/t/572738/java/java/epoch-wrong | CC-MAIN-2015-06 | refinedweb | 344 | 66.84 |
How to extend your SAP Marketing Integrations with Post-Exits in SAP Cloud Platform Integration (Part-2)
This blog is successor to this blog. So I highly recommend you to read it first before proceeding with this one especially if you don’t know the meanings of the notations (Message A, Message B etc) that we use in this blog. The predecessor blog explains all of them.
This part is going to focus on configuration activities solely.
Configuration Activities
1. Preparation of Integration Package “SAP Cloud for Customer Integration with SAP Marketing”
You need to log in to your SAP Cloud Platform Integration (CPI) tenant with your credentials. You need to navigate to “Discover” page and find the integration package “SAP Cloud for Customer Integration with SAP Marketing”.
After you copy it, your copy will be available in “Design” tab in your CPI tenant. These activities are already explained in the documentation of the standard integration package here. You need to read “Integration with SAP Marketing via CPI” or “Integration with SAP Marketing Cloud via CPI” documentations depending on your deployment.
When you check out the copied package in “Design” tab, you can spot our integration flow “Replicate Business Partner to SAP Marketing` in the list of “Artifacts” tab (Figure 1.5)
Figure 1.5: Replicate Business Partners to SAP Marketing integration flow
You need to configure the integration flow by following instructions in documentation of the standard integration package.
During the configuration of the integration flow, you need to take note of two points regarding our topic:
– You need to set `Extension Implemented” to “true” in integration flow configuration (Figure 1.6)
To do that, simple go to “More” tab and type “true” (all lower case) for the parameter named “Extension Implemented”. This indicates we have an extension scenario and standard integration flow should call our post-exit flow that we are going to create.
Figure 1.6: “Extension Implemented” parameter
– You need to note down address of Post-exit flow because it will be really important during the design of our Post-Exit Flow.
To find out the address of Post-Exit reference, you need to go to “Receiver” tab and pick “BusinessPartnerReplicationPostExit” from drop-down list for “Receiver” parameter. Address should appear like in the Figure 1.7.
Figure 1.7: Address of the Post-Exit Flow
After you’re done with other configurations for “Replicate Business Partner to SAP Marketing` you just need to save your settings.
That’s it, There’s nothing we should do about the standard integration flow from this moment on.Now we’re getting on to design our Post-Exit flow.
2. Designing Post-Exit Flow
To design our Post-Exit flow, we need to create an integration flow in our integration package. For Post-Exit concept to work properly, your standard integration flow has to be in the same CPI tenant with your Post-Exit flow. We’re going to create our Post-Exit integration flow in the same integration package with our standard integration flow, so this prerequisite will already be fulfilled.
To create our Post-Exit flow, you can follow below screenshots (Figures 1.8 – 1.10)
Figure 1.8: Editing standard integration package
Figure 1.9: Creating Post-Exit Integration Flow
I normally give the same name as original standard integration flow and add “Post Exit” as a suffix. This way our post-exit flow gets listed right after original standard integration flow in the list of “Artifacts” tab in our integration package. You can easily spot your Post-Exit flows if you stick with this namespace pattern.
Figure 1.10: Maintaining information for your Post-Exit Flow
Finally click “OK” to save your Post-Exit integration flow.
2.1. Defining Process Adapter and Message Mapping
Now we’re going to design an integration flow like shown in Figure 1.2 in predecessor blog
Let’s start with “Process Direct” adapter. You can follow the screenshots below for the instructions (Figures 1.11 – 1.14)
Select “Connectors” from left lane menu and click on “Sender” box and draw a line to “Start” icon with drag&drop
Figure 1.11: Connect “Sender” to “Start” by drag6drop
Figure 1.12: Selecting ProcessDirect as “Adapter Type”
Now, here’s very important. On “Connection” tab, for the “Address” field, you need to type down the exact address you noted in Figure 1.7
Figure 1.13: Defining address for Process Direct adapter
You can optionally externalize this parameter so that you can also maintain this address while configuring the Post-Exit flow.
Figure 1.14: Externalizing address parameter
Now we need to create a message mapping for our own mapping. For instructions, you can follow screenshots below (Figures 1.15 – 1.19)
Figure 1.15: Defining mapping – 1
Figure 1.16: Defining mapping – 2
Figure 1.17: Defining mapping – 3
Figure 1.18 Naming your mapping
Figure 1.19: Defining mapping -4
We added required elements to our Post-Exit flow. Now we need messages (Message A, Message B and Message C) to perform our own mapping.
2.2. Getting Extended Metadata of C4C SOAP Service (Message A)
The creation of custom field (ZZMKTS4ID) and enabling it for relevant web services in SAP C4C is not part of this blog. These administration activities are normally done by C4C consultants.
To download extended metadata of the SOAP service (including our custom field), log in to SAP C4C with your credentials. You need to find corresponding communication arrangement for your integration scenario and download WSDL from there. For our scenario, the communication arrangement is “Business Partner Replication to SAP Business Suite” for Marketing communication partner.
You can follow the screenshots below for instructions (Figures 1.20 – 1.22)
Figure 1.20: Finding relevant communication arrangement – 1
Figure 1.21: Finding relevant communication arrangement – 2
Figure 1.22: Downloading WSDL for the SOAP service
You can optionally rename your wsdl file after you download it.
2.3. Getting Standard Metadata of SAP Marketing OData Service (Message B)
This is relatively easy because it’s already available in standard integration flow. You can download it from “Resources” tab of “Replicate Business Partner to SAP Marketing” integration flow once you identify which schema you should download (Figures 1.23 – 1.26)
Figure 1.23: Identifying the schema – 1
Figure 1.24: Identifying the schema – 2
Figure 1.25: Identifying the schema – 3
Figure 1.26: Downloading the schema
Similar to Message A, you can also rename this service metadata.
2.4. Getting Extended Metadata of SAP Marketing OData Service (Message C)
This part is a bit tricky. Fortunately, I already created a blog series that explain how to create a custom field in SAP Marketing and enable it for required OData services. Furthermore it also explains how you can get the latest version of an OData service metadata (including our custom fields) from SAP Marketing. Kindly note that, though, our custom field (ZZ1_S4ID_ENH) and our OData service (CUAN_BUSINESS_PARTNER_IMP_SRV) differs from the ones explained in referred blog (But of course, the mentality is the same).
For how to create custom field and enable it for our OData services, click here to find out.
In order to get the latest metadata of OData services from SAP Marketing, we first need to create a connection between “End” icon and “Receiver” box and choose OData as Adapter Type in our Post-Exit Flow (Figures 1.27 – 1.31)
Figure 1.27: Getting the latest metadata of OData service – 1
Figure 1.28: Getting the latest metadata of OData service – 2
Figure 1.29: Getting the latest metadata of OData service – 3
Figure 1.30: Getting the latest metadata of OData service – 4
Figure 1.31: Getting the latest metadata of OData service – 5
From this moment on, the steps are quite similar to steps explained here in this blog. We just need that schema generated at the end with .XSD extension. If you follow the steps and get the latest metadata from OData service CUAN_BUSINESS_PARTNER_IMP_SRV, you will have a list like the following in “Resource” tab for your Post-Exit integration flow (Figure 1.32)
Figure 1.32: The latest metadata of OData service (Message C)
Since we got the Message C in place, you can now delete the connection between “End” and “Receiver” and even “Receiver” itself in our Post-Exit flow design.
We need to add Message A and Message B as well to our Post-Exit integration flow resources [We downloaded them in the steps “2.2. Getting Extended Metadata of C4C SOAP Service (Message A)” and “2.3. Getting Standard Metadata of SAP Marketing OData Service (Message B)” respectively]. You have to select WSDL files from your PC folders that you downloaded them to (Figure 1.33)
Figure 1.33: Adding Message A and Message B to resource list
If you don’t rename the WSDL files after you downloaded them to your computer, you should end up with resource list like below (Figure 1.34)
Figure 1.34: Final list of resources (Message A, B and C)
2.5. Performing Post-Exit Mapping
We’re all set so we can perform our mapping as we have got all the sources that we need. Once you select the mapping to go into details, you can follow below screenshots as they demonstrate you how to select your sources in order and how you can perform our mapping according to our scenario: We should map our custom field from C4C (ZZMKTS4ID) with our custom field from SAP Marketing (ZZ1_S4ID_ENH) in addition to existing mapped standard fields (Figures 1.35 – 1.44)
Figure 1.35: Adding source message
Figure 1.36: Picking up Message A
Figure 1.37: Adding second source message – 1
Figure 1.38: Adding second source message -2
Figure 1.39: Picking up Message B
Figure 1.40: Adding target source (message)
Figure 1.41: Picking up Message C
Figure 1.42: Final picture after message assignments
Figure 1.43: Mapping custom fields & existing standard fields
Figure 1.44: Saving changes
3. Deploying standard integration flow and Post-Exit flow
Figure 1.45: Standard integration flow & Post-Exit flow
We configured our standard integration flow before and now we finished the configuration of our Post-Exit flow. We need to deploy them to see them in action. We first need to deploy standard integration flow “”Replicate Business Partner to SAP Marketing” and then our Post-Exit flow “”Replicate Business Partner to SAP Marketing Post-Exit” (Figure 1.46)
Figure 1.46: Deployment of standard integration flow & Post-Exit flow
4. Testing Standard Integration Flow and Post-Exit Flow
Once our standard integration flow and Post-Exit flow are deployed, we are ready to test them. Log in to your SAP Cloud for Customer system with your credentials and make a small change for your test customer. In our case, our custom field should be updated with S/4 HANA number (Figure 1.47)
Figure 1.47: Update of test customer in SAP Cloud for Sales
You can check the payload of this change in SAP C4C via “Web Service Message Monitor” and you can also check if there’s any error for that outbound message. We can confirm that our custom field (ZZMKTS4ID) gets the value “0020000452” in the corresponding payload (Figure 1.48)
Figure 1.48: Checking outgoing payload in SAP C4C via Web Service Message Monitor
We should see our standard integration flow and Post-Exit flow are triggered successfully in CPI (Figure 1.49)
Figure 1.47: Trigger of standard integration flow and post-exit flow
And for the last step, we can check if our mapped custom field in SAP Marketing (ZZ1_S4ID_ENH) gets the right value. We can do it by searching our test customer via “Inspect Contact” app in “Data Stewardship” section in our SAP Marketing system. We need to check the origin data for SAP C4C for our test customer(Figure 1.48)
Figure 1.48: Checking incoming SAP C4C origin data via Inspect Contact app
Summary
That’s it! You should be able to extend your integration flows for your custom integration scenarios. With this new functionality;
- You don’t need to worry about later releases for your standard integration package as the standard integration flows always remain intact thus unmodified
- Based on previous point, you don’t risk any update or bug fixes applied by SAP to standard integration content (standard integration flows)
- All your extension activities are carried out in a separate custom integration flow so you have to work with less resources and less CPI elements (only one mapping actually)
- You save a load of time without performing your extension activities over and over again because your Post-Exit flow will always be there after you upgrade to newer release for your integration package
Good luck with your extensions
Well written blog Hakan. Thanks for taking the time to do that!
Hi Marcus,
Thanks for the feedback! Appreciated.
Let me know if any part requires more elaboration…
Kind Regards,
Hakan
Incredible way of explanation. Thank you so much Hakan Köse . I will wait now for your next blog.
BR
Saurabh
Thanks Saurabh!
It’s always great to hear what your thoughts are about my content
Best Regards,
Hakan
Hi Hakan,
great blog! Very good step by step explanation! 🙂
Do you also already have any blog about the BAdI implementation to bring the data of your custom field into the contact as additional facet, that you wrote about in the first part of your article?
BR Tobias | https://blogs.sap.com/2020/01/29/how-to-extend-your-sap-marketing-integrations-with-post-exits-in-sap-cloud-platform-integration-part-2/ | CC-MAIN-2020-50 | refinedweb | 2,260 | 55.54 |
PO and write MS Excel files using Java. An alternate way of generating a spreadsheet is via the Cocoon serializer.
also read:
- Java Tutorials
- Java EE Tutorials
- Design Patterns Tutorials
- Java File IO Tutorials
HSSF is the POI Project’s pure Java implementation of the Excel ’97(-2002) file format. We will see how to read the data from a Excel sheet and display in console using java code in this article.
Features of HSSF
- HSSF provides a way to read spreadsheets create, modify, read and write XLS.
- Eventmodel api for efficient read-only access.
- It provides full usermodel api for creating, reading and modifying XLS files.
Where to get the POI API?
You can download the POI API from
Apache POI – Terminology
Before getting in to HSSF, we will see some of the POI-Terminologys
-.
Reading data from Excel format file and displaying to console
Let us assume we have the following excel file (test.xls) with us.
Now let us see how to read through the rows and cells and get the data and display in the console.
Apache POI – Code Sample
The following java program reads a excel file and displays the data to the console.
[code lang=”java”]
/*
* POIExcelReader.java
*
* Created on 7 October, 2007, 9:05 PM
*/
package com.ms.util;
//~— non-JDK imports ——————————————————–
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichText.poifs.filesystem.POIFSFileSystem;
//~— JDK imports ————————————————————
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
/**
* This java program is used to read the data from a Excel file and display them
* on the console output.
*
* @author dhanago
*/
public class POIExcelReader
{
/** Creates a new instance of POIExcelReader */
public POIExcelReader ()
{}
/**
* This method is used to display the Excel content to command line.
*
* @param xlsPath
*/
@SuppressWarnings ("unchecked")
public void displayFromExcel (String xlsPath)
{
InputStream inputStream = null;
try
{
inputStream = new FileInputStream (xlsPath);
}
catch (FileNotFoundException e)
{
System.out.println ("File not found in the specified path.");
e.printStackTrace ();
}
POIFSFileSystem fileSystem = null;
try
{
fileSystem = new POIFSFileSystem (inputStream);
HSSFWorkbook workBook = new HSSFWorkbook (fileSystem);
HSSFSheet sheet = workBook.getSheetAt (0);
Iterator rows = sheet.rowIterator ();
while (rows.hasNext ())
{
HSSFRow row = rows.next ();
// display row number in the console.
System.out.println ("Row No.: " + row.getRowNum ());
// once get a row its time to iterate through cells.
Iterator cells = row.cellIterator ();
while (cells.hasNext ())
{
HSSFCell cell = cells.next ();
System.out.println ("Cell No.: " + cell.getCellNum ());
/*
* Now we will get the cell type and display the values
* accordingly.
*/
switch (cell.getCellType ())
{
case HSSFCell.CELL_TYPE_NUMERIC :
{
// cell type numeric.
System.out.println ("Numeric value: " + cell.getNumericCellValue ());
break;
}
case HSSFCell.CELL_TYPE_STRING :
{
// cell type string.
HSSFRichTextString richTextString = cell.getRichStringCellValue ();
System.out.println ("String value: " + richTextString.getString ());
break;
}
default :
{
// types other than String and Numeric.
System.out.println ("Type not supported.");
break;
}
}
}
}
}
catch (IOException e)
{
e.printStackTrace ();
}
}
/**
* The main executable method to test displayFromExcel method.
*
* @param args
*/
public static void main (String[] args)
{
POIExcelReader poiExample = new POIExcelReader ();
String xlsPath = "c://test//test.xls";
poiExample.displayFromExcel (xlsPath);
}
}[/code]
Code walk through
- POIFSFileSystem is the main class for POIFS system. POIFSFileSystem manages the entire life cycle for the file system.
- POIFSFileSystem has a constructor which can take a InputStream as the parameter. Here in the above code we have created a FileInputStream and assigned to the InputStream. This inputStream object is passed to the POIFSFileSystem constructor and POIFSFileSystem object is created.
- After creating POIFSFileSystem object, HSSFWorkbook object has to be created.
- HSSFWorkbook object is a high level representation of a workbook. This is the first object most users will construct whether they are reading or writing a workbook. It is also the top level object for creating new sheets/etc.
- HSSFWorkbook object is created using POIFSFileSystem object. By using the constructor HSSFWorkbook(POIFSFileSystem fs).
- Once we get the HSSFWorkbook object it is very easy to get the Sheet. HSSFWorkbook has a method getSheetAt(int index) Get the HSSFSheet object at the given index.
- Note that index starts at zero. In our code we have used like “workBook.getSheetAt (0)” means we are intrested in first sheet.
- The above method will give us a HSSFSheet object.
- HSSFSheet object has got a method called “rowIterator()”. This will give us all the rows in a Iterator and is of type HSSFRow
- By Iterating this in a while loop we can get each and every for and cells in them.
- HSSFRow has a method called “cellIterator()” This will also return a Iterator consisting of type HSSFCell.
- By Iterating this we will get individual HSSFCell objects.
- By getting the HSSFCell we can get the cell type by using the method “getCellType()”
- By finding the cell type we can use the appropriate method to get the values as shown in the code above. Then it is up to the programmers requirement to use the values got accordingly. Here we have simply displayed it in the console.
Output
[code]
Row No.: 0
Cell No.: 0
String value: Name
Cell No.: 1
String value: Age
Cell No.: 2
String value: URL
Row No.: 1
Cell No.: 0
String value: Muthukumar Dhanagopal
Cell No.: 1
Numeric value: 33.0
Cell No.: 2
String value:
Row No.: 2
Cell No.: 0
String value: Krish
Cell No.: 1
Numeric value: 27.0
Cell No.: 2
String value:
Row No.: 3
Cell No.: 0
String value: Sri Hariharan Muthukumar
Cell No.: 1
Numeric value: 3.0
Cell No.: 2
String value:
[/code]
Other operations you can do with HSSF
- to create a new workbook
- to create a sheet
- to create cells
- to create date cells
- Working with different types of cells
- Aligning cells
- Working with borders
- Fills and color
- Merging cells
- Working with fonts
- Custom colors
- Reading and writing
- Use newlines in cells.
- Create user defined data formats
- Fit Sheet to One Page
- Set print area for a sheet
- Set page numbers on the footer of a sheet
- Shift rows
- Set a sheet as selected
- Set the zoom magnification for a sheet
- Create split and freeze panes
- Repeating rows and columns
- Headers and Footers
- Drawing Shapes
- Styling Shapes
- Shapes and Graphics2d
- Outlining
- Images
- Named Ranges and Named Cells
- How to set cell comments
- How to adjust column width to fit the contents
Summary
Through this article i have just given the much needed push (Even eagles need a push). It is up to the programmers or developers who wanna proceed further to know more about POI and its API. Now a days there are many applications which are there in real time which uses Excel sheets and need to be read from Java and vice verse. POI is a very helpful, fantastic and easy tool helping Java programmers in achieving this. | https://javabeat.net/apache-poi-reading-excel-sheet-using-java/ | CC-MAIN-2022-05 | refinedweb | 1,111 | 60.72 |
I need to read more than 256 bytes from an I2C peripheral in a single transfer.
The standard component I2CM_0_MasterReadBuf() and associated ISR are limited to 256 bytes due to the cnt variable being uint8 instead of (a more useful) uint16. This is something that does not appear to be configurable at the build level.
I can create a copy of the API function to use locally but is there any way to override the ISR in the build with my own version where I can also change the counter size?
I have resolved this, the trick is in the mode parameter I2CM_MasterReadBuf().
I was able to split the transfer into two consecutive calls:
for the first mode = I2C_MODE_NO_STOP,
for the second mode = I2C_MODE_RESTART.
However it's not clear how you could do more than two blocks in a transfer without a STOP, I tried consecutive intermediate blocks with each setting mode to:
I2C_MODE_REPEAT_START
I2C_MODE_NO_STOP
I2C_MODE_REPEAT_START | I2C_MODE_NO_STOP /* this is really what you want to work */
The first of these puts a stop on the bus, the latter two end up at the CYASSERT() in the ISR
case I2CM_0_SM_MSTR_RD_ADDR: /* After address is sent, read data */
.........
else
{
/* Address phase is not set for some reason: error */
#if(I2CM_0_TIMEOUT_ENABLED)
/* Exit interrupt to take chance for timeout timer to handle this case */
I2CM_0_DisableInt();
I2CM_0_ClearPendingInt();
#else
/* Block execution flow: unexpected condition */
CYASSERT(0u != 0u);
#endif /* (I2CM_0_TIMEOUT_ENABLED) */
}
break;
Fortunately < 512 bytes is enough for my application! | https://community.cypress.com/thread/34852 | CC-MAIN-2020-40 | refinedweb | 240 | 53.24 |
Duncan Mackenzie
Microsoft Developer Network
February 28, 2003
Summary: Duncan Mackenzie describes how to build a tool that uses the Background Intelligent Transfer Service features of Microsoft Windows XP to download large files over slow or intermittent links. (15 printed pages)
Applies to:
Microsoft® Visual Basic® .NET
Microsoft® Windows® Server 2003
Microsoft® Windows® XP
I'm sitting in a hotel room in San Francisco working on a project that can't wait until I get back to my office, and all I can think about is my reliance on connectivity. I, and a bunch of other happy developers, am here because of the VSLive/VBits conference. Trouble is, I didn't bring everything I need for my work, so now I desperately need a network connection. Sure, I have dial-up access in the hotel room, but though quick enough for e-mail, it's anything but practical for large file transfers.
Sound like a familiar situation? Well, it happens to me all the time, and usually it's a pain. This time, however, I decided I'm not going to be beaten by mere, piddling circumstances. I am, after all, a developer. Not only that, I'm a developer looking for a good time (developing that is). I'm going to solve this problem—and turn the solution into this month's article. (Which I have just decided is about using the Background Intelligent Transfer Service features of Microsoft® Windows® XP to download large files over slow or intermittent links.)
Okay. So let's say there is a file that I need and I can't wait until I'm back in Redmond. For instance, let's say it is the demo for Impossible Creatures (which is a whopping 285 MB), and that I really, really need it for some serious research. As I said, my dial-up access is slower than a dead snail, but there is wireless in a nearby coffee shop that should be considerably faster. Even so, as much as I like coffee, I couldn't possibly sit there sipping caffè mochas while the entire file downloads—not if I ever want to sleep again. Not only that—what if the wireless connection dropped for a moment, or I decided to actually attend a session at the conference (which would require leaving the coffee shop and probably shutting down my machine)? What would happen to my mission-critical download then?
Well, that's precisely the problem the Background Intelligent Transfer Service (BITS) was built to solve. Well, okay, maybe not for this precise problem, but BITS was created to download large files across intermittent and/or slow network connections, and even allow the machine to be shut down without losing the download. I had worked with the BITS library before, and I even wrote a .NET wrapper for it (in an earlier article on MSDN), but I had never used it for ad hoc downloads. What I needed now was a system that would allow me to add "jobs," which is the BITS term for a set of files to be downloaded from a Web server, whenever I find something on the Web that I want to pull down. A console application would be enough to get my game demo download started, but I'd prefer to extend it into a system capable of more general use.
Note For more information on BITS, check out the detailed reference material available on MSDN.
The first thing I needed to do was to compile a list of the features that would make this utility useful to people besides me:
To save time, I grabbed the "Browse for Folder" component from Microsoft's support Web site (part of Microsoft Knowledge Base article 306285), which helped me with requirement 4 from the list above. For the rest, the wrapper provided all of the functionality I needed for working with BITS, so I was left to focus on the user interface. I needed to display the list of jobs currently in progress, provide support for dragging links from the Web browser, and allow the user to configure their desired download location.
This is one of the few applications I have created that does not involve a database, but I still used data binding to build my interface. With Microsoft® Windows® Forms applications, you can bind to arrays and collections in addition to databases, so all I really needed was a collection of background copy jobs in progress. The BITS wrapper already provides a collection that contains the current set of background copy jobs, but I decided to create new classes that wrapped the raw BITS information into a display-friendly format.
I created a class to encapsulate a single BITS "job" and a strongly typed collection class to hold a list of all my jobs. Then I bound a data grid to that collection. I wanted to display the copy progress graphically, and although I probably could have found a progress component on the Web, I went ahead and built one of those from scratch. I still had to add a couple of buttons, a main menu, and a context menu, but the grid is the heart of this user interface (see Figure 1).
Figure 1. The copy utility attempts to look professional, no matter what it is downloading
Once I add drag-and-drop support, and the ability to set a default save location for downloaded files, the application will essentially be ready to use.
The feature that really makes this utility usable is the ability to drag links in from your browser. Without this, you would have to copy and paste your links or type them in manually, and neither is a very enjoyable user experience. In general, URLs are not designed for use by humans; whenever possible, do not make people type them into your application(s).
Implementing a link drag-and-drop feature in your own application takes only a few steps. First, set the AllowDrop property of the target control (the control that will accept dragged objects) to True. Next, you will need to add code in the DragDrop event for that control, which will check whether the dragged object is of the desired type, and process the link (in this case, adding it as a BITS job).
'm_Options is my user settings class, discussed later...
Private Sub dgJobs_DragDrop(ByVal sender As Object, _
ByVal e As DragEventArgs) _
Handles dgJobs.DragDrop
Try
If e.Data.GetDataPresent(DataFormats.Text, _
True) Then
e.Effect = DragDropEffects.Link
'should contain the URL if a link is
'dragged in from IE
Dim sURL As String = _
e.Data.GetData(DataFormats.Text, True)
Dim myURI As New Uri(sURL)
Dim fileName As String = _
Path.GetFileName(myURI.LocalPath)
Dim localPath As String = _
Path.Combine( _
Me.m_Options.defaultSaveLocation, _
fileName)()
Else
e.Effect = DragDropEffects.None
End If
Catch ex As Exception
e.Effect = DragDropEffects.None
MsgBox(ex.ToString)
End Try
End Sub
In addition to DragDrop, I also handle the DragEnter event where I check the type of data being dragged and indicate whether I am able to accept it. Setting the DragEventArgs.Effect property will change the cursor displayed during the drag operation.
Private Sub dgJobs_DragEnter(ByVal sender As Object, _
ByVal e As DragEventArgs) _
Handles dgJobs.DragEnter
Try
If e.Data.GetDataPresent(DataFormats.Text, True) Then
e.Effect = DragDropEffects.Link
Else
e.Effect = DragDropEffects.None
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
With the drag-and-drop feature available, I expect most jobs will be created using this technique, but it does not cover all situations. To cover occasions where you do not have a direct link but you can discover the appropriate URL, I added a dialog and associated menu option for manually creating jobs (see Figure 2).
Figure 2. A dialog allows jobs to be created manually.
This dialog is a good example of building and using a standard dialog in Microsoft® Visual Basic® .NET. You create an instance of the Form, set up its properties, display it modally, and then retrieve its properties once it has been closed.
'm_Options is my user settings class, discussed later...
Private Sub addNew_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) _
Handles addNew.Click
Dim newJobDialog As New addNewJob()
newJobDialog.Options = Me.m_Options
Dim newJobResult As DialogResult
newJobResult = newJobDialog.ShowDialog
If newJobResult = DialogResult.OK Then
Dim sURL As String = _
newJobDialog.SourceURL
Dim myURI As New Uri(sURL)
Dim localPath As String = newJobDialog.Target
Dim fileName As String = _
Path.GetFileName(localPath)()
End If
End Sub
In addition to retrieving and providing information to a dialog, the New Job form also illustrates the use of regular expressions to validate the source URL and the use of the SaveFileDialog component to allow the user to pick a location for the downloaded file.
'Validate Source URL
Private Function ValidURL( _
ByVal sourceURL As String) As Boolean
Dim urlValidator As String = _
"http:\/\/[\w]+(.[\w]+)([\w\-\.," & _
"@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?"
Dim r As New Regex( _
urlValidator)
Return r.IsMatch(sourceURL.Trim)
End Function
'Pick Save Location
'm_Options is my user settings class, discussed later...
Private Sub browseForFile_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles browseForFile.Click
'Pull filename out of Source URL
Dim fileName As String
If ValidURL(Me.Source.Text) Then
Dim source As New Uri(Me.Source.Text)
'get file name
fileName = Path.GetFileName(source.LocalPath)
Else
fileName = ""
End If
'saveDestinationAs is a SaveFileDialog control on Form
Me.saveDestinationAs.FileName = fileName
If Not m_Options Is Nothing Then
Me.saveDestinationAs.InitialDirectory = _
m_Options.defaultSaveLocation
End If
If Me.saveDestinationAs.ShowDialog() _
= DialogResult.OK Then
Me.Destination.Text = saveDestinationAs.FileName
End If
End Sub
This application only has one user-configurable option—the default directory for downloads—but the concepts illustrated in this sample could apply equally well to a more complicated set of configuration options. By using a class to hold my user settings, I can take advantage of the built-in serialization features of Microsoft® .NET and save/restore the entire Options class with a few simple lines of code. Serialization is how I will save my settings, but where should I save them? There are two main locations recommended for saving user-specific configuration: the user's application data folder and isolated storage. For this example, I decided to use Isolated Storage, which allows me to create files without any concern about where those files will be located or whether they will conflict with the setting files for another program. Using the classes available in the System.IO.IsolatedStorage namespace combined with the System.Runtime.Serialization classes, I can save and restore my serialized settings specifying only a file name of "settings.xml". There is a bit more code in my listing than you would require for just saving and retrieving a settings object, but I decided to pull the default download directory of Microsoft® Internet Explorer out of the registry for use as a default.
Imports System.IO
Imports System.IO.IsolatedStorage
Imports Microsoft.Win32
Public Class UserSettings
Private Shared Function _
GetIEDefaultSaveLocation() As String
'When you download a file from IE,
'it defaults to the last location
'you downloaded a file to, this code
'just pulls that location out of the
'registry. If the setting isn't available,
'the user's My Documents folder is used
'as a default.
Dim saveDir As String
Try
Dim IEMain As RegistryKey
IEMain = Registry.CurrentUser.OpenSubKey _
("Software\Microsoft\Internet Explorer\Main", _
False)
saveDir = IEMain.GetValue("Save Directory", _
Nothing)
If saveDir Is Nothing Then
'default to user's My Documents folder
saveDir = Environment.GetFolderPath( _
Environment.SpecialFolder.Personal)
End If
Catch ex As Exception
MsgBox(ex.ToString)
saveDir = Directory.GetDirectoryRoot( _
Application.StartupPath)
End Try
Return saveDir
End Function
Public Shared Function GetSettings() _
As Options
Try
Dim m_Options As Options
Dim settingsPath As String = "settings.xml"
Dim isf As IsolatedStorageFile
isf = IsolatedStorageFile.GetUserStoreForAssembly
If isf.GetFileNames(settingsPath).Length > 0 Then
Dim myXMLSerializer As New _
Xml.Serialization.XmlSerializer( _
GetType(Options))
m_Options = CType( _
myXMLSerializer.Deserialize( _
New IsolatedStorageFileStream _
(settingsPath, IO.FileMode.Open, _
IO.FileAccess.Read)), Options)
Else
m_Options = New Options()
m_Options.defaultSaveLocation = _
GetIEDefaultSaveLocation()
End If
Debug.WriteLine(m_Options.defaultSaveLocation)
Return m_Options
Catch ex As System.Exception
MsgBox(ex.ToString)
Return Nothing
End Try
End Function
Public Shared Sub SaveSettings( _
ByVal currentSettings As Options)
Try
Dim isf As IsolatedStorageFile
isf = IsolatedStorageFile.GetUserStoreForAssembly
Dim settingsPath As String = "settings.xml"
Dim myXMLSerializer As _
New Xml.Serialization.XmlSerializer( _
GetType(Options))
myXMLSerializer.Serialize( _
New IsolatedStorageFileStream( _
settingsPath, IO.FileMode.Create, _
IO.FileAccess.ReadWrite), _
currentSettings)
Catch ex As System.Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
<Serializable()> Public Class Options
Dim m_defaultSaveLocation As String
Public Property defaultSaveLocation() As String
Get
Return m_defaultSaveLocation
End Get
Set(ByVal Value As String)
Try
If Path.IsPathRooted(Value) AndAlso _
Not Path.HasExtension(Value) Then
If Not Directory.Exists(Value) Then
Directory.CreateDirectory(Value)
End If
m_defaultSaveLocation = Value
End If
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Set
End Property
End Class
By calling UserSettings.GetSettings when my application loads and UserSettings.SaveSettings when it exits, I can ensure that user preferences are correctly saved and restored. To actually change the settings of my utility, I could have used an Options dialog, but with only a single available setting ("Default Save Location") it seemed easy enough just to provide a "Set Default Download Location" menu item. In the click event for the menu item, I used the Browse for Folder component to allow the user to select an existing folder or to create and select a new folder.
Private Sub mnuSetDefaultLocation_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles mnuSetDefaultLocation.Click
If defaultSaveLocation.ShowDialog() = _
DialogResult.OK Then
m_Options.defaultSaveLocation = _
defaultSaveLocation.DirectoryPath
End If
End Sub
If I had been writing this application using the 1.1 version of the .NET Framework, then I could have used the FolderBrowserDialog class directly from the Windows Forms namespace, but I am building this sample using 1.0. Fortunately, the freely available component from Microsoft's support site works just fine, and since the price is right, I am quite happy to use it.
The nature of BITS makes it well suited to many work scenarios, because it is useful anytime you need to transfer files over an intermittent network connection. Accordingly, this means that this utility is potentially a work tool. Unfortunately, this work connection can't really be avoided in this case. So if you happen to use the program more for downloading files over your company's VPN connection than for pulling down the latest game demos, that's okay; I won't tell anyone. For more ideas on how BITS can be used in work situations, check out this article from MSDN Magazine, which shows an application that updates itself through background downloading of new files. Of course, the most widely used example of the usefulness of BITS is in the Windows Update features of Windows XP, where BITS can be used to download patches, drivers, and software updates completely in the background.
The finished background copy utility includes a few more features than have been discussed in this article, but you can download it and dig through the code at your leisure. Although you can download the complete code for this little program, there is no user manual available, so let me give you a few tips about using this utility to download files:
At the end of some of my Coding4Fun columns, I will have a little coding challenge—something for you to work on if you are interested. For this article, the challenge is to build your own application using the Background Intelligent Transfer Service (BITS) in some way. As I mentioned above, BITS lends itself to quite a few different work and personal scenarios, so I am sure you will be able to come up with interesting applications. Managed code is preferred (Visual Basic .NET, C#, J#, or Managed C++ please), but an unmanaged component that exposes a COM interface would also be good. Just post whatever you produce to GotDotNet and send me an e-mail message (at duncanma@microsoft.com) with an explanation of what you have done and why you feel it is interesting. You can send me your ideas whenever you like, but please just send me links to code samples, not the samples themselves (my inbox thanks you in advance).
In response to my Playing with Music Files column, I received quite a few comments and links to very cool sample applications. I appreciate the feedback, and I'll post links to a few of these samples in my next column. If you are looking for more digital-music–related development information right now, I would suggest looking into the managed code samples in the Windows Media Player SDK.
Have your own ideas for hobbyist content? Let me know at duncanma@microsoft.com, and happy coding!
Coding4Fun
Duncan Mackenzie is the Microsoft Visual Basic .NET profile on GotDotNet. | http://msdn.microsoft.com/en-us/library/ms973203.aspx | crawl-002 | refinedweb | 2,871 | 55.84 |
On Sat, 2016-08-27 at 10:07 -0700, Michael wrote: > if someone forked my repository, did work on "master", and submitted > it to go onto my "master", then how do I say "No, come in on a branch > named devB instead"?
Advertising
Something important to understand is that your local repository and every remote you register all have their own "namespaces" for branches. Because of this, in fact someone else's "master" can never interfere with your "master" or a different remote's "master". The default name for the remote you cloned from is "origin". That means there's an "origin/master", "origin/foo", "origin/bar", etc. for every branch ("master", "foo", "bar") that exists on the remote. So you can see what the remote's master contained with "git log origin/master" (as of the last time you fetched from that remote). You can compare them with "git diff origin/foo foo", etc. You also have your own branches, "master", "foo", "baz", etc. which are local to your repository and don't exist in the remote. And if you add a second remote (which of course has to have its own name, not "origin") then you will get all of its branches imported into your repository, but under that remote's name, so "other/master", "other/foo", "other/boz". So there's really no reason to be concerned about other people using "master", since that's their "master" and is not your "master". They are in different namespaces and Git won't get them confused. However, people soon discovered that _much_ of the time, you really only have a single remote and the extra command line fu needed to keep everything straight was annoyingly redundant. So Git has a concept of a "tracking branch", which is a local branch which is tracking a branch in one of your remotes. If your local branch is a tracking branch for some remote's branch, then when you pull from that remote Git knows to merge from that remote's branch into your branch. Note there's no reason at all that the remote branch and the local tracking branch have to have the same root name. A local branch "foo" could be tracking a remote "other/fubar". So, you could have a local branch "master" which tracks "origin/master" and a different local branch "master_other" which tracks "other/master". You might try reading which I think explains this fairly well. -- You received this message because you are subscribed to the Google Groups "Git for human beings" group. To unsubscribe from this group and stop receiving emails from it, send an email to git-users+unsubscr...@googlegroups.com. For more options, visit. | https://www.mail-archive.com/git-users@googlegroups.com/msg10409.html | CC-MAIN-2016-44 | refinedweb | 451 | 69.82 |
Here is mine:
Offline
Reki wrote:
dwm-6.0 with several patches, and dzen2 for the statusbar.
Hi Reki,
nice terminal colors!
would u mind sharing it?
Thanks! Here's my .Xresources:
Just scroll down to the colors part.
Last edited by Reki (2012-02-05 03:07:42)
Offline
Arch + dwm • Mercurial repos • Github
Registered Linux User #482438
Offline
First steps with scrotwm...
Really like scrotwm but we can't disable workspaces we don't use. This is the only drawback.
Great setup by the way.
Last edited by Ypnose (2012-02-05 10:37:06)
Offline
Openbox + tint2. Trying my hand at tweaking tabs in FF to better match Vimperator / the rest of my theme ... getting there.
Willing to share how to get tabs like that ?
Offline
Varg wrote:cirnOS wrote:
Sorry to ask you but would you be willing to tar your subtle folder? I find it a pain to save each file manually...
Forget that I saw the zip function and downloaded that. Is there a way to change the tiling function to grid mode like how DWM and WMFS does? I just played with subtle around and I like it.
Edit: If I add a bottom bar in subtle is there a way to pipe conky to it?
Subtle is a pure manual tiler so I don't think that you can get the same behaviour as DWM. I noticed that there is a columns sublet but I never tried it.
There is a sublet to pipe conky to your bar but I never used that either.
Use:
sur list -r
to see all available sublets.
How did you achieve that tiling on this screenshot?- … %20wm&qo=2
That's default Subtle
By default every window takes up the entire desktop. Then you can use the windows key and keypad to change size and position:
W-7 -> Top left
W-3 -> Bottom right
W-4 -> Left side half of the screen
W-4-4 -> left side of screen but 66% in of the screen size
W-4-4-4 -> Left side of screen but 33% of the screen size
github - tweets
avatar: The Oathmeal
Offline
finwin wrote:Cloudef wrote:
Also, slowly switching over to monsterwm.
Same thing here
What panel is that? snapwm or dzen?
It is the default dwm panel (i was installing monsterwm not using it
) with conky piped into dzen2 on the right side.
finwin wrote:Cloudef wrote:
Also, slowly switching over to monsterwm.
Same thing here
Lovely color scheme! Can you share it? Oh, and what font are you using in vim?
Of course
*foreground:#a0a0a0 *background:#000000 !black *color0: #1B1D1E *color8: #505354 !red *color1: #F92672 *color9: #FF669D !green *color2: #A6E22E *color10: #BEED5F !yellow *color3: #FD971F *color11: #E6DB74 !blue *color4: #66D9EF *color12: #66D9EF !magenta *color5: #9E6FFE *color13: #9E6FFE !cyan *color6: #5E7175 *color14: #A3BABF !white *color7: #CCCCC6 *color15: #F8F8F2
Font is Dina 15
Offline
Working on my hosting site...
OpenBSD, xxxterm, mcwm & tamsyn on desktop, OpenBSD & nginx on server :)
Last edited by sime (2012-02-05 14:30:42)
Offline
doug piston: wallpaper. please.
Offline
I love the wallpaper... can I have it?
Offline
el mariachi
Offline
Offline
grobar87 wrote:
I love the wallpaper... can I have it?
And... here... we... go!
Offline
Playing with No-wm
#include "dvtm"
#include "some_sorta_bar"
#include "dmenu"
Could you elaborate on no-wm? I don't really know what makes it tick, e.g. how do you tile windows?
Offline
lorin wrote:
Openbox + tint2. Trying my hand at tweaking tabs in FF to better match Vimperator / the rest of my theme ... getting there.
Willing to share how to get tabs like that ?
Bear in mind I have almost no idea what I'm doing, but this is my userChrome.css. I cheated and used an addon to move the Firefox menu, as removing the icon itself in css was leaving a weird little gap.
.tabbrowser-tab { height: 18px !important; min-height: 18px !important; max-height: 18px !important; padding-right: 3px !important; padding-left: 5px !important; padding-top: 5px !important; margin-left: 0px !important; margin-right: 1px !important; background: #758CA3 !important; border: none !important; color: #FFFFFF !important; font-family: gelly; font-size: 9px; font-weight: normal; padding: 0 0.5ex !important; -moz-appearance: none !important; -moz-border-radius: 0 !important; } .tabbrowser-tabs{ border:0px !important; background-color: #454545 !important; } #TabsToolbar { background-color #758CA3; height: 19px; -moz-box-shadow: none !important; } .tabbrowser-tab:hover { background: #758CA3 !important; } .tabbrowser-tab[selected] { background: #75A3A3 !important; }
Offline
@ttgr nice desk
Last edited by knob (2012-02-05 22:33:18)
Offline
going oldskool w/blackbox
bbpager, bbdock, tint2, adeskmenu, obmixer, bbtime
Offline
Working on my hosting site...
OpenBSD, xxxterm, mcwm & tamsyn on desktop, OpenBSD & nginx on server
What is the web browser you're using?
Offline | https://bbs.archlinux.org/viewtopic.php?id=134789&p=5 | CC-MAIN-2018-13 | refinedweb | 795 | 78.45 |
Creates a new thread.
Syntax
#include <prthread.h> PRThread* PR_CreateThread( PRThreadType type, void (*start)(void *arg), void *arg, PRThreadPriority priority, PRThreadScope scope, PRThreadState state, PRUint32 stackSize);
Parameters
PR_CreateThread has the following parameters:
type
- Specifies that the thread is either a user thread (
PR_USER_THREAD) or a system thread (
PR_SYSTEM_THREAD).
start
- A pointer to the thread's root function, which is called as the root of the new thread. Returning from this function is the only way to terminate a thread.
arg
- A pointer to the root function's only parameter. NSPR does not assess the type or the validity of the value passed in this parameter.
priority
- The initial priority of the newly created thread.
scope
- Specifies your preference for making the thread local (
PR_LOCAL_THREAD), global (
PR_GLOBAL_THREAD) or global bound (
PR_GLOBAL_BOUND_THREAD). However, NSPR may override this preference if necessary.
state
- Specifies whether the thread is joinable (
PR_JOINABLE_THREAD) or unjoinable (
PR_UNJOINABLE_THREAD).
stackSize
- Specifies your preference for the size of the stack, in bytes, associated with the newly created thread. If you pass zero in this parameter,
PR_CreateThreadchooses the most favorable machine-specific stack size.
Returns
The function returns one of the following values:
- If successful, a pointer to the new thread. This pointer remains valid until the thread returns from its root function.
- If unsuccessful, (for example, if system resources are unavailable),
NULL.
Description
If you want the thread to start up waiting for the creator to do something, enter a lock before creating the thread and then have the thread's root function enter and exit the same lock. When you are ready for the thread to run, exit the lock. For more information on locks and thread synchronization, see Introduction to NSPR.
If you want to detect the completion of the created thread, make it joinable. You can then use
PR_JoinThread to synchronize the termination of another thread. | https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/Reference/PR_CreateThread | CC-MAIN-2016-40 | refinedweb | 308 | 56.86 |
Archived:Simple Hello World Application Using Graphics View Framework.
Introduction
This article demonstrate how to use Qt's Graphics View Framework to create custom controls. Qt has a very flexible and easy to use GUI components in form of Widgets like QPushButton, QLabel, QCheckBox, QListWidget etc
Using these Qt Components one can easily design good GUI based application and give a good User Experience to the application user. But when we need to write some custom widgets of our own, these inbuilt components have lots of limitation. So for this Qt has a Graphics View Framework which helps the developer to render their custom controls on the screen. Graphics View provides a surface for managing and interacting with a large number of custom-made 2D graphical items, and a view widget for visualizing the items, with support for zooming and rotation.
Basic Elements of Graphics-View Framework
The Graphics View Framework comprises of three basic elements or classes which helps the developer to use and understand the Graphics View Framework.
- QGraphicsView
- Displays the widgets of a screen, it basically visualizes content of a scene. The view widget is a scroll area, and provides scroll bars for navigating through large scenes. The view receives input events from keys and touches, and translates these to scene events (converting the coordinates used to scene coordinates where appropriate), before sending the events to the visualized scene.
- QGraphicsScene
- Class for storing the widgets, handling event propagation(input from keyboard and touches) and managing item states. It represents a scene with items in it. QGraphicsScene also manages the state of item like selection and focus and acts as a container to different items placed on the scene.
- QGraphicsItem
- A basic class for the graphical items on the scene. It can also represent a group of items.
Graphics View provides several standard items for typical shapes, such as rectangles (QGraphicsRectItem), ellipses (QGraphicsEllipseItem) and text items (QGraphicsTextItem), but the most powerful QGraphicsItem features are available when one writes a custom item. QGraphicsItem is responsible for keyboard input, focus, drag and drop.
Simple Graphics View Framework Composition
A QGraphicsScene object is flexible enough to include any number of QGraphicsItem objects and still maintain the efficiency in retrieving them. On the other hand, a QGraphicsView object size is limited by the device’s display size. Putting these 3 elements together we have something like this:
The basic idea here is to manage the events of each item you create and redraw them as needed. This way, you can make your own custom widgets with more visually appealing features.
Simple Hello World Example
#include <QtGui/QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsItem>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// making a scene on the application
QGraphicsScene scene;
//adding some text to the scene
scene.addText("Hello, world!", QFont("Times", 20, QFont::Bold));
//assigning that scene to the view
QGraphicsView view(&scene);
view.show();
return a.exec();
}
Screenshot of the application is shown below:
Lets add some more lines to the code:
#include <QtGui/QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsItem>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QPainterPath path;
path.moveTo(30,120);
path.cubicTo(80, 0, 50, 50, 80, 80);
scene.addPath(path, QPen(Qt::black), QBrush(Qt::green));
scene.addText("Hello, world!", QFont("Times", 15, QFont::Bold));
QGraphicsView view(&scene);
view.show();
return a.exec();
}
and this will look like :
Conclusion
So we can see how powerful is Qt Graphics View Framework, in the time ahead I will write some articles in which we will use some different Graphics Item to design some simple custom screens. | http://developer.nokia.com/community/wiki/Archived:Simple_Hello_World_Application_Using_Graphics_View_Framework_in_Qt | CC-MAIN-2014-10 | refinedweb | 605 | 52.29 |
Help to understand an AttributeError in a polynomial ring
F. Chapoton recently wrote a program the behaviour of which I do not understand.
def fermat(n): q = polygen(ZZ, 'q') return sum(n ** j * binomial(n, j) * (-1) ** (i + n + j) * binomial(n - 2 - j + 1, i + 1) * q ** i for j in range(n - 1) for i in range(n - 1 - j))
Now consider:
v = fermat(5) print v.parent() print v.list()
This outputs
Univariate Polynomial Ring in q over Integer Ring [821, 181, 21, 1]
which is fine. However the loop
for n in (1..9): v = fermat(n) print v.parent() print v.list()
gives the errors:
AttributeError: 'int' object has no attribute 'parent' AttributeError: 'int' object has no attribute 'list'
What happens here?
For n=1, the sum is empty and by default this gives a python int. That is because I simplified my program for oeis. If you care, you need to add R=q.parent() and then use R.sum(...)
Thanks Frédéric. If you write your comment as an answer I will accept it. So all this has nothing to do with the preparser or range formats as suggested in kcrisman's answer. | https://ask.sagemath.org/question/36387/help-to-understand-an-attributeerror-in-a-polynomial-ring/?sort=latest | CC-MAIN-2019-43 | refinedweb | 200 | 76.11 |
Chrooting into an existing installation
Run
lsblk and note the partition layout of your installation. It will be usually something like
/dev/sdXY or if you have an NVMe drive
/dev/nvme0nXpY.
Mount the file system:
# mount /dev/sdXY /mnt
Additionally, if you have an EFI system partition and need to make changes in it (e.g. updating the vmlinuz or initramfs images):
# mount /dev/sdXZ /mnt/esp
Finally, enter the chroot:
# arch-chroot /mnt
To exit the chroot use:
# exit
You can now do most of the operations available from your existing installation. Some tasks which needs D-Bus will not work as noted in #Usage. -t sysfs /sys sys/ # mount --rbind /dev dev/
And optionally:
# mount --rbind /run run/
If you are running a UEFI system you will also need access to EFI variables. Otherwise, when installing GRUB you will receive a message similar to:
UEFI variables not supported on this machine:
# mount --rbind /sys/firmware/efi/efivars sys/firmware/efi/efivars/
Unshare, part of util-linux, can be used to create a new kernel namespace. This works with the usual chroot command. For example:
$ unshare --map-root-user chroot ~/namespace /bin/sh
Troubleshooting
arch-chroot: /location/of/new/root is not a mountpoint. This may have undesirable side effects.
Upon executing
arch-chroot /location/of/new/root a warning is issued:
==> WARNING: /location/of/new/root is not a mountpoint. This may have undesirable side effects.
See arch-chroot(8) for an explanation and an example of using bind mounting to make the chroot directory a mountpoint. | https://wiki.archlinux.org/title/Arch-chroot | CC-MAIN-2022-40 | refinedweb | 260 | 53.61 |
Sencha GXT Grid and overlap over components
Sencha GXT Grid and overlap over components
I am using the sencha grid component and sometimes after the grid completes rendering, it will overlap on top of components above the grid. For example, if I add a search box field at row1 and then the paging grid on row2. The paging grid will overlap the component in row1 so you can't see the search box.
Is there anyway for this component to refresh properly?
import com.sencha.gxt.widget.core.client.grid.Grid;
VerticalLayoutContainer container = new VerticalLayoutContainer();
container.add(new FieldLabel() new VerticalLayoutContainer.VerticalLayoutData(.99, .1, new Margins(2, 2, 2, 2)));
applicantGrid = new Grid();
container.add(applicantGrid, new VerticalLayoutContainer.VerticalLayoutData(.99, .8, new Margins(2, 2, 2, 2)));
So the field label (row1) will not get shown properly because the 'applicantGrid' is slightly overlapping the row1 field label.
Is there a refresh or something I can do to the 'Grid' widget to make it work properly.
GXT version: 3.0.1
Yes. The problem is in your layout data. Remember, values < 0 mean use the actual height/width, values from zero to including 1 are treated as percentages, and values over 1 are treated as pixels.
What you most likely want is 1.0, -1.0 for your first row and 1.0, 1.0 for your grid. This tells the first row to render at 100% width and actual height and the grid to be 100% width and take up all the remaining vertical space.
If you need to add anything else to your VLC, e.g., a paging tool bar, that would probably be 1.0, -1.0 as well but obviously depends on your needs/use case.
Give that a go and see if it fixes your problem. If not, you may need to call forceLayout() on the VLC after rendering but this is not always needed.
inner.clear();
final Widget w = event.getContainer().asWidget();
inner.add(w, new VerticalLayoutContainer.VerticalLayoutData(1, 1));
this.forceLayout();
Another issue also, we are clearing and then re-adding those components. I wonder if there is a better 'refresh' type of operation.
It looks like the verticallayout data with gxt allows me to use 0 to 1 values. Where each percentage is a percentage is a percentage of that particular portion of screen out of 1.0.
Is there a way to have components add naturally so that I dont' have to define the height with vertical layout data.
E.g. if I add a textfield of height 30px and then a gridpanel of 70px. I don't have to use verticallayoutdata with 0.3 and 0.7. Can I just add those widgets.
What type of widget is "inner?" If it's a HasOneWidget, you don't need the clear because setWidget will remove the old widget if it exists.
Since you are dynamically changing out the contents of stuff, the forceLayout() may be necessary and this is essentially the "refresh" operation.
To answer your other question, I don't know. Try creating a widget of a fixed size, and then calling VLC.add(...) without any layout data. I think it should work, but am not sure.
If you call setPixelWidth and setPixelHeight, using -1 is ok or omitting the VLD all together is fine. No VLD implies -1.0, -1.0.
From, a few guides you might find helpful on this topic: | http://www.sencha.com/forum/showthread.php?264881-Sencha-GXT-Grid-and-overlap-over-components&p=970650 | CC-MAIN-2014-15 | refinedweb | 572 | 67.86 |
I am currently making a program where a user selects an image qpushbutton. I already have superseded mouseMoveEvent, mousePressEvent, and mouseReleaseEvent in the button class to get a movable button. The buttons are currently moving independently, but I would like the buttons to move so that the horizontal distance between them stays the same.
So currently in pseudo code I have:
import stuff import mvbutton as mv class MasterClass(QWidget): def __init__(self, *args): QWidget.__init__(self, *args) #more setup stuff, layout, etc self.addbutton(image,name,size) def addbutton(#args): self.button=mv.dragbutton(#args) #some more setup #now rename so that each button has its own name if name== "name1": self.name1=self.button else: self.name2=self.button self.button="" #more code to set up
I supersede the mouse motion/press/release functions in the dragbutton class. I cannot, therefore reference the new
self.name# there. So the
self.move(pos) in my dragbutton class cannot get the
self.name# because it is a different self. Any ideas on how I could get this to work? Thanks. | http://www.howtobuildsoftware.com/index.php/how-do/UTt/python-qt-python-27-pyqt-have-2-pyqt-buttons-move-synchronized-when-mouse-moves | CC-MAIN-2018-13 | refinedweb | 180 | 60.31 |
can someone help here please…i am not able to understand the test cases…can anyone explain ?
Thank you in advance
can someone help here please…i am not able to understand the test cases…can anyone explain ?
Thank you in advance
so see bro we are given a tree so lets say i consider the first test case:
5 1 2 1 3 2 4 3 5
so there is an edge between 1 & 2, 1 & 3 , 2& 4 , 3&5
5<-3<-1->2->4 this is how the graph should like . So lets say I don’t use the special operation before attacking any town , I have to face 5 warriors at a time .
Now if i use the special operation on node 1 then there will be no edge between 1 and 2 , and between 1 and 3 . So in this process I capture node 1 and then there will be two components of graph left i.e 5->3 and 2->4.
So if i attack at 2(because its being now disconnected) I have to face 2 warriors now.
Note : 1 is the optimum node now lets say what if i use special operation on node 2 then
1 and 2 will get disconnected and the graphs remaining are 5<-3<-1 & 2<-4.
So now if i attack at node 3 then i have to face 3 warriors at a time which is not optimum so I should have selected 1 which is like the mid point.
Try to figure out the 2nd test case .If u don’t understand I can help and also whenever u post doubts tag admin and problem setter he can help u with the editorial.
thank you sooooo much @kanisht09 for helping me
this tutorial is very very helpful for me
u r welcome bro
@sandeep1103 please share the editorial , i m having difficulty in the implementation. would be a great help
I have but the code which i have is not mine i picked someone’s code and modify that code according to me and then try to understand the test cases. I had picked this code before your wonderful help
#include <bits/stdc++.h>
using namespace std;
int n;
int dfs(vector<vector>&a,vector &vis,int x,int &X,int &W){
int ans=0,num=1;
vis[x]=true;
for(int i:a[x]){
if(!vis[i]){
int tmp=dfs(a,vis,i,X,W);
num+=tmp;
ans=max(ans,tmp);
}
}
ans=max(ans,n-num);
if(ans<W)
X=x,W=ans;
else if(ans==W)
X=min(X,x);
return num;
}
int main(){
int t; cin>>t;
while(t–){
cin>>n;
vector<vector> a(n+1);
for(int i=1;i<n;i++){
int X,v;
cin>>X>>v;
a[X].push_back(v);
a[v].push_back(X);
}
vectorvis(n+1,false);
int X=INT_MAX,W=INT_MAX;
dfs(a,vis,1,X,W);
cout<<X<<" "<<W<<endl;
}
return 0;
}
Blockquote
Hey!! bro can you share your approach of Notebook Distribution ques. i am having trouble to implement this.
The editorial has been posted.
The question basically asks you to find the centroid of the tree. Centroid of the tree is a node whose subtree size does not exceed N/2 (N being the number of nodes). You can check out my submission here:
You can simply binary Search over the answer. Here, have a look at my submission and let me know if you are not able to understand anything.
“”
dp denotes subtree size . let me know if u have any issue.
well as far subtree is involved can u please suggest me some starter problems so it would be easy for me to solve this .Like using dfs i can calculate connected components ,length of each connected component and print the node which is a part of the component and where can i learn this. Please reply @ssrivastava990 ,@harsh0911
Bro there are many blogs over codeforces , just google it -
for questions -
“”
wow its really nice thanks for ur help
Great place to learn certain basic algorithms and also practise questions.
To practise, I recommend to apply filters on codeforces and then practise to increase your level, gradually moving on to more complex problems.
googling skills matters
I used binary search for this problem
Here is my solution :
And if u want to learn how to apply binary search for problems like this do watch Coden code utube channel’s playlist on binary search.It really helped me a lot.
can you explain your logic ? i know how to use binary search but still i am able to think why we use this .
Encoding August 20 Problem Name-Notebook Distribution visit here i had the same problem like u | https://discuss.codechef.com/t/naruto-and-one-shot-graph-ques/76623 | CC-MAIN-2020-40 | refinedweb | 796 | 68.7 |
Command Line Junkie
The original subject behind this month's article, was going to be "Cross Platform C#", however, during the course of sketching it out, I realized that there wasn't really enough material to do the actual article I wanted to do.
You see, last time I actually had to port any C# code to a system other than Windows, was quite some time ago.
In fact it was so long ago, that Mono was still quite in its infancy and .NET 3.5 had only just arrived on our doorsteps.
Armed with what I knew from then, and going forward into now, I made some assumptions that turned out to be wholly incorrect.
Back then, when I first tried doing some cross platform code, the only thing I actually had any real success porting across was simple command line programs, using standard output and standard input for their I/O.
For the younger members of the audience standard input and standard output - aka stdin/stdout are what you use when you're at a command prompt or in a power-shell session, in the days before Windows and on most servers this is still the only way to work.
This wasn't really a problem though, because in all honesty, the code I was porting across was simple 'CGI' (CGI = Common gateway interface) binaries anyway, so it wasn't a big deal.
I did as part of learning Mono however, attempt to write some simple win-forms programs, and quickly discovered many differences in the naming of objects and namespaces, that where very different to what I was used to on the Windows platform.
So back to the point of this article, when I sat down to write this, I did a few tests first, just to see if I still had the same environment that I had back then, and was very surprised to find that I didn't.
You see I'd intended to document these changes, and give folks a point by point trouble shooting guide, but the ONLY problem I actually encountered was trying to run a win-forms program at an SSH terminal command line (more on that soon).
So the question now remained, what to do? Scrap this idea, and run with the next one, or see what I could salvage? Well as you may have guessed, I opted for the later of the two.
So what has 'Cross platform' got to do with being 'A command line junkie', well everything really if you think about it. You see, many people who use Visual Studio and other tools don't often realize, that you don't actually need Visual Studio to write .NET applications at all, and everything we’re about to do here, we're going to do using a command line.
When you install .NET on your Windows PC (even just so you can run a .NET application) , you are in actual fact installing all the compilers, linkers and other tools you actually need (and use) when building your applications.
Don't believe me?
Take a look in:
C:\windows\Microsoft.NET\Framework
or
C:\windows\Microsoft.NET\Framework64
You should see a number of folders matching each version of .NET you have installed, and if you go into one of them, in most cases you'll see tools such as 'csc.exe' & 'vbc.exe'
You may also see 'msbuild.exe'. Msbuild is the tool used by Visual Studio to compile your project files, which are just msbuild scripts, and most of the time if your rebuilding an app or solution you only need to go to the folder where your project lives and type:
msbuild <solutionfile.sln>
To Actually Compile and Build Your Project
If you do actually try this, you'll see the output is identical to what you see in the output pane when working in the Visual Studio editor.
This article however, is not about msbuild (I may cover that in a future article); what we are going to look at here is 'csc.exe'
CSC is the 'C Sharp Command-line' compiler and as you may have guessed is used to compile generic C# code there and then without the complexities of VS, and for those who are wondering, VBC is the visual basic compiler.
Before we go any further, you might want to make sure that CSC is in your path, that way you can call it simply by just specifying 'csc' instead of 'c:\windows\Microsoft.NET\version\csc.exe' each time you want to use it. From now on, I'll just be referring to it as 'csc'.
Fire up notepad or some other simple text editor and create a file called 'cmdline.cs'. Enter the following c# code into this text file:
using System; namespace dnnutsandbolts { static class cmdline { static void Main() { Console.WriteLine("Hello World!"); } } }
Now open up a command line in the folder where you just saved it, and type:
csc cmdline.cs
If everything worked ok, you should now have a 'cmdline.exe' program. Go ahead, run it by typing 'cmdline'; you'll see that it works exactly as expected and displays 'Hello World' on the command prompt.
If you ever need to hack together quick and dirty command line tools, this is the way to do it. I've done this millions of times to add extra tools needed in batch files and other scenarios.
You may not realize it, but you've just done pretty much what creating a new console mode application project does in visual studio, only much quicker and quite a bit easier I'm willing to bet.
Time to Try Something a Little More Involved
Create a new file called 'winform.cs' and enter the following code:
using System; using System.Drawing; using System.Windows.Forms; namespace dnnutsandbolts5 { static class winform { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new HelloWorld()); } } public class HelloWorld : Form { public HelloWorld () { Text = "Hello world"; Button b = new Button {Text = "Click Me!"}; b.Click += Button_Click; Controls.Add (b); } private void Button_Click (object sender, EventArgs e) { MessageBox.Show ("Button Clicked!"); } } }
And just as before from your command line enter:
csc winform.cs
Which should result in 'winform.exe' appearing in the folder; and like the previous example, typing 'winform' and pressing return, should run your app and present a simple form, with a clickable button on.
OK, so this is great, and potentially quite useful, but what's it got to do with Linux and Mono?
Well now that you know you can create programs in C#, using nothing more than a simple editor and a command line, how about we try opening up a Linux command line and see if we can do the same?
How you do this is entirely up to you and what you have available. For me, I have physical servers that I have access to via an SSH command line, using Putty. For the winforms test I created a virtual machine using virtual box, then installed a desktop version of Ubuntu on it.
Once you can get your command line open, copy your 'cmdline.cs' file across to your Linux box by whatever means you have.
Once you've copied, switch to the folder where you created it, and type the following:
gmcs cmdline.cs
At this point, I am assuming you have the Mono development system installed on your Linux system; if not then for me under Ubuntu server, it was simply a matter of typing:
sudo apt-get install mono-complete
If you’re using a different Linux please refer to your system documentation for the correct process.
'gmcs' is to Mono what 'csc' is to .NET on windows, it's the C Sharp compiler frontend and is targeted specifically at version 4 of the .NET runtime. There is also 'mcs' which will create output for .NET version 2 runtime or for projects targeting V3.5 or lower.
If 'gmcs' worked above, then just as with Windows, you should have a 'cmdline.exe' application, ready to run, and if you run it, you should get 'Hello world' just as before.
You can also, compile your winforms app in the same way:
gmcs winform.cs -r:System.Windows.Forms.dll -r:System.Drawing.dll
There is you'll notice, one difference. Unlike 'csc' your usings are not picked up automatically so you generally have to specify them using the '-r' syntax shown above, it's for reasons like this you’re advised to use a build runner.
If you try running the winforms app in a command only environment, you'll get an unhandled exception that makes no sense. It took me about an hour of digging to realize it was because the Linux box I was using did not have any GUI/Desktop software installed on it. Something that kind of makes sense, if you’re building graphical software.
Installing a Desktop Linux (as previously described) and making sure that Mono was installed, then compiling and running, allowed me to take the exact same source code from Windows across to Linux, and compile it without making any changes however.
The ultimate question then, is why is this useful, and where do I go from here.
Well it's useful, because in recent months, as more and more companies start to embrace Open Source software, many businesses are moving to Linux based platforms to cut down on licensing costs. As a result, many are also porting across huge enterprise projects, originally written using Microsoft Tools for the Windows platform, and so starting a whole new business of porting software across.
I can almost hear everybody reading this, thinking… Can I run my 'MVC site' on Mono, and what about webforms? The answer to both of those questions is yes, if you're running under the Apache web server, then you can simply install 'mod_mono' and give Apache everything it needs. You will have to make some minor changes here and there, and I think the webforms implementation is only good to about 3.5 at present. As always though, the documentation and source code is your friend.
Another thing to be watching, is the upcoming 'OWIN' standard, for the open Windows hosting platform. We already have many self-hosting tools, as well as tools to host OWIN apps on IIS, Apache, Nginx and many others.
If hosting under a web server is not your cup of tea, then you always have the option of using something like NancyFX (which I myself have tried with great success to provide Json Endpoints for a web application) or Service Stack.
If you look closely at many of the packages available in NuGet, you'll see a lot of them have been tested and are known to work on Mono.
That's all for this week, but in a future article we'll look at getting a full cross platform project up and running in either MVC or something similar.
If you have any ideas for anything you'd like to see in this column, then hunt me down on the interwebs. I can generally be found hanging around Twitter as @shawty_ds or in the Linked.NET (Lidnug) users group on Linked-In that I help run.
Until next time, keep porting. | https://www.codeguru.com/columns/dotnet/command-line-junkie.htm | CC-MAIN-2019-35 | refinedweb | 1,891 | 68.6 |
Hi
Just wanted to bring the above bug
"XPath Namespace resolver fails when namespace starts with a #"
to the attention of this list, since I've run into the same issue.
In my case, the namespace looks like a GUID:
xmlns:ns3='25863374-67c0-4723-8c21-1fb7e315143b'
Someone went to a lot of effort to report the bug against the openjdk,
but it appears to have languished with Oracle...
I had a look through Apache JIRA, but couldn't see it there...
If this is not a known issue, please let me know, and I'll submit it to JIRA.
thanks .. Jason | http://mail-archives.apache.org/mod_mbox/xalan-j-users/201402.mbox/%3CCAM-hvXfJ_vET+HF5=YGFdwkLXb41r5OMJn271nGkALOwnfqN1Q@mail.gmail.com%3E | CC-MAIN-2017-17 | refinedweb | 102 | 73.21 |
JS: Map Object
New in ES2015.
Map is the value of the property key
"Map" of the global object.
[see JS: the Global Object]
console.log( window["Map"] === Map ); // true
Type
Map is a function.
[see JS: Value Types]
// type of Map console.log ( typeof Map === "function" ); // true
Parent
Parent of
Map is
Function.prototype.
[see JS: Prototype and Inheritance]
// parent of Map console.log ( Object.getPrototypeOf ( Map ) === Function.prototype ); // true
Purpose
Purpose of
Map is:
- To create instance of “map” object. Instance of map object is a collection of key/value pairs as a lookup table data structure. This is different from the generic JavaScript object 〔JS: Object Type 〕. The map object instance is designed specifically as a lookup table data structure.
- Used as a namespace to hold general purpose methods for working with “map” instances.
- Holds the property key
"prototype". The value of
Map.prototypeis the parent object of all “map” instances.
Facts about map:
- Map instances are collections of key/value pairs.
- The key can be any JavaScript type.
- The value can be any JavaScript type. [see JS: Value Types]
- Keys are always distinct.
- The insertion order of entries are maintained.
[see JS: the Map Object Tutorial]
How Map Determines Uniqueness of Keys
The equality test used for determining whether 2 keys in a map is the same as
===,
except treatment of
NaN (not a number).
NaN === NaN return
false, but for map object,
NaN is considered same as any
NaN.
// this is false console.log(NaN === NaN); // false // for map object, NaN is same as any NaN const m = new Map(); m.set(NaN, "n1"); m.set(NaN, "n2"); console.log(m) // Map { NaN => 'n2' }
Constructor
Properties
Reference
ECMAScript 2015 §Keyed Collection#sec-map-objects
JS Map Topic
Liket it? Put $5 at patreon.
Or, Buy JavaScript in Depth
Or, Buy JavaScript in Depth | http://xahlee.info/js/js_map_object.html | CC-MAIN-2018-51 | refinedweb | 308 | 70.19 |
This forum is now read-only. Please use our new forums at discuss.codecademy.com.
Introduction to Twitter's API Forum
View Course » View Exercise
Someone help wit ex.4
Someone help wit ex.4
print ["text"] or puts ["text"] doesn't work as wel
Try this:
tweets.each do |tweet| puts tweet['text'] end
It appears that the object
tweets is an array of hashes. You'll want to access the hash key
'text' in each of the elements of the array
tweets. Correct me if I'm wrong. This is quite confusing :)
BTW -- I couldn't get the exercise to pass with
3 Comments
Can you help to point out what my problem is? I tried with puts tweet["user"]["name"]+' - '+tweet["text"] but it always said "You did not generate the correct output. Did you print the username, followed by ' - ', followed by the Tweet text?"
Thanks.. I need to learn Ruby ;)
Even if I changed the count to 10 and set the code like this:
baseurl = "" path = "/1.1/statuses/user_timeline.json" query = URI.encode_www_form ( "screen_name" => "twitterapi", "count" => 10, ) address = URI("#{baseurl}#{path}?#{query}") request = Net::HTTP::Get.new address.request_uri # Print data about a list of Tweets def print_timeline(tweets) # ADD CODE TO ITERATE THROUGH EACH TWEET AND PRINT ITS TEXT tweets.each do |tweet| puts tweet["text"] end end
I still get the following error:
"Ooops, try again. You did not generate the appropriate number of output lines. Did you update the count parameter?"
Is there something wrong?
I passed the exercise.
For this exercise you should be able to open twitter with your browser, Twitter is inaccessible in some countries.
set count to 10 :
query = URI.encodewwwform(
"screen_name" => "twitterapi",
"count" => 10,
def print_timeline(tweets)
tweets.each do |tweet|
p tweet["text"]
end
end
Thank u :) I completed | https://www.codecademy.com/forum_questions/513f471c4ad407451e0005b0 | CC-MAIN-2017-47 | refinedweb | 303 | 77.43 |
One of the biggest annoyances with Sharepoint 2007 is the quirky things you have to do in order to customize a site. This is especially true when it comes to custom master pages. You create a stunning master page in Designer, configure the site to use it, then load the page and wait to bask in the glory. Lo and Behold! It worked! Job done, go grab a beer ... but you better drink it fast because Sharepoint has a nasty surprise in store for you. That master page only works on the content pages in your site. System pages (i.e. viewlists.aspx) will refuse to use your amazing Master page. All that work is wasted on a half complete user experience. Or is it?Why is it not doing what I tell it to do?This is because those system pages are hard-wired to use a different master page (application.master) . To make matters worse, you only get one application.master for everywhere. You could go modify this file, but be careful: changes to this will affect ALL pages based on that master, everywhere. It's not something that can be customized on a site-by-site basis. To make matters still worse, Microsoft *will* update this file in upcoming patches, so odds are good that it will break on you sometime in the future, and likely with little warning.Ok, so what's the skinny?Create a custom httpModule and install it on your Sharepoint site that remaps which .Master pages your pages use. If you aren't familiar with httpModules, fear not, they are extremely simple.The httpModule sits in the middle of the http request processing stream and can intercept page events when they initialize. The pages load up and say "I'm going to use application.master", to which your module replies "not on my watch, buddy" and not so gently forces the page to use the Master page of your choice.The Gory Details(this assumes that you already have the aforementioned Nifty Master Page created. If not, please search Google for any of the hundreds of tutorials on how to do this)
Prepare your Master PagesYou will need two .Master pages. One to replace default.master and the other to replace application.master. It is very important that when you are creating these pages that you include all of the ContentPlaceHolders that exist in the .Master page you are replacing. Throw any ContentPlaceHolders that you are not using in a hidden DIV at the bottom of the page - but before the closing FORM tag (the only exception to this seems to be "PlaceHolderUtilityContent" which goes in after the closing form tag). Once in place, you can use the normal Master Page options in the UI to select the default.master replacement.
Second, be sure to remove the Search Control from your Application.Master replacement. The reason for this is that the search box does not normally appear on system pages and will cause an error during rendering.
You can probably simplify this a bit by using nested master pages, but I haven't had a chance to look into that yet.Step 1 - Create the httpModuleCreate a new Class Library project in Visual Studio and start with the code below. So simple, even a manager could do it (maybe). Obviously, you will have to change the path to match your environment. Oh, and sign the assembly as well.
using
3/1/2007 - UPDATE!In response to comments, I have updated these instructions, in particular, I have added the "Prepare your Master Pages" section that addresses most of the issues encountered in the comments.
Also, do not use this method if your sharepoint install has the shared Service Provider (SSP) installed on the same web application as your main sharepoint environment. The system pages used by the SSP do not work properly when their master page is replaced like this. I'm sure there is a logical reason why, I simply haven't had the time to dive into it.
Pingback from Dreamrift » Useful SharePoint References
Daniel:
Any idea why I might be getting "could not load file or assembly" errors no matter what?
I have followed your instructions above several times and used sn.exe to dig out the public key of my dll. I have also copied the dll to every bin folder related to WSS I can find, and dragged the dll into the GAC....
*sigh*. I'm lost. Any help would be appreciated.
follow-up to my post of despair above ... especially since I did not remember my original fix when I had to install the switcher all over again in a new VM instance.
My problem was that I had not renamed "MasterPageHandlerModule" to match the name of my .dll and had been attempting to refer to "MasterPageHandlerModule" rather than "wss_redirect".
Jason,
Glad to hear you got it working!
Corps: Après plusieurs discussions entre collègues et lectures sur le net sur les cas pratiques d'utilisation
Hi,
I created my own custom application.master page and placed it in the /_catalog/masterpage directory as stated above, however my code continues to break on the following line:
page.MasterPageFile = "/_catalogs/masterpage/MyCustom.master";
SharePoint continues to come back with a "file not found" error. I have tried changing the path several times to no avail. What am I doing wrong? By the way my class has been compiled, placed in the GAC, and I have made the proper entries in the application's web.config file. Thank You.
Arnie, first off, I'd suggest that you verify that your master page has been properly approved through the Content Approval mechanism.
It may also be related to how your site is authenticating. If you have anonymous on a site but require authentication at the root, you might be seeing this as well.
You might also want to enable debugging to help ensure that the "file Not Found" error you are seeing is actually where you think it is ().
Hi David,
I tried your suggestion and I am still getting the same error (File Not Found). Thank You for providing the information on how to turn on Asp.NET debugging for the site, unfortunately it did not provide me with any additional information. I am open to suggestions. My code is as follows:
using System;
using System.Web;
using System.Web.UI;
using System.IO;
namespace HPI_Http_Intercept
{
public class MasterPageModule :.MasterPageFile != null)
{
if (page.MasterPageFile.Contains("application.master"))
{
page.MasterPageFile = "/_catalogs/masterpage/HPhilips_Application.master";
}
}
public void Dispose()
}
}
Thank You,
Arnie Lugo
Nice one dave, are you planning to link Sharepoint with your photography ??
Sorry Siam, you must have me confused with someone else. The extent of my photography skills is creating blurry photos of family vacations.
Arnie, the only time I've seen this behavior was on a system that was using Content Management and required full approval for the master pages.
Just out of curiousity, what happens when you manually set a site to use your new master page via the SharePoint UI?
Hello:
This is a very good article, I am a new SharePoint developer and I did the same steps as you mentioned.
Created a Class Library Project
Use your code
Build Dll and copied it at inetput/wwwroot/.../bin
when I go back and create a site or anything, it does not change the master page with mine. It does not give any error or anything.
What do I have to do to make this http module execute? I dont think this code is being hit when I am browing the SharePoint site.
Your help is appreciated
James,
There are a number of things it could be. First off, is your DLL strong-named. Secondly, did you modify the web.config for the site as mentioned in Step 2? Lastly, are you certain you are changing the right Site? SharePoint will create lots of sites and sometimes it may look like one directory is for the site you are working with but it is actually a different one.
Also, have you checked both the Event log and the 12\LOGS folder for errors when loading a page. Both of those may provide additional clues.
You were right, I was modifying the wrong webconfig file, thanks for your help.
Now atleast I can see that its being called, i do get the following error though:
----------------------------------------------------------------------------------
File Not Found. at Microsoft.SharePoint.ApplicationRuntime.SPRequestModuleData.GetWebPartPageData(HttpContext context, String path, Boolean throwIfFileNotFound))
Troubleshoot issues with Windows SharePoint Services.
---------------------------------------------------------------------------------------------
It seems like it can not find the file
"_catalogs/masterpage/TestSolution.master";
When I deployed my solution, I can see this master page in master page gallery but I am not able to find any virtual directory _catalogs under any site.
How can I tell if my new master page is at its right location i.e. _catalogs/masterpage direcotry.
I have a solution, which creates a site definition template and when i use this template I can see that its using my master page and when i browse to another area within same site it was using application.master but now its giving me error.
Thanks
the catalogs folder should be off of the root of the site collection as '/_catalogs' not a subfolder of a particular web.
Also, this folder does not appear in the 'Content and Structure' view but does appear when you are working on the site collection in SharePoint Designer. As long as your page is getting in there and it appears in the Master Page Gallery, that should be good enough.
While you are in the Master Page Gallery, make sure that the 'Approval Status' for your new master page is set to 'Approved'.
Also, make sure you don't have a Search Control on that Master Page as it will cause errors. That's why I recommend 2 master pages. One for normal content pages and one for system pages (i.e. if you see '_layouts' in the url, that means it is a system page)
David,
This is a great article. This is the exact problem I have with our portal site
AS you mentioned, do not use this method if your sharepoint install has the shared Service Provider (SSP) installed on the same web application as your main sharepoint environment. Most of the companies use small farm for SharePoint. We have one server for sql database and the other server for everything else.
Do you have any suggestions on how to make application master page works in this situation (SSP and web application on the same box)?
Thanks,
Peter
Hi David!
Great stuff, if I just would get it to work. Have copied the code exactly as it says, Signed the assembly and Build the project. Transferred my .dll to the bin-folder of my site, and altered the web.config (should you use the key that you get when signing the assembly or can I use the original key from the code here?)
The error i get in eventviewer after changing the web.config is this:
Exception information:
Exception type: ConfigurationErrorsException
Exception message: Could not load file or assembly 'MasterPageHandlerModule, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6bdb1331dfc11306' or one of its dependencies. The system cannot find the file specified. (C:\Inetpub\wwwroot\wss\VirtualDirectories\80\web.config line 149) (C:\Inetpub\wwwroot\wss\VirtualDirectories\80\web.config line 149)
PS. The dll is named MasterPageModule.dll DS
What am I doing wrong? Please Help!
Regards
/Jimmy
Hi Jimmy:
The httpModule entry in webconfig shold be as follows:
<add name=<Any tag name e.g. "Test"> type=<class name, if you have a namepace as well make sure its namespace.classname>, <DLL file name>, Version=<version>, Culture=neutral, PublicKeyToken=<key that you get from DLL u created for httpModule"/>
Hi David,
I followed your instruction, created a new class library. I copied the new build DLL into the bin folder under the site collection c:\Inetpub\wwwroot\wss\VirtualDirectories\mysitecollectname\bin\ folder instead of c:\Inetpub\wwwroot\wss\VirtualDirectories\80\bin folder. It looks like application.master page changed to my customized master page only for that site collection. My Central Administration Tool and other site collections still use the application.master page. That is great.
Now the system pages switched to my customized master page instead of application.master page, but it does not pick the changes in ItemStyle.xsl file I modified.
Is there any way I can force the system pages not only using customized master page but also to use ItemStyle.xsl?
Thanks a lot David!
Realised that my DLL file name was wrong, changed it and the error disappeared, but when I went to a System page I got an Unknown error. After some thinking and looking at the original application.master, I realised that it was a lot diffrent than default.master (which I just took a copy of, deleted the search-field and renamed) Took a copy of the original application.master and changed it instead, and voila! .. Works like a charm now!
Pingback from Customizing Application.master « Greg Galipeau’s Weblog
We followed everything what you mentioned in yoru document and it worked all great problem is when we click on mysite we get error. it could be bcoz we have SSP on same server,, But is there any way to solve this problem ?? even other sites on same server also have thsi problem too.
I followed everything what you mentioned in your document and it worked all great.
the problem is when I try to upload documents to document library I got the following error
The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again.
I checked the log file under 12\logs directory, there is no related entry logged there.
When I commented out the following line of code in web.config. the problem is gone.
<!--
<add name="MasterPageHandler" type="MasterPageModule, SPSMasterPageHandler, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5c0b2f6acfaf6191" />
-->
Any idea?
Corpo: Olá pessoal, Estou escrevendo este post em resposta a uma série de dúvidas relacionadas ao modelo
Thanks for the great tip! I am having one problem however. The master page loads correctly on the pages it is supposed to but when I try to add a column to a list there are errors on the page. The page renders but when I fill out the form and click the 'OK' button to submit nothing happens. Disabling the module in the web.config temporarily removes the issue.
David,
Great article, just one question...do i need to make a copy of application.master and default.master or do I use my customdefault.master as both? At one point in the article it seems to read as needing 2 different master pages and at another it seems like I am using one master in 2 different locations. Thanks.
I have created the master pages and its working fine. Now, I want this to be installed on my site as an feature which can be activated / deactivated by the user. Can it be achievable ? Please reply soon
Thanks! For me it works on _Layouts only (not on other application sites like List and Documents etc.)
Any ideas?
Great solution! Thank you. I have perhaps a novice problem whereby the client-side javascripts within my master page appear not to be loading now that the solution is in place. I use the "src" tag to reference my scripts from file for inclusion. I can embed the script into the master page and they work fine. Any clues why separate "src" might not work?
I M gettin this exception in my event log. Always this prob occured very frequently once application Pool recycles.
Exception type: ConfigurationErrorsException
Exception message: Could not load type 'MasterPageModule'.
(E:\Inetpub\wwwroot\wss\VirtualDirectories\myapps.csplc.org80\web.config line 145)
Pleas suggest me the Solution
I deployed this, never get any errors, so tried debugging and everytime it hits:
Page page = HttpContext.Current.CurrentHandler as Page;
it shows page being null, and thus never replaces the master page. do you have any idea why it would be showing as null?
Thank you:..
Great solution!
i do have one issue thou.
i have one topsite, and several undersites and i cant figure out any way to modify
page.MasterPageFile = "/_catalogs/masterpage/CustomApplication.master";
so that i can have one CustomApplication.master for each undersite.
page.MasterPageFile = @"~\customer1\_catalogs\masterpage\CustomApplication.master";
works, but then all customers get the same .master file.
any suggestions how to make this link dynamic?
Thanks, For the great post...
I have one doubt. This application.master works fine for the administration pages in the top level site. But when I go to subsites, the administration pages (i.e. _layouts pages) are again taking the master page as the default one (i.e. application.master).
So how to achieve a single custom application.master across the sites?
I am having the same error as James did in the past.)
This error does not happen on the main site collection myportalsite/.../default.aspx. But my web application has about 20 other site collections in addition to the mail site collection. The error happened on all other site collections.
myportalsite/.../default.aspx.
"_catalogs/masterpage/MyApplication.master";
works fine for the main site collection, but not working for other site collections within the same application.
I have tried to use "/sites/IT/_catalogs/masterpage/MyApplication.master";
but it is still not working
Any suggestions?
Thanks in advance,
Same problem here. This application.master works fine for administration pages in the top level site. But when I go to subsites, the administration pages (i.e. _layouts pages) are again taking the master page as the default one (i.e. application.master). | http://www.sharepointblogs.com/dwise/archive/2007/01/08/one-master-to-rule-them-all-two-actually.aspx | crawl-002 | refinedweb | 2,986 | 66.23 |
Hi.
What's the error?
public class LL{
static Node first;
private class Node
{
int data;
Node next;
Hi.
What's the error?
public class LL{
static Node first;
private class Node
{
int data;
Node next;
Java programming is a part of their undergraduate program, while we are graduate students.
Grid computing has nothing to do with OOP.Its a form of distributed computing.
--- Update ---
There is just one actionPerformed() method, so the problem is fairly pin-pointed
Why should I use one class per Dialog?
What would be System.out.println() good for? I am seeing that the first button works when clicked, while the second doesn't (they should both close the...
My latest, shortened code is:
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import com.sun.management.OperatingSystemMXBean;
import...
The check boxes will read "OS version", "CPU architecture", etc , according to which some boolean variables are set, which help to decide which fields of a stored object in a queue will be...
But what if I have more buttons?
I have 1 HButton, named 'button' on a 'JDialog' named 'dialog', and anotther JButton named 'queryButton' on a 'JDialog' named 'queryDialog'.
I changed the...
I have studied some examples, but believe me or not, I have no teacher. Never had any teacher.
--- Update ---
Multiple threads merged.
They each work , but the problem is that I have...
What's the use of reading oracle tutorials when I must use openjdk?
I will post my original code, OK.
--- Update ---
My original code
import java.io.*;
import java.util.*;
I changed it to FlowLayout()
I am new to Java. I wastesting to discover the problem. I changed the pane type from Container to JFrame
It is just that My professor wanted me to write a java...
I am still without solution
Nothing.I have pasted all the code
Hi.
What is it that an empty dialog appears as the result of my code?
my code:
import java.lang.System;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class t{
No, not yet.
Don't know how to upgrade to see if the problem resolves
ok
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import com.sun.management.OperatingSystemMXBean;
import java.lang.management.ManagementFactory;
import...
Yes, that is how I declared it.
The for-loop has in its body:
OperatingSystemMXBean osBean = (com.sun.management.OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
...
osBean is defined as:
OperatingSystemMXBean osBean = (com.sun.management.OperatingSystemMXBean)
ManagementFactory.getOperatingSystemMXBean();
and the error text reads:
...
Hi.
What's the problem with my errorring line?
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import com.sun.management.OperatingSystemMXBean;
import...
Eh...I haven't defined it?Look inside for-loop...I have. haven't I? I have.....seemingly, unless it goes out of scope
Hi.
What's wrong with:
public void showResults(Info[] queue,int k)
{
String results = "";
for(int i =0;i<queue.length;++i)
if(nameChecked)
results += queue[i].name;
sysinfoHooshi.java:72: unexpected type
required: variable
found : value
{ e.getStateChange()==1 ? nameChecked=true :nameChecked = false;}...
Hey, those "if"'s are commented out
I have told you:lines with getStateChange() == 1.
Unfortunately I cannot name number.This forum doesn't show line numbers.
Hi.
This is a snapshot of my code:
public class sysinfoHooshi implements ActionListener{
class Info{
public String name;
public String version;
public String arch;... | http://www.javaprogrammingforums.com/search.php?s=de21115c4e0fb6f0e550a2cb6d113ed9&searchid=1724953 | CC-MAIN-2015-35 | refinedweb | 567 | 53.58 |
#include "lib/crypt_ops/crypto_rsa.h"
#include "lib/testsupport/testsupport.h"
Go to the source code of this file.
Return a newly allocated copy of the public key that a certificate certifies. Watch out! This returns NULL if the cert's key is not RSA.
Definition at line 285 of file x509_nss.c.
Referenced by tor_tls_verify().
Check whether cert is well-formed, currently live, and correctly signed by the public key in signing_cert. If check_rsa_1024, make sure that it has an RSA key with 1024 bits; otherwise, just check that the key is long enough. Return 1 if the cert is good, and 0 if it's bad or we couldn't check it.
Definition at line 302 of file x509_nss.c.
Referenced by tor_tls_verify().
Read a DER-encoded X509 cert, of length exactly certificate_len, from a certificate. Return a newly allocated tor_x509_cert_t on success and NULL on failure.
Definition at line 269 of file x509_nss.c.
References tor_assert().
Return a new copy of cert.
Definition at line 138 of file x509.c.
References tor_assert().
Set *encoded_out and *size_out to cert's encoded DER representation and length, respectively.
Definition at line 216 of file x509_nss.c.
References tor_assert().
Referenced by add_x509_cert().
Return a set of digests for the public key in cert, or NULL if this cert's public key is not one we know how to take the digest of.
Definition at line 58 of file x509.c.
Referenced by connection_or_compute_authenticate_cell_body(), and or_handshake_certs_check_both(). | https://people.torproject.org/~nickm/tor-auto/doxygen/x509_8h.html | CC-MAIN-2019-04 | refinedweb | 243 | 69.58 |
30/10/2014
Build Inkscape on Windows using MinGW (and a cygwin's bazaar)
Here are the notes I took this night while compiling Inkscape. They originally were writen as emails for the Inkscape devel list, but as they were many of them, I'll put them here and send a unique email to the list.
Just to be clear : pretty much everything in this post is not a fix for the issues I encountered, just a way to work around it in order to build Inkscape.
[Inkscape][Devel][Windows][Bazaar] Fetching source using Bazaar on Cygwin, no file fetched exceptinside .bzr folder
Hi everyone,
I just wanted to report some difficulties I add to fetch the source code of Inkscape using Bazaar on Cygwin and how I managed to go on anyway.
I'm pretty sure it's something trivial for a skilled bazaar user, but it wasn't painless for me to figure how to do, and I just want next random guy after me not having the same troubles.
What happened is that I simply followed the wiki how to that is located here
And after a few (dozens of) minutes of downloading, my local repository was empty... except for the .bzr folder.
No error happened and no error was logged anywhere.
bzr updatewas only showing me something like
Tree is up to date at revision 13638 of branch ...
It looked like everything was alright, but I had no code to edit or compile. I finally figured out what happened through the
bzr statuscommand that led me to this error message :
bzr: ERROR: No WorkingTree exists for "
This led me to forums answers, that finally give me an explanation of the issue.
That was using :
bzr reconfigure --tree
I still had nothing but .bzr in my local folder, but this time a "bzr status" show me every single file as if they were deleted.
So I just had to
bzr revert *
I'm not sure if what happened to me was something unusual or linked to the fact I use Bazaar on Cygwin.
But I wanted this to be logged somewhere, as this may happen to someone else, that may not want to spent the few hours I spent to figure out what the matter was.
Cheers.
[Inkscape][Devel][Windows][MinGW] Compiling using mingw - as.exe cannot start
...
Now I have the sources and I try to build it using mingw.
The symptom is that this command line
g++ buildtool.cpp -o btoolis generating following error :
as.exe wasn't able to start ... 0xc0000022
This forum helped me to find this ticket.
It basically explain that the libiconv-2.dll library that was generated through the command :
g++ buildtool.cpp -o btoolis interfering with the one located in mingw environment.
So I just had to re-set my path to make it work
set PATH=C:/MinGW32bin;%PATH%
Additionally, it would be great to update the mingwenv batch file, in order to make c:/Devlibs to be located before c:/mingw in the path.
Cheers
[Inkscape][Devel][Windows][MinGW] Compiling using mingw - 'gettimeofday(timeval*, NULL)' is ambiguous
...
Next compilation error is :
buildtool.cpp: In member function 'virtual bool buildtool::Make::run(const String&)':
buildtool.cpp:10273:36: error: call of overloaded 'gettimeofday(timeval*, NULL)' is ambiguous
buildtool.cpp:10273:36: note: candidates are:
c:/mingw32bin../lib/gcc/mingw32/4.6.1/../../../../include/sys/time.h:39:29: note: int gettimeofday(timeval*, void*)
buildtool.cpp:84:12: note: int gettimeofday(timeval*, timezone*)
Which I trivially "solved" by editing buildtool.cpp and replacing :
::gettimeofday(&timeStart, NULL);by
::gettimeofday(&timeStart, (timezone*)NULL);
Cheers
[Inkscape][Devel][Windows][Cygwin+MinW] Using bzr on Cygwin and MingW
Next compilation error is :
Make error line 0: executeCommand : could not create process : Le fichier spÚcifiÚ est introuvable.
Make error line 0: error executing 'bzr revno':
As I use MingW fr compilation but Bazaar on Cygwin, this may not be solved easily. I may have to install bazaar on Windows. For now I just faked a bzr.exe on windows that return the revision number at which I am. Here is the code :
#include <iostream>
using namespace std;
int main()
{
cout << "13638" << endl;
return 0;
}
Cheers
[Inkscape][Devel][Windows]Python] Python crash (Oxc0000022)
Next compilation error is a python.exe crash.
It appear that the used python is
c:/Devlibspythonpython.exe
Which doesn't start at all, even if launched separatedly by hand.
Fortunately I also had another python interpreter in my active PATH, so i just renamed it :
mv c:/Devlibspythonpython.exe c:/Devlibspython_python.exe
Cheers
[Inkscape][Devel][Windows][Python] New python issue "<cxxtestpart> problem:"
Next compilation error is :
Make error line 231: executeCommand : could not create process : Le fichier spécifié est introuvable.
Make error line 231: <cxxtestpart>, problem:
It appears this is the following of my previous python issue. If you grep python.exe inside files :
./build-x64.xml
./build.xml
You'll find multiple path where python interpreter path is absolutely referenced, I just changed them to my python.exe file.
Long term solution may be to make C++ compilation work with recent Mingw (that would carry a better python.exe), or to make the scripts able to use another python.
I'm not sure if one of those solution even would be possible to achieve.
Once this issue fixed, Inkscape is compiling but not linking.
[Inkscape][Devel][Windows][GetText] msgfmt crash
...
Now Inkscape is compiling, but not building yet. I got issues with msgfmt.:
##### compile gettext .po files to .mo
--- i18n / msgfmt
Make error line 421: <msgfmt> problem:
My way to "fix" the problem was to install a fresh version of gettext and libiconv for windows (from here)
And to make the path to point on this one before pointing on the C:/DevLibsbin one.
Hurray : it linked and it executes.
I'm still afraid of some patches I maid (especially if I look at this like this log :
--- distbase / copy
copy : c:/devlibs/python/python26.dll to inkscape
copy : 1 file copied
--- distbase / copy
copy : C:/Tools/python27/python.exe to inkscape/python
copy : 1 file copied)
But it linked and it executes.
Now I may start the fun part.
Cheers
Additional note about btool way to list the dep files (thanks to Failbit and JonCruz from irc://irc.freenode.org/#inkscape-devel )
When adding a cpp file :
- if you want btool to compile it, you may want to delete build.dep in src root and re-run btool
- if you want other OS's make system to be aware of it, you may want to add it (and .h too) in the folder's Makefile_insert
Makefile.am sources the Makefile_insert for each directory
then automake produces Makefile.in
then autoconf produces Makefile | http://mathieugueydan.blogs.centraliens-marseille.fr/archive/2014/10/index.html | CC-MAIN-2018-17 | refinedweb | 1,122 | 64.91 |
Painting • When a GUI needs to change its visual appearance it performs a paint operation • Swing components generally repaint themselves as needed • Painting code executes on the event-dispatching thread • If painting takes a long time, no events will be handled during that time ICSS235 - Painting
Example import javax.swing.*; import java.awt.*; public class Painting extends JPanel { public Painting() {} public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor( Color.yellow ); g.fillOval( 10,10,50,50 ); g.setColor( Color.black ); g.drawOval( 10,10,50,50 ); } public static void main( String args[] ) { JFrame win = new JFrame( "Painting" ); win.setSize(100, 100); win.getContentPane().add( new Painting() ); win.show(); }} ICSS235 - Painting
The Graphics Object • The Graphics object both a context for painting and methods for performing the painting. • The graphics context consists of state such as the current painting color, the current font, and the current painting area • The color and font are initialized to the foreground color and font of the component just before the invocation of paintComponent • You can ignore the current painting area, if you like ICSS235 - Painting
The Coordinate System • Each component has its own integer coordinate system • Ranging from (0, 0) to (width - 1, height - 1) • Each unit represents the size of one pixel ICSS235 - Painting
Borders • You must take into account the component's size and the size of the component's border • A border that paints a one-pixel line around a component changes the top leftmost corner from (0,0) to (1,1) and reduces the width and the height of the painting area by two pixels each • You get the width and height of a component using its getWidth and getHeight methods. • To determine the border size, use the getInsets method. ICSS235 - Painting
Example import javax.swing.*; import java.awt.*; import java.awt.Insets.*; public class Painting extends JPanel { public Painting() {} public void paintComponent(Graphics g) { super.paintComponent(g); Insets border = getInsets(); int width = getWidth() - border.left - border.right; int height = getHeight() - border.top - border.bottom; int x = ( width / 2 ) - 25 + border.left; int y = ( height / 2 ) - 25 + border.top; g.setColor( Color.yellow ); g.fillOval( x, y, 50, 50 ); g.setColor( Color.black ); g.drawOval( x, y, 50, 50 ); } } // Painting ICSS235 - Painting
Forcing a Paint • The repaint() method schedules a paint operation for the specified component • A version of repaint() exists that allows you to specify the area that needs to be repainted • Typically a component will invoke repaint() when it has done something to change its state ICSS235 - Painting
Example import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.awt.Insets.*; public class Painting extends JPanel { private boolean drawn = false; private int x; private int y; public Painting() { addMouseListener( new MouseInputAdapter() { public void mouseClicked( MouseEvent ev ) { x = ev.getX(); y = ev.getY(); repaint(); }}); } … ICSS235 - Painting
Animation import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.awt.Insets.*; public class Painting extends JPanel implements ActionListener { private boolean drawn = false; private int x; private int y; private Timer alarm; public Painting() { alarm = new Timer( 500, this ); alarm.start(); } public void actionPerformed( ActionEvent ev ) { x = x + 10; y = y + 10; alarm.restart(); repaint(); } ICSS235 - Painting | https://www.slideserve.com/blangley/painting-powerpoint-ppt-presentation | CC-MAIN-2021-39 | refinedweb | 538 | 50.67 |
Difference between revisions of "Spreadsheet Workbench/es"
Revision as of 09:17, 25 February 2019
Introduction
The Spreadsheet Workbench allows you to create and edit spreadsheets, use data from the spreadsheet as parameters in a model, fill the spreadsheet with data retrieved from a model, perform calculations, and export the data to other spreadsheet applications such as LibreOffice or Microsoft Excel.
The Spreadsheet Workbench has been available since FreeCAD 0.15.
Contents
- 1 Introduction
- 2 Cell Expressions
- 3 Supported Functions
- 4 Reference To CAD-Data
- 5 Cell Properties
- 6 Spreadsheet Data in Expressions
- 7 Units
- 8 Importing and exporting
- 9 Current Limitations
- 10 Scripting Basics
Cell Expressions
A spreadsheet cell may contain arbitrary text or an expression. Technically, expressions must start with an equals '=' sign. However, the spreadsheet attempts to be intelligent; if you enter what looks like an expression without the leading '=', one will be added automatically.
Cell expressions may contain numbers, functions, and references to other cells. Cells are referenced by their row (CAPITAL letter) and column (number). Example: B4 + A6
Numbers may use either a comma ',' or a decimal point '.' separating whole digits from decimals.
The constants pi and e are predefined, and must be written in lowercase.
Supported Functions
Mathematical Functions
The mathematical functions listed below are available.
Multiple arguments to a function may be separated by either a semicolon (';') or a comma followed by a space (", "). In the latter case, the comma is converted to a semicolon after entry.; cell references consist of the row letter (CAPITAL) <=.
The conditional statement has a bug regarding nested conditional statements. Only the true-result may contain another conditional statement. This is because parentheses are removed after an expression is entered. Trying to put a nested conditional statement in the false-result may result in incorrect parentheses causing a different result after saving and reopening the document. Note: This may not longer be true; at least some false result conditionals work properly.
Reference To CAD-Data
It is possible to use data from the construction in the spreadsheet. The following table shows some examples assuming the model has a feature named "Cube" (note that this is the internal name of the feature, not the user assigned Label):
Cell Properties
The properties of a spreadsheet cell can be edited with a right-click on a cell. The following dialog pops up:
It has several tabs. The following properties can be changed:
- Text color and background color
- Text horizontal and vertical alignment
- Text style: bold, italic, underline
- Display unit for this cell. Please read the section below.
- Define an alias-name for this cell. This alias-name can be used in cell formulas and also in FreeCADExpressions introduced in version 0.16
The expressions are explained here: Expressions
Spreadsheet Data in Expressions
The usage of spreadsheet data in other parts of FreeCAD requires a fully defined name. Because it is possible to have
more than one spreadsheet in a document, the spreadsheet name together with the cell name or alias is required.
The following pictures showing the usage of an alias "number" from a spreadsheet "MySheet" in an expression
in the PartDesign Workbench.
Typing an "M" shows a list of available names. The arrow-buttons allow to select "MySheet".
Typing an "n" shows now the list of available alias names in MySheet starting with "n". The "number" can be selected with the down-arrow-button. Once a valid name with a usable content is given, the result field will present the calculated length.
Units
The Spreadsheet uses units. If a number has a unit, this unit will be used in all calculations. The multiplication of two length with the unit mm gives an area with the unit mm².
You can switch the length-unit from mm to inch in the dialog, you get with a right-click on a cell. The cell will now show the length in inches. The value used for calculations does not change. The results of a formula using this value do not change, when the shown unit of an input was changed. The result is still calculated from the length in mm.
A number without a unit cannot be changed in a number with unit by the cell properties dialog. One can put in a unit string, that will also be shown, but the cell still contains only a number without unit.
Sometime it is desirably to get rid of a unit. This can only to be done by multiplying over the menu Spreadsheet/ Import Spreadsheet or by clicking on the icon
. This import function does not open Excel files or any other spreadsheet format.
Spreadsheets in Excel-format "xlsx" can be imported via the menu File/Import... into a FreeCAD document. Excel-spreadsheets can also be opened by FreeCAD by clicking in the menu File/Open... or by clicking on the icon
. In this case
a new document with a spreadsheet inside is created. Supported are the following features:
- all functions that are also available in the FreeCAD spreadsheet. Other functions do give an error in the corresponding cell after the import.
- Alias names for cells
- More than one table in the Excel-sheet. In this case more FreeCAD spreadsheets are created.
Other functionality is not imported into the FreeCAD spreadsheet. The Excel-import is introduced in version 0.17of FreeCAD.
Current Limitations
It is not possible providing data for a geometry, for example a length, in a spreadsheet and retrieving in the same spreadsheet the volume of the resulting shape. This will create a circular reference. This is a design decision. However, it is possible to use two different spreadsheets: one as data-source for geometry and another for reporting geometry-data.
It is not possible to select and copy multiple cells. Only the content of a cell from the input field can be copied and paste into the input field of another cell.
For FreeCAD earlier versions see Spreadsheet legacy
Scripting Basics
import Spreadsheet sheet = App.ActiveDocument.addObject("Spreadsheet::Sheet") sheet.>IMAGE | https://wiki.freecadweb.org/index.php?title=Spreadsheet_Workbench/es&diff=prev&oldid=430666 | CC-MAIN-2020-16 | refinedweb | 999 | 56.35 |
07 October 2009 14:53 [Source: ICIS news]
HOUSTON (ICIS news)--US agrochemicals and biotechnology major Monsanto reported a fourth-quarter net loss of $233m (€158m), compared with a loss of $172m in the same quarter last year, the company said on Wednesday.
A sales decrease for flagship Roundup herbicide, and other glyphosate-based herbicides as a result of pricing competition and a global glyphosate supply and demand imbalance were noted as factors in the decline, Monsanto said.
The company also cited charges related to restructuring and the sale of its sunflower operations.
Net sales for the quarter ended 31 August were $1.9bn, down 8.3% from the 2008 fourth quarter.
For the full fiscal year ended 31 August, Monsanto’s net sales rose 3% to $11.7bn and net income was $2.1bn, up slightly from $2.0bn a year earlier.
Record full year net sales were driven by higher worldwide corn and soybean seed and traits revenue in the ?xml:namespace>
Overall, seed and traits revenue made up more than 65% of gross profit, which was 17% higher than in fiscal 2008, the company said.
Seeds and traits, which was targeted to account for 85% of company business in 2012, was expected to cross the $5bn gross profit mark for the first time in 2010, the company said
($1 = €0.68)
Additional reporting by Stefan Baumgarten | http://www.icis.com/Articles/2009/10/07/9253562/us-monsanto-net-loss-deepens-in-fourth-quarter.html | CC-MAIN-2014-52 | refinedweb | 229 | 64.2 |
I'm pretty new to programming (especially C++), and I'm having a problem using cin.getline.
The program is suppose to get the title of a book (as well as other things), but completely skips over it and displays 'Title: ' and then immediately displays 'Price: '.
What is really driving me insane is that I copied out all of the code relevent to getting and displaying the title and put it in another program all by itself and it worked perfectly.
I'm sure I'm making some very stupid mistake, but I've been looking through it for days and can't find what I'm doing wrong.
I'd really appreciate any help anyone could give me. Thanks!I'd really appreciate any help anyone could give me. Thanks!Code:#include <iostream> #include <iomanip> using namespace std; int main() { const int SIZE = 50; int quantity; char date[9], isbn[20], title[SIZE], again='Y'; float price, subtotal, total, tax; while (again == 'y' || again == 'Y') { cout << "\n"; cout << "Date: "; cin >> date; cout << "Quantity of Book: "; cin >> quantity; cout << "ISBN: "; cin >> isbn; cout << "Title: "; cin.getline(title, SIZE); cout << "Price: $"; cin >> price; subtotal = quantity * price; tax = subtotal * 0.06; total = subtotal + tax; cout << "\n"; cout << "Serendipity Booksellers\n"; cout << "\n"; cout << "Date: " << date << endl; cout << "\n"; cout << "Qty\t"; cout << "ISBN\t\t"; cout << "Title\t\t\t\t\t"; cout << "Price\t"; cout << "Total" << endl; cout << "________________________________________________________________________________"; cout << "\n"; cout << quantity << "\t"; cout << isbn << "\t"; cout << title << "\t\t\t"; cout << "$" << setprecision(2) << fixed << price << "\t"; cout << "$" << setprecision(2) << fixed << subtotal << "\t"; cout << "\n"; cout << "\t\t\tSubtotal " << setw(42) << "$" << setprecision(2) << fixed << subtotal; cout << "\t\t\tTax " << setw(48) << "$" << setprecision(2) << fixed << tax; cout << "\t\t\tTotal " << setw(45) << "$" << setprecision(2) << fixed << total << endl; cout << "\n"; cout << "Thank You for Shopping at Serendipity!\n"; cout << "Would you like to process another transaction (y/n). "; cin >> again; } return 0; } | http://cboard.cprogramming.com/cplusplus-programming/91099-getline-problem.html | CC-MAIN-2014-49 | refinedweb | 320 | 54.86 |
but i am on Ubunto 18.04
but i am on Ubunto 18.04
I see ;3 tnx for the info.
but i normally started the app with
webdev serve --auto restart
So i can use any other browser
flutter pub global run webdev serve
webdev could not run for this project.
You have a dependency on `flutter` which is not supported for flutter_web tech preview. See for more details.
pub finished with exit code 78
flutter run -d chrome
Does anyone know of a good way to share mobile code with flutter_web?I am wanting something like
import 'package:flutter_web/material.dart';
import 'package:flutter/material.dart';
Another exception was thrown: NoSuchMethodError: invalid member on null: 'findRenderObject'
flutter run -d
import 'io_impl.dart'
if (dart.library.js) 'html_impl.dart'; | https://gitter.im/flutter/flutter_web?at=5d643835a080d70ab586d56a | CC-MAIN-2021-25 | refinedweb | 130 | 60.72 |
Products and Services
Downloads
Store
Support
Education
Partners
About
Oracle Technology Network
Name: ynR10250 Date: 11/27/2003
On the system with Gnome & xkb, use any layout with non-latin
additional group of symbols (for instance, Russian). There's
an example of InputDevice section in XFree86 config file:
Section "InputDevice"
Identifier "Keyboard0"
Driver "keyboard"
Option "XkbRules" "xfree86"
Option "XkbModel" "pc105"
Option "XkbLayout" "us,ru"
Option "XkbOptions" "grp:shift_toggle"
EndSection
The same layout, at least in theory, may be created at runtime
by calling
setxkbmap -layout "us,ru" -option "grp:shift_toggle" -rules xfree86 -model pc105
Switch between groups by pressing left then right Shift.
Compile and run a simplest test:
import java.awt.*;
public class AcTest {
static Frame frame = null;
static TextField tf = null;
public static void main( String args [] ) {
frame = new Frame("Input test");
tf = new TextField();
frame.add( tf);
frame.setSize(200,80);
frame.setLocation(300,300);
frame.setVisible( true );
}
}
Switch to Russian, select text field and type 'q':
there must be 0x0439 character added but will be no input at all.
Also, no events generated.
======================================================================
CONVERTED DATA
BugTraq+ Release Management Values
COMMIT TO FIX:
mustang
EVALUATION
Name: ynR10250 Date: 12/01/2003
it looks like xkb-based localization never worked neither in 1.4.2
nor with motif toolkit in 1.5.0b29. Installing Gnome+xkb on Solaris, we
get (in XAWT) Arabic right-to-left output instead of Russian which is only
slightly better than nothing. To fix, we need to map most keysyms>256
to correct Unicode characters. It may be not altogether easy, so I suggest
commiting the fix to dragonfly.
###@###.###
======================================================================
Name: dmR10075 Date: 12/23/2003
To map keysym to unicode characters we can use XwcLookupString. It returns
string consisting of characters, in a simple case it will be exactly one character of
input we need.
How we can't get AWT key code so easily. The question is - do we need to get it? If I press
russian letter 'A' which AWT key code should I get in KEY_PRESSED?
We probably can perform complex lookup since the map AWT keycode <-> X11 key sym
is only for Latin-1 character+some additional characters. We can probably ask for keyboard
mapping for different mapping planes, find one which contains keysym for the current
keycode which maps into AWT key code and return that AWT key code.
###@###.### 2003-12-23
======================================================================
Name: dmR10075 Date: 12/24/2003
I investigated XKB and found no way to get first Latin-1 plane of the keyboard if the input is currently
on another plane(group <-> plane). It seems like, since XKB limits group count to 4, Gnome decides to
not use XKB groups but rather reinstall 1st group with different maps when switch happens. In my
configuration, there is always only one group and it is the current group. So, for non-Latin-1 groups,
we will always get AWT keycode 0 because we are unable to map local-specific keysym into Latin-1.
Possible fix might be to bring ALL keysyms into Java API(as constants, into KeyEvent, in addition to
Latin-1 and some special keysyms).
###@###.### 2003-12-24
======================================================================
After fix to 4360364, XAWT version should work properly with XKB in Mustang, on both Linux and Solaris.
Note that Solaris may be shipped with Xorg which doesn't work without XKB.
###@###.### 2005-05-25 09:56:02 GMT | http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4960727 | CC-MAIN-2013-48 | refinedweb | 560 | 60.85 |
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.10) Gecko/20050716 Firefox/1.0.6
Build Identifier: Mozilla Thunderbird version 1.0.6 (20050716)
Problem first found when developing a Microsoft Access database.
There is a facility to email a list of people from the database. A process reads
every record, puts all the email addresses into a variable (varEmail) and sends
the variable to the Email program with this VBA code:
DoCmd.SendObject acSendNoObject, , , varEmail
The default Email program will open and place all the addresses into the "To"
line. The user may then complete the email message and send.
This procedure should work with any MAPI compliant email program. It works well
with Outlook, Outlook Express and Eudora.
However with Thunderbird, Access returns and error message that there were "Too
many message recipients". There are in fact about 150 addresses. I can cut and
paste the entire list into Thunderbird's address line, it just will not accept
that many addresses from Access. Note: I did not actually send the message - not
wanting to upset all those users. I refer to an already logged bug - 113251
which may yet cause problems with too many recipients.
The process works with Thunderbird if there are not too many recipients eg 50
Also noted by another user: when cut/paste more than 200 addresses, Thunderbird
responds with the following message:
"The size of the message you are trying to send exceeds a temporary size limit
of the server. The message was not sent, try to reduce the message size and try
again. The server responded: Too many recipients."
Reproducible: Always
Steps to Reproduce:
1.Issue the VBA code from the Access database
2.
3.
Actual Results:
Error message - Too many Recipients"
Expected Results:
Inserted all recipients into the "To:" box
Refer to Bug 113251
I use Thunderbird 1.5.0.7 (20060909).
I want to prepare a mail with many recipients with the MapiSendMail command. I found out that Thunderbird accepts up to exactly 100 recipients, 101 and more recipients are rejected with the error MAPI_E_TOO_MANY_RECIPIENTS.
Why only 100 recipients? I guess the developer thought nobody needs more than 100 recipients so he just put this limit here. But I need more recipients! Please remove the check of the number of recipients and allow unlimited recipients. Thanks! BTW: Outlook has no problem with more than 100 recipients...
TB version 3.0a1pre (2008050203) in WinXP
I was able to paste >900 comma delimited email-id to the TO: field
on pressing tab to move to next line/field, TB started to reformat the mail id to one id per line and gave multiple script too long error message.
I kept pressing "Continue" many times and finally the script finished splitting email-id list and reformatting one per line.
So it looks like WORKSFORME.
Following is the "script too long" message I got.
========== Script too long message ==========
A script on this page may be busy, or it may have stopped responding. You can stop the script now, or you can continue to see if the script will complete.
Script: chrome://messenger/content/messengercompose/addressingWidgetOverlay.js:1058
============== end of message ==============
BTW: I have SMTP/POP email account not the MAPI states that:
> There appears to be a limit of approximately 60 addresses when sending messages > if you enter each address separately.
So what is the current official number of allowed recipients (either in one line or separate) ?
(In reply to comment #4)
> So what is the current official number of allowed recipients (either in one line or separate) ?
Przemyslaw Bialik, read RFC 2822, please.
>
> 2.1.1. Line Length Limits
> There are two limits that this standard places on the number of
> characters in a line. Each line of characters MUST be no more than
> 998 characters, and SHOULD be no more than 78 characters, excluding
> the CRLF.
This is not limitation by architecture or design. Practical reason. It's described as following in the "2.1.1. Line Length Limits" section.
> However, there are so
> many implementations which (in compliance with the transport
> requirements of [RFC2821]) do not accept messages containing more
> than 1000 character including the CR and LF per line, it is important
> for implementations not to create such messages.
And maximum number of field(==A mail header, To: in this bug's case) is ONE.
> 3.6. Field definitions
> Field Min number Max number Notes
> to 0 1
> cc 0 1
> bcc 0 1
In contrast to RFC 2822, RFC2821(SMTP) itself doesn't limit number of RCPT commands(RECIPIENT). This is the reason why mailing list(and spammers too) can send a mail to many persons at once with short To: <mailing_list_address>(usually no CC:/no BCC:. i.e. sent as bcc).
Further, because RFC2821(SMTP) doesn't care for mail header content(defined by RFC2822), spammers can write any From:/To:/CC: header in spam mail.
Hi,
we have come across this bug too. We have a mission-critical foxpro database application which is being used by upward of 50 staff. One of its functions is to send an email to users within the database and like the other reports, this fails when there are more than around 100 email addresses. This is forcing users who want to use TB to go back to Outlook and putting egg on our faces for recommending TB.
I don't think I believe the RFC line limit is the issue. If you look at section 2.2.3, of the same document it says:
This bug is a VERY serious problem for us. What can we do to get it fixed?
Hi again,
I've had a root around in the code and it looks like fixing this issue would be pretty straightforward -- in that you can just increase the limit. The patch below is written against the latest release of thunderbird, 2.0.18.
At the minute I don't have a build environment for TB but I will try and set one up to test this shortly.
We _really_ don't want to maintain our own custom version of thunderbird so it would be far preferable if this could be accepted into the mozilla trunk. I don't believe the quoted RFC justifies this limitation and it has been said that Eudora and Outlook don't show this problem.
Gavin
--- mozilla/mailnews/mapi/mapiDll/MapiDll.cpp 2004-04-29 20:58:22.000000000 +0100
+++ mozilla2/mailnews/mapi/mapiDll/MapiDll.cpp 2008-08-26 17:43:39.000000000 +0100
@@ -45,7 +45,7 @@
#include "msgMapiMain.h"
#define MAX_RECIPS 100
-#define MAX_FILES 100
+#define MAX_FILES 2000
#define MAX_NAME_LEN 256
Ahem! In a little haste, that patch was ever so slightly wrong :-)
This time it should be right, see below.
Gavin
--- mozilla/mailnews/mapi/mapiDll/MapiDll.cpp 2004-04-29 20:58:22.000000000 +0100
+++ mozilla2/mailnews/mapi/mapiDll/MapiDll.cpp 2008-08-26 18:05:09.000000000 +0100
@@ -44,7 +44,7 @@
#include "msgMapi.h"
#include "msgMapiMain.h"
-#define MAX_RECIPS 100
+#define MAX_RECIPS 2000
#define MAX_FILES 100
The limit up 100 recipients is still there in the current version 2.0.0.16 (20080708) and the MapiSendMail command. Gavin has found the line of code: Hey mozilla-team, it's only ONE line of code to change! Now it's very disappointing to get the message that Dan Mosedale has changed the assignment to "nobody". Don't change the assignment change the single line of code!
(In reply to comment #9)
> Now it's very disappointing
> to get the message that Dan Mosedale has changed the assignment to "nobody".
That was a block change to remove someone from the assignee field who is currently not working on anything mozilla.
> Don't change the assignment change the single line of code!
Gavin, if you want to get your fix into the tree, please take a look at
You'll need to make it an attachment for starters, and provide a patch for the current trunk builds as well. For getting the source for these see
Hi,
(In reply to comment #10)
> Gavin, if you want to get your fix into the tree, please take a look at
>
>
> You'll need to make it an attachment for starters,
Of course :-)
> and provide a patch for the current trunk builds as well. For getting the
> source for these see
>
I'll try and do this next week, thanks.
Gavin
Hi,
Apologies for the _huge_ delay on this but I haven't had much time for it myself. A student here in the college has been tasked with setting up a build environment, making the above change to the code and testing.
Initial indications are very positive. We used our foxpro database application to send a mapi call with over 500 addresses in BCC. This appeared to work perfectly. We didn't actually send the email, but I don't think that should be an issue. Thunderbird popped up a new email window with the full list of emails in the BCC..
Gavin
(In reply to comment #12)
>.
Do you also intend to fix Trunk ? Do you intend to release this "stress" tool in the open ?
Hi,
(In reply to comment #13)
> Do you also intend to fix Trunk ?
Yes. We're keen to get this fixed and never have to worry about it again. We have the v3-beta2 downloaded to test it against that too.
I know I have some things to do (resubmit as an attachment) which I'll do shortly. I have to check if the patch is different for
> Do you intend to release this "stress" tool in the open ?
Absolutely. Though it remains to be seen how useful it will be to others. All we have planned at the moment is a short piece of code which will allow the user to pass a file with an arbitrary list of email addresses to a MAPI sendmail call. This will test the limit of how many recipients we can safely pass. If you have ideas for further features, let me know and I'll see what we can get done.
It looks like the thunderbird mapi code doesn't change very often so I'm not sure how much is needed here.
Gavin
Created attachment 373713 [details] [diff] [review]
patch to increase the maximum recipients for MAPI calls from 100 to 2000
following the discussion on this bug and some testing, I'd like to request this patch be reviewed.
David does this needs super-review to land ?
Yes, bienvenu: wanna sr it too?
Thanks for the patch, this is now checked in to trunk:
Many thanks for accepting the patch.
I realise this is the wrong time to say this but does anyone know what would be a reasonable limit for this. Our choice of 2000 was fairly arbitrary and someone here tells me that even that might not always be enough.
Is there a sensible limit which should be placed? Does TB itself have a maximum recipients? Is there any virus-spreading implication in having the number very large?
(In reply to comment #19)
>
> Is there a sensible limit which should be placed? Does TB itself have a
> maximum recipients? Is there any virus-spreading implication in having the
> number very large?
As I remember, virus-spreading was the whole reason for having this number be relatively small. The code was written around the time some MS products were getting infected regularly. But if you can make one mapi call, you can make two, so it's not like a low number is really making it that much harder for malware.
I don't know what a reasonable limit would be - I think the way the code is written, it does require the limit to be a static number, but I don't remember for sure.
Yeah, it's a compiled constant. The number is declared to the pre-processor:
#define MAX_RECIPS 100
and used only once:
if (lpMessage->nRecipCount > MAX_RECIPS)
return MAPI_E_TOO_MANY_RECIPIENTS ;
You could easily remove the check entirely, but I'm not sure that would be a good idea. You could make it configurable which might be an interesting compromise in that it could be set to something low like 100 by default but then raised by users who actually need that.
....as you say though, if a virus can send one it can send as many as it likes so perhaps a limit isn't really that useful.
Is there any possibility that this fix could be put into a stable release of v2 any time soon? It doesn't appear to be in v2.0.0.23??
Thanks,
Gavin
To ask for it to be included into v2.0.0.x, set the approval1.8.1.next? flag on the patch. At least it's very small, and i haven't heard of any problems caused by it.
Comment on attachment 373713 [details] [diff] [review]
patch to increase the maximum recipients for MAPI calls from 100 to 2000
just hoping to get this into a stable release asap.
thanks
I see that thunderbird v2 releases are (understandably) rare at this point.
Can I assume that any new release of Thunderbird (v2 or v3) will contain this fix?
Sorry, I'm a little ignorant of how the patch approval process. We still have staff suffering from this and would rather avoid deploying a build of our own. Is a further release of v2 likely or do we need to wait for v3?
This will be in v3, which should come out in a matter of weeks.
Comment on attachment 373713 [details] [diff] [review]
patch to increase the maximum recipients for MAPI calls from 100 to 2000
Approved for 1.8.1.24, a=dveditz for release-drivers
fixed landed for 1.8.1.24
Can someone who was encountering this issue attempt their e-mail using the nightly Thunderbird 2.0.0.24pre build? This can be found at. It would be good to verify that this issue is fixed. | https://bugzilla.mozilla.org/show_bug.cgi?id=305168 | CC-MAIN-2016-36 | refinedweb | 2,353 | 72.97 |
Bulma CSS Framework
Install Bulma into React.js
Bulma is a modern CSS framework.
I have always been a big fan of Bootstrap. Recently I try to some other frameworks. But I Recently find the Bulma framework.
Bulma is a modern CSS framework. Bulma is open source like bootstrap. Bulma also provides you ready to use frontend components that component help make the website fast and easy. You also easily combine with other components.
I don't use Bulma soo much on my project daily basis. I’m just exploring the Bulma framework and try to understand how to use it.
Note:
In This Article, I'm told how to add the Bulma framework in react app. if you create an intarweb with Bulma. I personally recommend you use the react-bulma-components library to create your own web app.
react-bulma-components is a great way to add bulma to your app. react-bulma-components also provide in-build react components for your app.
Installation
Most common two ways to add Bulma in your project. In Project, I always recommended you to add Bulma help of Npm or yarn.
- Contact delivery network CDN
- Npm or Yarn
- Requirements
Contact delivery network CDN
Bulma also provide a Contact delivery network
<link rel="stylesheet" href="">or@import ""
Npm or Yarn
My Recommended way to add Bulma into reacting app.
npm install bulma
or
yarn add bulma
Requirements
Bulma works correctly in your reactJS. Firstly, add two lines of code in our react app.
Follow two steps
- HTML5 doctype
- Add meta tag
- How to use
HTML5 doctype
Firstly define html5 doctype in your HTML. Document Type Declaration gives instructions to the web browser about the version of the markup language.
<!DOCTYPE html>
Add meta tag
Firstly setup doctype after adding a response meta tag in your app. response meta helps responsive your app to different web browsers.
<meta name="viewport" content="width=device-width, initial-scale=1">
Note
If you create react, use
npx create-react-app my-appthe npx command. By default, npx adds HTML 5 doctype and also adds a responsive meta tag in-app.
How to use it
two ways you add Bulma into react.js
Let's start code
- CDN ways
- NPM ways
CDN ways
You copy the CDN file and paste it into the react.js public/index HTML file in CDN ways. After saving it.
<" /><link rel="stylesheet" href=""><title>React App</title></head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div></body>
</html>
NPM ways
Firstly go to react index.js app and import Bulma CSS files into node_modules.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';import 'bulma/css/bulma.min.css';ReactDOM.render(<React.StrictMode><App /></React.StrictMode>,document.getElementById('root'));
After start write coding in react app.js.
import './App.css';function App() {return (<section className="section"> <div className="container">
<h1 className="title"> Hello World </h1>
<p className="subtitle"> My React app with <strong>Bulma</strong> </p>
</div></section>
);
}export default App;
Reference
Getting started with Bulma
Getting started with Bulma You only need 1 CSS file to use Bulma Bulma is a CSS library. Bulma means it provides CSS…
bulma.io
jgthms/bulma
Modern CSS framework based on Flexbox. Contribute to jgthms/bulma development by creating an account on GitHub.
github.com
Conclusion
In my opinion, Bulma is a great CSS framework. You build a responsive website very easily and in fast ways. You defiantly use it and build its own site.
Bulma also provides scss support for developers. You easily customize the sass variable according to your own thought.
Bulma provides all browser support. Like Chrome, Edge, Firefox, Opera, and Safari.
Bulma also partially support Internet Explorer (10+). | https://medium.com/frontendweb/install-bulma-into-react-js-b835b2fe2204?source=post_internal_links---------7---------------------------- | CC-MAIN-2022-27 | refinedweb | 633 | 51.34 |
I'm having trouble doing a challenge in ruby about palindromes.
I actually looked too many sources and i think my brain melted a bit as i am a novice programmer.
Lemme sum up the question :
So from user we get beginning value ending value, and a depth value.We take the beginning value and check If the number is a palindrome,if it isn't then we add its reversed to itself( 20, reverse(20)=02, add , 22) and check the number we find if its a palindrome.If it isn't we take the calculated number and add its reversed to itself.But we only can do that "depth" value times.
And print if we find a palindrome through those calculations we print value ----> xxxx if not we print value ----> special number.
I'm able to find palindromes, through given and ending value.But i just cant implement the depth thing.My problem looks a lot like Setting a Limit on loops and calculating palindromes in C programming but since i'm a ruby novice i cant make sense of C for now.Any help will be appreciated.
Edit : We do that like x to y , beginning value to ending value, like if they type 20 as beginning and 30 as ending value, we check 20 if its a palindrome add its reversed etc.Once we finish checking it we check the next number, 21 then 22,23... to 30.
def doit(n, max_tries) max_tries.times.each do rev = n.to_s.reverse.to_i (n == rev) ? (return n) : n += rev end nil end doit(22, 1) #=> 22 doit(21, 1) #=> nil doit(21, 2) #=> 33 doit(137, 1) #=> nil doit(137, 2) #=> 868 doit(1373, 2) #=> nil doit(1373, 3) #=> 9119 doit(13732, 9) #=> nil doit(13732, 10) #=> 134202431 | https://codedump.io/share/1m4cO2b9zUCR/1/finding-palindromes-by-adding-its-reversed-to-itself-through-x-to-y-doing-only-depth-number-of-calculation | CC-MAIN-2018-13 | refinedweb | 300 | 80.82 |
Please review and help troubleshoot
Here's the code:
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range(2, x - 1):
if x % n == 0:
return False
break
else:
return True
Please review and help troubleshoot
Here's the code:
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
else:
for n in range(2, x - 1):
if x % n == 0:
return False
break
else:
return True
First, test your for loop. If you write "for n in range(2,x-1)" and print out the "n", what will the console prints out? Maybe test with number instead "x-1". Then you know what you have to write.
Second, if "x" is greater than 2, always x-1 will define your return. If x = 9, the for loop will test number 8 last and it will return true, but 9 is not prime.
Think about it.
When x == 9, n reaches 7, not 8.
for n in range(2, x - 1):
x - 1 needs to be 9 in order to reach 8. Remember
range() does not include the upper bound.
a = range(2, 9) print a # [2, 3, 4, 5, 6, 7, 8] a = range(2, 9 - 1) print a # [2, 3, 4, 5, 6, 7]
The code is valid as written, and follows the instructions. The real issue is,
else: return True
The above is inside the if statement so returns on the first iteration in that loop that does not return False.
That is why i wrote first that he have to check what will prints out for "n" if the range is (2,x-1). but u wrote it down
You should use: for n in range(2,x)
because range(a,b) function ends at b-1, so if x is 3 and u use x-1, range function will ends on 1 which is even smaller than 2.
Besides that, you should put 'return True' out of if/else statement.
A post was split to a new topic: My code is that can you help me
This is not what the instructions ask for. The range is not the problem, as has been stated repeatedly in this topic. It's the placement of the final
else statement that is the problem.
- Define a function called is_prime that takes a number x as input.
- For each number n from 2 to x - 1, test if x is evenly divisible by n.
- If it is, return False.
- If none of them are, then return True.
The ambiguity here is that we don't know if the author means literally, x -1 or figuratively, since a
range(2, x) it technically 2 through x - 1.
At any length, it won't matter. So long as we do not iterate up to and including
x we'll be fine.
There are other limits that we could impose, but that is not what the exercise asks for. We should try to complete it according to instructions, then practice writing different approaches on our own.
Consider, what if the limit is only one-half of
x, plus 1 for good measure?
What if the limit is square-root of
x, plus 1?
We rarely see problems with the range, but we most frequently see problems with indentation.
Thank you for your reply. I agree in most cases range is not a problem, but I was just taking about the matter the warning shows, you can see in the screenshot the warning is the program fails in execute is_prime(3), and it returns None.
If the problem comes from the indent of last line, it will return False or True instead of None. (Indeed it's also another problem)
Range(2,x-1) works well with numbers greater than three, but here the website will check if 3 is feasible for this function.
When x is 3,
for n in range(2,2):
does not execute. This is where the
else in line with
for will catch it and return True.
for n in range(2, x-1): else: return True
or more simply
return True
No
else needed.
if x < 2: return False for n in range(2, x): # the 2 catches all even numbers for x. if x % n == 0: return False return True
Now picture x being 3. It won't enter the loop because the range is too small. Anything that makes it past the loop (and the first condition) will always be True, hence, Prime. | https://discuss.codecademy.com/t/6-is-prime-troubleshooting-help/54438 | CC-MAIN-2018-26 | refinedweb | 761 | 87.45 |
i am trying to invoke ISP boot-loader from iap command. Found it is generating auto-baud and responding back with required details(mentioned in user manual UM10800 of LPC 824 page no 12-13).
Problem what i am facing is it is not staying in boot mode for long time and it resetting.
Can someone help me how to sort out this problem?
Below is the code to reinvoke isp.
#define REINVOKE_ISP 57
int iap_reinvoke_isp(void)
{
cmd_table.cmd_code = REINVOKE_ISP;
__disable_irq();
iap_call(&cmd_table, &result_table);
__enable_irq();
return (int)result_table.ret_code;
}
Hi Ranjith,
Sorry for my later reply, I just get your question post case.
Next time, you need to use @ somebody, then the detail person will get the message.
Now, do you mean, in IAP, if you use invoke ISP bootloader command, then you will enter ISP mode, but if you don't do the operation with the according ISP, the ISP mode will be exit? Is the question right? In your side, how long it will be exit, how did you find the mode is exit(do the reset)?
Please confirm the question, then I will do the testing on my side.
Have a great day,
Kerry
-----------------------------------------------------------------------------------------------------------------------
Note: If this post answers your question, please click the Correct Answer button. Thank you!
----------------------------------------------------------------------------------------------------------------------- | https://community.nxp.com/thread/461991 | CC-MAIN-2020-10 | refinedweb | 212 | 73.78 |
Bulat Ziganshin wrote: > Hello Simon, > > Tuesday, November 14, 2006, 4:02:09 PM, you wrote: > > >>>>>>>#ifdef mingw32_HOST_OS >>>>>>> if ((how & O_WRONLY) || (how & O_RDWR) || (how & >>>>>>> O_APPEND)) return _sopen(file,how,_SH_DENYRW,mode); >>>>>>> else >>>>>>> return _sopen(file,how,_SH_DENYWR,mode); >>>>>>>#else >>>>>>> return open(file,how,mode); >>>>>>>#endif > > >>>i.e. no sopen at all? in this case, other parts of library should >>>make proper locking for unix. > > >>Yes, we do. See >>. > > > after some thought, i still want to complain. locking files while it's > open on Windows and using special procedure on Unix is internal trick > of Handle-based I/O library. it's bad that this trick was exposed as > non-consistent behavior of c_open call which, by its name, is > proposed for general use by other libs > > i think that proper design was either to make such function internal > to GHC.Handle module, or incorporate all necessary locking logic into > the c_open/c_close and make exhaustive doc-comment to warn users > thinking that c_open should be the same as raw C open() call > > in current situation when some code besides of GHC.* may rely on this > strange inconsistent behavior i think at least commenting it will be a > good idea Well, c_open isn't a visible API: the module System.Posix.Internals is hidden in the Haddock documentation. It isn't hidden in the package spec, but that's because the unix package requires it. Maybe in your reorganisation of the base package you could clean this up. Bottom line: it's not intended for user consumption, so I don't buy your argument. In fact I'd rather use the proper Win32 API instead of CRT functions in the IO library. Cheers, Simon | http://www.haskell.org/pipermail/cvs-ghc/2006-November/032687.html | CC-MAIN-2013-20 | refinedweb | 282 | 61.67 |
David Rasmussen's BlogMostly OneNote stuff. Server2006-06-13T14:51:00ZOneNote 2010 will be available in more places and more ways<P style="MARGIN: 0in 0in 10pt" class=MsoNormal><SPAN style="mso-ascii-font-family: Calibri; mso-hansi-font-family: Calibri"><FONT size=3 face=Calibri. </FONT></SPAN></P><SPAN style="mso-ascii-font-family: Calibri; mso-hansi-font-family: Calibri"><FONT size=3 face=Calibri> <P style="MARGIN: 0in 0in 10pt" class=MsoNormal><BR.<SPAN style="mso-spacerun: yes"> </SPAN>We’re not announcing any details about other SKUs yet. Overall we’ve seen a lot of interest in OneNote and we’re trying to make sure customers will be able to get it easily whether you use Office at home or at work.</P> <P style="MARGIN: 0in 0in 10pt" class=MsoNormal><BR>I look forward to being able to share more details with you about the new features in OneNote 2010 in future posts.</FONT></SPAN><?xml:namespace prefix = o<o:p></o:p></P><img src="" width="1" height="1">DavidRasmussen Print Driver – A 64 Bit Solution<p><em><font size="3">Short version: I have a solution for those of you needing a 64 bit OS solution for printing to OneNote. Read on for details.</font></em></p> <p. </p> <p…).</p> <p>You can see the details, download, installation and usage instructions for the <a href="">XPS2OneNote 64 bit OneNote print driver</a> solution on <a href="">codeplex</a>. </p> <p>I hope it works well for you. Please feel free to leave me comments and suggestions here.</p> <p> </p> <h1>Some additional comments</h1> <p>You can ignore all of this… unless you’re interested in context.</p> <ul> <li>First, please let me repeat my sincere and humble apology that the included print driver didn’t work for 64 bit OSes as I wrote in my <a href="">original post explaining why the Send to OneNote 2007 print driver doesn’t work on 64 bit OSes</a>. I know it seems lame. </li> <li). </li> <li… </li> <li… </li> <li. </li> <li. </li> <li>And while I know it’s not much consolation, we wrote in the <a href="">System Requirements</a>. </li> </ul> <p>With that all said I hope this solution works for you and feel free to leave me comments about it.</p><img src="" width="1" height="1">DavidRasmussen 64 bit print driver<p><font size="3">__</font></p> <p><font size="2"><em>UPDATE: Please see my </em></font><a href=""><font size="2"><em>recent post on a solution for Printing to OneNote on 64 bit OSes</em></font></a><font size="2"><em>.</em></font></p> <p> </p> <p> </p> <p>__</p> <p. </p> <div class="commentBodyStyle livepreview"> </div> <div class="commentBodyStyle livepreview">Context:</div> <div class="commentBodyStyle livepreview". <br /> <br /. <br /> <br /. <br /> <br /. <br /> <br /. <br /> <br /. <br /></div><img src="" width="1" height="1">DavidRasmussen 2007 SP1 - Can't Create notebooks On Some Servers<p>Sorry. We broke your OneNote. </p> <p <a href="">WebDAV</a>. This is what we call a "regression" (when in fixing something you break something else). We feel very bad about this and we're working hard to address it. </p> .).</p> <p>Here are the details and a work around.</p> <h1></h1> <h1>Issue: can't create notebooks on Windows file share running WebDAV</h1> <ul> <li>If you try to create a new notebook on a Windows file share server that also runs WebDAV then you will fail to create the notebook. </li> <li>For example if you try to create a notebook called <em>notebookname</em> at <a href="file://\\fileservername\filesharename">\\fileservername\filesharename</a> you'll get an error message like: "OneNote cannot create a new notebook at: http://<em>fileservername</em>/<em>sharename</em>/<em>notebookname</em>"</li> </ul> <h1>Workaround:</h1> <p>To work around this follow these steps.</p> <ol> <li>Go to the folder where you want the notebook in Windows Explorer (e.g. go to <a href="file://\\fileservername\filesharename">\\fileservername\filesharename</a> )</li> <li>Create a new folder with the name you want the notebook to have (e.g. <em>notebookname</em> )</li> <li>Right click that folder and choose "Open as Notebook in OneNote"</li> <li>The folder will open up as a blank notebook in OneNote. Then click on the message in the middle of the screen to create the first section and you're good to go.</li> <li>Alternatively: instead of step 3 above you can start OneNote then go to "File"->"Open" -> "Notebook" and then select the folder you created in step 2.</li> </ol> <h1>Background:</h1> <ul> <li <a href="">UNC</a> path, and the server is also running a WebDAV server then this logic has a flaw in it that causes it to try the WebDAV redirector (<a href="">UNC</a> paths can be valid WebDAV paths...).</li> <li>This won't affect many people in larger companies where Windows file servers and Web servers or SharePoint servers are usually kept distinct for clear role separation.</li> <li>It is more likely to affect small business scenarios where a server may play multiple roles and is potentially acting as a web server as well as a file share. Examples might be Windows Small Business Server depending on how it's configured.</li> </ul><img src="" width="1" height="1">DavidRasmussen Shared Notebooks - Options and Troubleshooting - Part 2: Notebooks On SharePoint<p>Continuing from my <a href="">previous post about OneNote Shared Notebooks</a> on Windows File Shares, this one will focus on OneNote shared notebooks on SharePoint servers. The advantages, disadvantages, and troubleshooting tips.</p> <p> </p> <h1>Notebooks on SharePoint Servers</h1> <h2>Overview</h2> <ul> <li><a href="">SharePoint</a> is a great team repository, a place to share documents, lists, calendars, and so on. <ul> <li>You can access documents from a browser with more context than just a file list on a file share. </li> <li>There are lots of nice features for custom solutions like workflow support, metadata support, search and query by metadata across an entire enterprise and so on that I won't go into. </li> </ul> </li> <li>Many teams have all their shared documents on SharePoint servers for these benefits. </li> <li>In that case, it makes sense to have your OneNote shared notebooks in the same place on SharePoint. </li> <li><strong>Internet access to your notebooks</strong> is one significant benefit </li> <ul> <li>SharePoint is accessible via http over port 80. </li> <li>It can be made available more easily across the internet. </li> <li>Many service providers offer SharePoint hosting services </li> <li>If you have a OneNote shared notebook on a publicly hosted SharePoint server you will be able to access it with OneNote from anywhere, and collaborate with people anywhere. </li> </ul> <li><em>Note: you still need OneNote to access the notebook, not just a web browser. However, you can optionally publish an html web view of your notebook using the </em><a href=""><em>OneNote Web Exporter PowerToy</em></a><em>.</em> </li> </ul> <p> </p> <p><strong>Performance and Reliability</strong></p> <p>More things can go wrong when syncing OneNote notebooks to SharePoint vs syncing to a Windows file share. As there is more complexity and variety in the components and configurations involved.</p> <ul> <li><u>Sync times are much longer</u> on SharePoint</li> <ul> <li>OneNote syncs every 10 minutes to SharePoint, whereas it syncs every 30 seconds on Windows file shares.</li> <li>The worst case time between making a change and others seeing it is 20 minutes (vs a minute on a file share).</li> </ul> <li>A change to a OneNote section file on SharePoint <u>requires the whole file to uploaded or downloaded</u></li> <ul> <li>On Windows file shares, OneNote can read/write just the bits in the file it needs to update. This is very efficient.</li> <li>However, file access on SharePoint uses <a href="">WebDAV</a></li> <li>WebDAV does not support byte range read/write (also known as <a href="">Partial Get/Put</a>)</li> <li>Thus OneNote must upload or download the entire file. </li> <li>This uses more bandwidth, hence the reason for the 10 minute sync interval.</li> <li>This is also the reason <a href="">why Embedded files are stored alongside the section file in a thicket folder</a> on SharePoint (whereas they are stored inside the .one file on Windows file shares). </li> </ul> <li><u>Authentication is a common problem area</u></li> <ul> <li>SharePoint supports <a href="">multiple authentication types</a> - including <a href="">Windows Integrated</a> (Kerberos or NTLM), <a href="">Basic</a>, <a href="">Digest</a>, Forms, and in some cases <a href="">Windows Live ID</a>.</li> <li>They each have some unique characteristics, and subtleties in behavior</li> </ul> <li><u>Vista vs XP client makes a significant difference</u></li> <ul> <li>Vista has a completely new improved WebDAV stack that OneNote uses</li> <li.</li> <li>On XP, Office uses a technology named"<a href="">Rosebud< "<a href="">Microsoft Office Protocol Discovery</a>" [<font size="1">scroll down halfway to 'Understanding Microsoft Office Protocol Discovery]</font> (<a href="">Front Page Server Extensions</a>) to SharePoint and avoids the XP WebDAV stack altogether.</li> <li>See my earlier post on <a href="">SharePoint - Access Denied</a> for some more details on differences between behavior on XP and Vista</li> </ul> <li>[<em>there's a lot more technical background information I could write here, but that's enough for now, and if I get many questions I'll add further clarifications later...]</em></li> </ul> <p><em></em></p> <p><strong>Troubleshooting Tips</strong></p> <p>The most likely problems you'll see with OneNote notebooks on SharePoint are related to authentication.</p> <ul> <li>Getting "Access Denied" infobar prompts</li> <li>Getting password prompts that keep popping up</li> <li>Failing to open a notebook (possibly after getting password prompts)</li> <li>Having read only access to the notebook (you can't type anything)</li> </ul> <p>Below are some steps that commonly solve these issues:</p> <ol> <li>Install Office 2007 SP1. It's available through <a href="">Microsoft Update</a> (so you may already have it installed) or for <a href="">direct download</a>. You can check if you have this installed by clicking "Help" -> "About Microsoft Office OneNote" in OneNote. The version number at the top should be 6211.1000 and say "SP1" in it. It has some relevant fixes to improve this.</li> <li>Confirm that <a href="">"Auto Detect Settings" is on</a> in Internet Explorer if you're using Vista.</li> <li>Install Vista SP1 (if you have Vista) from Microsoft Update as soon as it's available (soon). It has some relevant fixes.</li> <li>If your SharePoint site uses Basic Authentication (some hosting service providers use it) then you must use https:// for the URL path.</li> <li.</li> </ol> <p> </p> <p>[Sorry, it took a while to get around to part 2. I was out on vacation.]</p><img src="" width="1" height="1">DavidRasmussen Shared Notebooks - Options and Troubleshooting - Part 1: Windows File Shares<p... </p> .</p> <p>The key deciding factor in sharing your notebook is the location you choose to share it from and the technology used to access that. These include.</p> <ol> <li>Windows File Shares (otherwise known as SMB or CIFS shares) </li> <li>SharePoint servers </li> <li>USB drives / SD cards / other removable drives </li> <li>Windows Home Server </li> <li>WebDAV servers </li> <li>Peer replication technologies like FolderShare or Groove </li> <li>Other web storage services (Sky Drive, Office Live, etc.) </li> </ol> <p>I realize this list makes things look complex. In the basic scenarios things just work. But there's a great diversity of file sharing technology options out there that at least some people somewhere are using and it's worth being comprehensive.</p> <p>There are sub categories within each of these. I'll go over each in a separate post. This one will cover Windows File Shares.</p> <p> </p> <h1>Windows File Shares</h1> <h2>Overview</h2> <ul> <li>Windows File Shares are generally the best performing, fastest and most reliable place to share OneNote notebooks (I use them mostly) </li> <li>Work very well on home networks, or work networks </li> <li>Usually not available over the internet (although they can be with VPN software like <a href="">Hamachi</a>) </li> <li>Use the <a href="">SMB</a> (otherwise known as CIFS) protocol </li> <li>Available on Windows Servers (common in work environments), or personal Windows XP or Vista machines </li> <li>Mac OS and Linux also provide support for Windows File Shares using <a href="">SMB</a> </li> <li>On Linux <a href="">SAMBA</a> is the technology most often used to provide Windows File Shares using SMB </li> <li>Home network hard drives that are small Windows Files Share/SMB servers are becoming more popular and are cheaply available under brands like <a href="">Western Digitals "My Book", iomega, Maxtor, Buffalo, Linksys, DLink</a> etc. Technically these are <a href="">NAS</a> devices, and are usually small servers inside running Linux and <a href="">SAMBA</a>. I don't recommend these for reasons discussed <a href="#SAMBAissues">below</a>. </li> </ul> <h2>Performance and Reliability</h2> <ul> <li>Performance is very good. </li> <li>OneNote can access only the parts of the file it needs. It does not have to update the whole file when syncing. </li> <li>Syncs every 30 seconds. </li> <li>Generally very reliable, with the <strong><u>big exception of all </u></strong><a href=""><strong><u>SAMBA</u></strong></a><strong><u> based shares</u></strong> (see below) and some issues if you're using Windows Offline Files </li> </ul> <h2>Troubleshooting tips</h2> <p>Below are some potential issues, explanations and resolutions.</p> <ol> <li> <h3>Can't write to the notebook. Can't create it or save it to the windows share. </h3> <ul> <li>Confirm you have permissions </li> <li>As a simple test copy a small file (text file or something) up to the same folder location as the notebook using Windows Explorer. </li> <li>If this fails you don't have permission to access the share or file system. You need both share permissions and file system permissions (that's the most confusing aspect for some people). Here's a <a href="">technical article about the distinction between Share permissions and File System permissions</a>. I'll try and post a simpler guide later [TODO]. In general, if you <a href="">setup a Share on Vista the normal way</a>, then it takes care of these two types of permissions automatically (I think XP SP2 does too...). </li> </ul> <p></p> </li> <li id="SAMBAIssues"> <h3>On your networked hard drive or <a href="">SAMBA</a> share sections disappear (and other issues including possible corruption)</h3> <ul> <li>This applies to things like the <a href="">Western Digitals "My Book", iomega, Maxtor, Buffalo, Linksys, DLink</a> networked hard drives. </li> <li>Recovery: If you look in the folder on the network share, you'll often see an extra file with a name like "foo~RF12345678.tmp". Rename this to "foo.one" then open OneNote and sync and you'll probably have your file back. </li> <li>Details on this (and why <u>I don't recommend SAMBA shares</u>) below. I'd suggest you consider storing your OneNote notebooks somewhere else. </li> <li>Most of the network hard drives use a small Linux OS and <a href="">SAMBA</a> to provide the file share </li> <li>Many versions of SAMBA are badly behaved and don't fully and correctly implement SMB </li> <li>In particular many SAMBA implementations seem to have problems with ReplaceFile failing, which OneNote uses </li> <li>SAMBA, like much open source, has many different versions (100s) that have been picked up by the various different hardware manufacturers (running on multiple trimmed down variants of Linux), they've individually tweaked them, forked the code, and do not necessarily update them. The result is that while some of the latest versions of SAMBA do seem to implement ReplaceFile correctly, many of the networked hard drives seem to use versions that don't implement ReplaceFile well. Such is the nature of open source. [Whereas if you have a Windows Server, XP or Vista machine and you stay fully up to date on your Windows Updates they are all the same (well each OS is) and known to work and be reliable. ] </li> <li>This tends to hit OneNote more than other apps, because most apps don't use ReplaceFile. Most apps just open a file, with an exclusive lock on it, then save it and release when they're done. Because OneNote has multiple simultaneous users on a notebook things are a little more complicated. Also we use ReplaceFile to safely do operations like optimizing the file (we optimize a copy then replace the original, ReplaceFile is supposed to be atomic and safe). Other applications that tend to behave a little more like OneNote are Money and Quicken and things that have database type continual access. So these apps will often exhibit issues working against these networked hard drives too. </li> <li>Basically the most common and therefore well tested aspects of the SMB protocol and file system semantics work fine on these devices. But if you have an app that uses a broader set then they can run into trouble. </li> <li>Because of these issues above I'm not sure how much I'd trust these SAMBA hard drives, given other things that aren't well tested (like ReplaceFile) may be buggy too. We've seen other issues on SAMBA shares, including corruption. </li> </ul> </li> <li> <h3>Password prompts</h3> <ul> <li>You may get an infobar on the notebook (yellow message bar at the top of the page) saying that you need a password. </li> <li>Click this and then enter the user name and password for the notebook on which the server is located </li> <li>If you check "remember this password" then you won't get asked for it in future and OneNote will just be able to automatically sync. Otherwise you'll need to reenter it every time you restart. <br /></li> </ul> </li> <li> <h3>Windows Offline Files causes duplicate copies of sections if edited from more than one machine, or edits from one machine don't seem to be showing up or are lost.</h3> <ul> <li><a href="">Windows Offline Files</a> might deserve a post all of its own... see this article on <a href="">Windows Offline Files</a> for an overview. </li> <li>Windows Offline Files provides cached access to network file shares when you're offline from them. Note that OneNote also has its own cache that enables it to work offline, and do things like multi-user edit, sync and merge automatically. </li> <li>Windows Offline Files is great for things like work laptops that connect to your network share at work, and you want access to the same files while traveling or out of office. It's used when you have your Documents folder redirected to a network share for example. </li> <li>However, it means that when you are offline, OneNote is working against a local cached copy of the file (cached by Windows separate to the OneNote cache). This interferes with OneNote's ability to merge changes from multiple machines. Basically machine A and B both sync to a Windows Offline Files local cache copy. To OneNote it looks like it wrote to the server (because the Windows Offline Files cache is meant to be transparent in this respect). Then later when you're online Windows Offline Files replicates these two (now different) files up to the server. Windows Offline Files doesn't know anything about how to merge OneNote files, so it just gives you the option to keep both copies or replace one with the other. Depending on what you choose you'll either end up with duplicate section files in the notebook (that are slightly different) or losing one set of changes. And on Vista if you don't resolve the Windows Offline Files conflict (it shows up in the Sync Center in the taskbar) then you'll be continuing to work against the local copy in the Windows Offline Files cache and won't even see the changes from the other machine at all. </li> <li>How to avoid this: <ul> <li>If it's only you accessing the files (e.g. laptop and desktop both pointing to the same server Documents folder), then before switching machines and making edits: <ul> <li>Make sure OneNote is in sync (F9 on the keyboard will force sync) on the machine you're leaving </li> <li>Make sure Windows Offline Files is in sync (can force sync from the sync center in notification area on Vista) </li> <li>Then when you get on the other machine make sure Windows Offline Files is in sync there before starting to edit in OneNote </li> </ul> </li> <li>If multiple people are sharing the files <ul> <li>Don't use Windows Offline Files on this share. Or move the notebook to another file share. </li> <li>On Vista, you can check which shares Windows Offline Files is syncing from the Sync Center partnerships. </li> </ul> </li> </ul> </li> <li>I personally choose to keep my OneNote notebooks on shares that don't have a Windows Offline Files partnership syncing it (I use Windows Offline files for other shares). OneNote does a fine job caching, syncing and merging all by itself. And multiple layers of syncing and caching tend to get in the way of merge technologies like OneNote's. </li> <li>There a bunch of useful information online about managing <a href="">Windows Offline Files</a> like: <ul> <li><a href="">How to make folders available offline</a> (and conversely if you reverse this you can stop Windows Offline Files from syncing a folder) </li> <li>Windows Offline Files <a href="">sync conflicts</a>, how they occur, and how you resolve them </li> <li>Windows Offline Files <a href="">sync errors</a> (problems with sync rather than conflicting file changes) <br /></li> </ul> </li> </ul> </li> <li> <h3>Windows Offline Files on Vista causes corrupt OneNote files</h3> <ul> <li>There was a bug in Windows Vista's new Offline Files implementation that could cause corruptions in OneNote files (and some other like Money) </li> <li>It has been fixed in Windows Update. It's a "recommended" update because it's not a security fix. So you have to choose to install it. Having said that, you really should install it when you see the list of issues it addresses. </li> <li>Details of the fix are here <a href=""></a> </li> <li>So if you're using Vista, OneNote and Windows Offline files make sure you have installed all the latest Windows Updates. </li> </ul> </li> </ol> <p>OneNote notebooks on SharePoint coming up in the next post...</p><img src="" width="1" height="1">DavidRasmussen OneNote to Sharepoint - Access Denied and Automatically Detect Settings<P>If you have a OneNote notebook on SharePoint you may have seen something like the following errors at some time:</P> <UL> <LI>An 'infobar' appears at the top of the page in OneNote saying you don't have permission to sync to that section file </LI> <LI>You may have failed to create a new notebook on that SharePoint location </LI> <LI>You may have failed to open the notebook </LI></UL> <P.</P> <H1>Automatically Detect Settings needs to be on</H1> <UL> <LI>You need to ensure that "Automatically Detect Settings" is checked on in the "Internet Options" settings in Internet Explorer, as shown below. </LI> <LI>You can get to this from Internet Explorer -> Tools -> Internet Options -> Connections -> LAN Settings </LI></UL> <BLOCKQUOTE> <P><A href="" mce_href=""><IMG style="BORDER-TOP-WIDTH: 0px; BORDER-LEFT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-RIGHT-WIDTH: 0px" height=372 alt=image</A> </P></BLOCKQUOTE> <UL> <LI>If this option doesn't work for you because it messes with your browsing in Internet Explorer then go back to your original settings and read the rest of the nitty gritty in this post for other ways to possibly fix this. </LI></UL> <BLOCKQUOTE> <P>* <EM.</EM></P></BLOCKQUOTE> <H1>Why do you need Automatically Detect Settings on?</H1> <P>There's a lot of details behind this that may be hard to follow if you don't know much about HTTP etc. I'll try and explain it briefly.</P> <H2>Background</H2> <UL> <LI>"Automatically detect settings" talks to a server on your network to get basic configuration information like proxy server </LI> <LI>In XP HTTP traffic goes over a protocol stack called WinInet </LI> <LI>In Vista there is also a new network stack called WinHTTP for HTTP traffic. This is a much improved HTTP specific stack. It was originally created for Windows Server 2003. WinInet still exists on Vista for backwards compatibility. </LI> <LI>WebDAV (a protocol for accessing files over HTTP) was re-written in Vista to use WinHTTP. This was a significant improvement over the WebDAV stack in XP. </LI> <LI>However, many applications still use WinInet because they haven't been re-written to use WinHTTP on Vista. Internet Explorer for example still uses WinInet. And many parts of Microsoft Office still use WinInet. Parts of OneNote included. </LI> <LI. </LI> <LI.</LI> <LI>Note: that your credentials are always encrypted anyway, so I'm not talking about plain text transmission here. WebDAV still thinks it's a good idea not to send them unless needed on public internet. It's good surface minimization. </LI> <LI>In theory, if WebDAV gets a permission denied response the user will be explicitly prompted for the credentials and WebDAV will then proceed to send them and you'll successfully connect. </LI> <LI>The reason for the difference in behavior is that inside a work environment people generally expect to just be able to connect to all their server resources without having to enter credentials for each server. </LI></UL> <H2>The problem</H2> <P mce_keep="true"> </P> <UL> <LI>OneNote syncs in the background relatively frequently. It's not just saving when the user hits save. OneNote is also syncing potentially several notebooks on different servers. </LI> <LI.</LI> <LI>So as a result, OneNote makes file access calls in a 'UI.</LI> <LI...</LI></UL> <H2>This affects other apps too</H2> <UL> <LI>This problem manifests in different ways for different apps</LI> <LI...).</LI> <LI>So for many apps this manifests as you getting one to three credential prompts while trying to open a file. Sometimes these may fail and you'll end up with a read only copy of the file open.</LI> <LI>See this <A href="" mce_href="">post on the SharePoint team blog</A> for more details on this </LI> <UL> <LI.</LI></UL> <LI.</LI></UL> <H1>What's being done to address this?</H1> <P>We're paying lots of attention to this issue. And here are a couple of things that are being done among others:</P> <UL> <LI>There are hot fixes coming from the Windows team to help deal with this as mentioned on the SharePoint team blog post. The hotfixes are <A href="" mce_href="">KB941853</A> and <A href="" mce_href="">KB941890</A>. These fixes are only available through support right now (e.g. if you're a corporate customer) but should be available in a future service pack after further testing and work.</LI> <LI>OneNote will also be doing work to have a better response to this particular kind of partial failure in the network calls, so the user gets more helpful information in the infobar and OneNote can prompt appropriately where possible.</LI></UL><img src="" width="1" height="1">DavidRasmussen Page Templates in OneNote with background images<p.</p> <p>Here are the steps.</p> <ol> <li>Create a new page</li> <li>Put the picture that you want to be the background on the page (not in an outline but directly on the page).</li> <ol> <li>When you paste the picture on the page it will default to being in an outline</li> <li>Drag it out of the outline (grab the four way handle to the left of the picture and drag it out onto the page surface outside the outline)</li> <li>Move the picture or resize it on the page to get it where you want</li> <li>Configure and arrange whatever other content you want on the page</li> </ol> <li>Right click the picture – choose “Set Picture as Background” (although depending on your purpose you may not need to do this) – note this option will only appear if the picture is on the page and not in an outline. <br /><a href=""><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="244" alt="clip_image002" src="" width="199" border="0" /></a></li> <li>Then you can make this page a template:</li> <ol> <li>Format (menu) -> Templates</li> <li>From the bottom of the task pane on the right choose “Save Current Page as a Template”</li> <li>Give it a name</li> </ol> <li>You can create pages with this template from the drop down arrow next to the new page button, here <br /> <a href=""><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" height="101" alt="clip_image004" src="" width="220" border="0" /></a></li> <li>You can even set it as the default template for the current section so that all new pages in the section appear that way.</li> </ol><img src="" width="1" height="1">DavidRasmussen Manager meets OneNote<P>We've met a number of users who use <A class="" href="" mce_href="">MindManager</A> <A class="" href="" mce_href="">OneNote 2007 + MindManager tool</A> provides three functions:</P> <UL> <LI>OneNote 2007 Send To MindManager</LI> <LI>OneNote Hyperlinks in MindManager</LI> <LI>OneNote Notebook Hierarchy Mapping</LI></UL> <P>In their own words, you can:</P> <UL> <LI>From MindManager, easily map out the OneNote Notebooks, Sections, and Pages, including hyperlinks to the notebooks, sections, and pages: </LI> <LI>From MindManager, send the current map to OneNote as an image that you can sketch on and annotate:</LI> <LI>From OneNote, send a page to MindManager as a hyperlinked topic:</LI></UL> <P>There are some <A class="" href="" mce_href="">screenshots</A> on the site that give you a better idea of what it does. And you can download it for free to try it out if you have MindManager.</P><img src="" width="1" height="1">DavidRasmussen"Virtual Notebooks" that include files from anywhere<P>I got the following question recently, and thought the answer might be valuable to others.</P> <H3>Question:</H3> <P?"</P> <H3>Answer:</H3> .</P><PSTEPS as follows:< P> <OL> <LI>Copy the relevant .one section files to where you want them on each of the customer sites (e.g. the “CompanyX.one” file to the CompanyX site, and the “CompanyY.one” file to the Company Y site).</LI> <LI>In Windows explorer create a folder for your roll up notebook on your local machine (or in redirected mydocs or wherever you keep your notebooks, it can be on a windows file share server if you want)</LI> <LI>Navigate to your first customer site file in SharePoint. In the browser right click on the file (e.g. “CompanyX.one”) and choose “Copy shortcut” so you get the URL to the file saved on the clipboard.</LI> <LI>Go back to the folder you created in step 2.</LI> <LI>Right click in the folder and choose “New”->”Shortcut”</LI> <LI>Paste the link to the file in the location field</LI> <LI>Give the link a name (e.g. “CompanyX”) then close and save your shortcut</LI> <LI>Repeat 3-7 for each of your customer sites/files</LI> <LI>When you’re finished go up to the parent folder of your notebook folder, then right click on the notebook folder you created in step 2, then choose “Open as notebook in OneNote”</LI></OL> <P.</P><img src="" width="1" height="1">DavidRasmussen the OneNote 2007 and 2003 file format are different<P>The OneNote 2007 file format is quite different to the 2003 format. Here are some details on the implications of this and the reason behind the difference.</P> <H3>Impact of this difference on interactions between OneNote 2007 and 2003 clients</H3> <UL> .</LI> <LI.</LI></UL> <H3>Why is the file format different?</H3> <P.</P> <P>In addition to that, we have a lot of new features that weren't supportable in the OneNote 2003 format. Among other things, they include:</P> <UL> <LI>Tables</LI> <LI>Embedded files</LI> <LI>Internal hyperlinks</LI> <LI>Outlook task flags</LI> <LI>New note tag types</LI> <LI>Drawing tools</LI> <LI>Document printouts (because we do them differently now)</LI> <LI>Shared notebooks and merging (as noted above) </LI> <LI>Merge conflict pages</LI></UL> <P mce_keep=.</P> <P mce_keep="true">On a final note, rest assured that we are very committed to file format compatibility as a goal for future OneNote versions.</P><img src="" width="1" height="1">DavidRasmussen 2007 and Groove<P...</P> <P>OneNote experience with <U>Groove Workspaces</U> will be limited / problematic</P> <UL> <LI>Groove Workspaces will work for individual OneNote section files sort of like a Word doc would, with all the associated potential for conflicts. </LI> <LI>Groove Workspaces will not work very well with OneNote notebooks, because OneNote notebooks are folders and require us to open the folder. Groove Workspaces aren’t exposed that way. When you open a document in a Groove Workspace, Groove copies it from their store (hidden and not something we can directly access) out to the temp directory and calls the app to open it from there. Consequently we only see one file (the section file) at a time in the temp directory. </LI></UL> <P>OneNote experience with <U>Groove Shared Folders</U> will be much better but still have conflict issues</P> <UL> <LI>Groove Shared Folders will work better for OneNote notebooks. These function much more like regular windows shared folders. OneNote can see all the files in it at once, you can open the folder as a notebook in OneNote. And basically OneNote notebooks will work there.</LI> <LI>However, you will still have conflicts if two people edit the same section at the same time (and you’ll end up with two copies of the section file), because Groove disintermediates OneNote's ability to do merge. </LI></UL> <P>Basically Groove works okay for single file document model (but still has conflicts) but it can be quite problematic for data that is represented by sets of files. OneNote Notebooks are an example, Front Page webs would be another example (although obviously less frequent).</P> <P.</P> <UL></UL><img src="" width="1" height="1">DavidRasmussen Notebooks on USB drives and SD cards<P.</P> <P.</P> <P. </P> <P.</P> <P>Step by Step Instructions:</P> <OL> <LI>Plug in the removable drive (USB drive, or SD card ). Note the drive letter. <LI>In OneNote 2007, create a new notebook on the drive. <UL> <LI>File - New - Notebook <LI>Give it a name and click next. <LI>Choose "I will use it on this computer" and click next. <LI>Click the browse button and browse to the USB drive and optionally a folder where you want the notebook stored. Click create.</LI></UL> <LI>Add any content you want to the notebook (section, pages etc.) <LI>Remove the USB drive at anytime <UL> <LI. <LI>You might want to give it 10 seconds or so after your last edit, or wait for the drive to stop flashing before removing it. OneNote will sync quickly. <LI.</LI></UL> <LI>Connect the USB drive to the second computer <LI>Open the notebook in OneNote on the second computer <UL> <LI>File - Open - Notebook <LI>Choose the folder with the notebook name that OneNote created on the USB drive above. <LI>You should now have all the notebook contents available on the second machine.</LI></UL> <LI>Again, you can remove the drive at anytime, without closing the notebook in OneNote. You can close the OneNote app at anytime and when you start OneNote again the notebook will be available from the cache.</LI></OL> <P.</P> <P.</P><img src="" width="1" height="1">DavidRasmussen Your Tasks With OneNote<P.</P> <P. <P> ...</P> <P>With the combination of OneNote 2007 and Outlook 2007 I now have a system that works very well for me. Here's how I manage my task list and workflow now.</P> <OL> <LI>I created a ToDo page in OneNote in my general section. This always contains my current to do list and grows and evolves as my tasks change. <LI>I have a direct keyboard shortcut to this page, Ctrl-Alt-T, so that I can instantly go to this page whether OneNote is running or not. This works from anywhere. See my post on <A href="">Keyboard Shortcuts for Favorite OneNote Pages</A> for how to do this. <LI>I write each task on a line. <LI. <LI>That line gets flagged as an "Outlook Task" in Onenote. It gets added to the task list in Outlook, and there is two way sync between them. If it gets marked done in Outlook it shows up as done in OneNote and vice versa. <LI>There's also cross linking. A link is created in the Outlook task that will jump you directly back to this item in OneNote. Or you can right click the flag in OneNote to open the matching task in Outlook. <LI. <LI.</LI></OL> <P>Now my work flow typically looks like this: </P> <OL> <LI>Hit Ctrl-Alt-T, I can look at my task list and get an overall view. <LI>Move things around with Alt-Shift arrows, for example to bring important stuff to the top. <LI>I can mark things done. I can add new things. I can add additional context and links to references or details I'll need to refer to when doing the task. <LI>I also see my tasks show up in the “ToDo bar” on the right of Outlook whenever I’m in Outlook. So they’re always in front of me. <LI>And I see them distributed across date in the Outlook calendar and allocate time accordingly. <LI>I can update the status in either place. <LI>I leave "done" tasks on my OneNote page for a while (they are flagged as done), but as I work on the parent task I can quickly see which of the sub tasks are done and what's left to do. Periodically I delete the done tasks from the ToDo page, for example when the parent task is complete. I always have a permanent record of them in Outlook. Ctrl-A once, followed by delete is a fast way to delete a task line. <LI>Also sometimes I add tasks out of context of my OneNote ToDo page. For example, if I'm taking notes in a meeting. I can use the same process to flag any item in the meeting notes as a task to do. I don't have to switch contexts, and later when I link back to the task I'll see all the information from that meeting that might relate to the task. </LI></OL><img src="" width="1" height="1">DavidRasmussen shortcuts for fast access to favorite OneNote pages<P>If you're like me you probably have a few OneNote pages or sections that you use frequently. For example, a to do list, daily log, team notebook homepage, or project status page.</P> <P>I like to have instant access to those things with a simple keyboard shortcut, whether OneNote is currently open or not. It really improves my workflow. I do that by creating windows shortcuts directly to those pages as follows:</P> <OL> <LI>In OneNote right click on the page tab, or section tab that you want the shortcut to go to. <LI>Choose "Copy Hyperlink to Page" or "Copy Hyperlink to Section" <LI>Go to your windows desktop (Win-D will take you straight there) and right click on the desktop. Choose "New" -> "Shortcut". <LI>In the location box, press Ctrl-V to paste the OneNote hyperlink. <LI>Click next. Then give the shortcut a name. For example "ToDo List". <LI>Click Finish. You now have a shortcut on the desktop. You can move it anywhere you want, like mydocs. <LI>Now right click on the shortcut icon and choose "Properties" <LI.</LI></OL> <P.</P> <P><STRONG>Vista bonus</STRONG></P> <P. </P> <P.</P> <P>Of course, if you don't have Vista but have some other desktop search tool that could work too.</P><img src="" width="1" height="1">DavidRasmussen | http://blogs.msdn.com/david_rasmussen/atom.xml | crawl-002 | refinedweb | 6,987 | 58.92 |
Here at t-bot, we just finished porting a part of one of our existing Rails applications to utilize the new Facebook platform. It took about a week, and despite the decent documentation for the Facebook platform, there was definitely a lot of trial and error. There also seems to not be a lot of resources on using Rails and the Facebook platform, so we thought we’d give back what we learned.
First, some basic info about the Facebook platform.
Basically Facebook acts like a middleman between the Facebook user and your Rails app. So when a Facebook user clicks on a link or submits a form in your Facebook application, Facebook POSTs that information, along with some of its own information, to your Rails application. When you configure your Facebook app settings, you tell Facebook that whenever it gets a request for, say, ‘’ to route that to ‘’. ‘show’ page. We adopted the convention of suffixing all Facebook views with ‘_fbml’ as well as using a separate layout specifically for Facebook. ‘fbml’ stands for FaceBook Markup Language. It’s basically HTML plus a bunch of Facebook specific tags such as:
<fb:actionCreate a new photo album</fb:action>
which renders to a link. We used mostly just HTML in our Facebook views with some FBML for the Facebook specific headers and navigation. We adopted the ‘_fbml’ file name suffix because when executing the following in a view:
<%= render :partial => 'user', :object => @user %>
Rails will always look for a file in the current action’s controller’s views directory named ‘_user.rhtml’. The file it’s looking for will always be prefixed with an underscore and its file type will be ’.rhtml’. It doesn’t matter if you specify the file extension or not in the #render call. Originally, the plan was to name all our Facebook views ‘
You can take this a little farther to clean up your controllers some more and make them look more RESTful.
And add the following in config/environment.rb or a file in lib:And add the following in config/environment.rb or a file in lib:
class UsersController < ApplicationController def show @user = User.find params[:id] respond_to do |wants| wants.html wants.fbml end end end ‘new_fbml.rhtml’ in ‘app/views/users’. By using #respond_to, we can get rid of the conditional logic and #facebook? query method in our controller, which is nice.
In order for the #respond_to to work, you’ll need to make sure all your urls requested from Facebook end in ’.fbml’ or add a default :format parameter to your named routes. So you’ll have to update your routes file:routes.rb
We started out this way in order to keep a nice separation between our Facebook and non-Facebook parts of the app. However, there was just too much duplication in the controllers so we decided to use method #1 and put Facebook specific conditional logic in our existing non-namespaced controllers.
Always make sure to use
:only_path => true in all your named route calls like so:
<% form_for :user, @user, :url => facebook_create_user_url(:only_path => true) do |form| -%> <% end %>bAnd in config/environments/development.rb
map.facebook_user "#{FACEBOOK_PATH_PREFIX}/user/:id", :action => 'show'
And in config/environments/production.rbAnd in config/environments/production.rb
FACEBOOK_PATH_PREFIX = 'your-facebookapp-name-development'
FACEBOOK_PATH_PREFIX = 'your-facebookapp-name'
At first I’d thought to try write my own library to make all the Facebook API calls, but then reconsidered because of time constraints, to use the rFacebook API. It doesn’t feel very Rubyish because it looks like basically a straight port of the PHP Facebook client. It gives you a Facebook session object that you can use to make Facebook API calls pretty easily, like: ‘vendor/plugins’.
One exception we kept seeing in our logs was:
RFacebook::FacebookSession::NotActivatedException (You must activate the session before using it.):
The way to ‘activate’ your session is to log into Facebook, go to your application page, go to its ‘About’ page, click the ‘Add Application’ button and then add the application to your list of applications. This got rid of the exception every time.
Since the Rails
flash is associated with each Rails session, you can’t use it because Facebook does not pass the Rails cookie back on each request it proxies to your Rails app. Instead, each request from Facebook is seen as a brand new session to your Rails app. This also prevents you from using the
session.
One solution here would be to write your own FacebookSession and somehow configure Rails to use that instead of its default whenever you reference
session in a controller. Facebook specific session information is passed along from Facebook to your Rails app in every POST, which could be used as a session key.
update: Moved :layout parameter from the ‘fbml’ content type respond_to block to the ‘fbml’ custom MIME type’s default block | http://robots.thoughtbot.com/tagged/facebook-rails-fist | crawl-003 | refinedweb | 816 | 61.97 |
Parent Directory
|
Revision Log
Removed duplicate version of the package.
package FIGRules; require Exporter; @ISA = ('Exporter'); @EXPORT = qw(NormalizeAlias FigCompare); use strict; =head1 FIG Rules Module =head2 Introduction This module contains methods that are shared by both B<FIG.pm> and B<Sprout.pm>. =cut # =head2 Public Methods =head3 NormalizeAlias C<< my ($newAlias, $flag) = NormalizeAlias($alias); >> Convert a feature alias to a normalized form. The incoming alias is examined to determine whether it is a FIG feature name, a UNIPROT feature name, or a GenBank feature name. A prefix is then applied to convert the alias to the form in which it occurs in the Sprout database. The supported feature name styles are as follows. C<fig|>I<dd..d>C<.>I<dd..d>C<.peg.>I<dd..d> where "I<dd..d>" is a sequence of one or more digits, is a FIG feature name. I<dd..dd> where "I<dd..d>" is a sequence of one or more digits, is a GenBank feature name. I<XXXXXX> where "I<XXXXXX>" is a sequence of exactly 6 letters and/or digits, is a UNIPROT feature name. =over 4 =item alias Alias to be converted to its normal form. =item RETURN Returns a two-element list. The first element (newAlias) is the normalized alias; the second (flag) is 1 if the aliias is a FIG feature name, 0 if it is not. Thus, if the flag value is 1, the alias will be expected in the B<Feature(id)> field of the Sprout data, and if it is 0, the alias will be expected in the B<Feature(alias)> field. =back =cut sub NormalizeAlias { # Get the parameters. my ($alias) = @_; # Declare the return variables. my ($retVal,$flag); # Determine the type of alias. if ($alias =~ /^fig\|\d+\.\d+\.peg\.\d+$/) { # Here we have a FIG feature ID. $retVal = $alias; $flag = 1; } elsif ($alias =~ /^\d+$/) { # Here we have a GenBank alias. $retVal = "gi|" . $alias; $flag = 0; } elsif ($alias =~ /^[A-Z0-9]{6}$/) { # Here we have a UNIPROT alias. $retVal = "uni|" . $alias; $flag = 0; } else { # Here we have an unknown alias type. We assumed that it does not require # normalization. (If it does, then additional ELSIF-cases need to be added # above.) $retVal = $alias; $flag = 0; } # Return the normalized alias and the flag. return ($retVal, $flag); } =head3 FIGCompare C<< my $cmp = FIGCompare($aPeg, $bPeg); >> Compare two FIG IDs. This method is designed for use in sorting a list of FIG-style feature IDs. For example, to sort the list C<@pegs>, you would use. C<< my @sortedPegs = sort { &FIGCompare($a,$b) } @pegs; >> =over 4 =item aPeg First feature ID to compare. =item bPeg Second feature ID to compare. =item RETURN Returns a negative number if C<aPeg> should sort before C<bPeg>, a positive number if C<aPeg> should sort after C<bPeg>, and zero if both should sort to the same place. =back =cut sub FIGCompare { # Get the parameters. my($aPeg, $bPeg) = @_; # Declare the work variables. my($g1,$g2,$t1,$t2,$n1,$n2); # Declare the return variable. my $retVal; # The IF-condition parses out the pieces of the IDs. If both IDs are FIG IDs, then # the condition will match and we'll do a comparison of the pieces. If either one is # not a FIG ID, we'll do a strict string comparison. The FIG ID pieces are, # respectively, the Genome ID, the feature type, and the feature index number. These # are all dot-delimited, except that the genome ID already has a dot in it. if (($aPeg =~ /^fig\|(\d+\.\d+).([^\.]+)\.(\d+)$/) && (($g1,$t1,$n1) = ($1,$2,$3)) && ($bPeg =~ /^fig\|(\d+\.\d+).([^\.]+)\.(\d+)$/) && (($g2,$t2,$n2) = ($1,$2,$3))) { $retVal = (($g1 <=> $g2) or ($t1 cmp $t2) or ($n1 <=> $n2)); } else { $retVal = ($a cmp $b); } # Return the comparison indicator. return $retVal; } 1; | http://biocvs.mcs.anl.gov/viewcvs.cgi/Sprout/FIGRules.pm?hideattic=0&revision=1.3&view=markup&sortby=rev | CC-MAIN-2020-16 | refinedweb | 630 | 75.91 |
This post will be mostly code. Please use proper indenting cuz Python otherwise will make your life hell. If you’re using Sublime go to, set Convert Indentation to tabs.
Gist : I have used the collections.defaultdict dict DT for implementing a dict of sets.
Vertices have been stored as adjacency list kind of elements as a dictionary. The code is raw and may have errors ( though no compilation error as of the post’s writing). Please comment for additional details. This is purely for testing purposes.
A Graph.
from collections import defaultdict
#The Graph will be a dictionary of sets
class Graph():
def __init__(self, connections, directed = False):
self.graph = defaultdict(set)
self.directed = directed
self.add_connections (connections)
def add_connections(self, connections):
for node1,node2 in connections:
self.add_connection(node1,node2)
def add_connection(self, node1, node2):
self.graph[node1].add(node2)
if not self.directed:
self.graph[node2].add(node1)
def remove(self, node):
#removes all references to the node
#Use iteritems for dict items like k,v in dictname.iteritems():
for n,cons in self.graph.iteritems():
try:
#Removing from a set involves setname.remove(element)
cons.remove(node)
except KeyError:
pass
try:
#Removing from a dictionary involves rem dict_element_name
del self.graph[node]
except KeyError:
pass
def isconnected(self, node1, node2):
if node1 in self.graph[node2] or node2 in self.graph[node1]:
return True
return False
def dfs(self,start):
#If start node does not exist, return None (search is futile)
if start not in self.graph:
return None
#Start with an empty set
visited = set()
#To return unse ( which is not a set
unset = []
#Initially fill stack with start vertex
stack = [start]
#While stack is not empty keep repeating this algorithms
while stack:
#Take the first element of stack (pop means last inserted , aggressive)
vertex = stack.pop()
#If vertex has not been visited yet, add it to visited and look for all the element in graph[vertex]
if vertex not in visited:
visited.update(vertex)
unset.append(vertex)
stack.extend(self.graph[vertex] - visited)
return unset
def bfs(self, start):
if start not in self.graph:
return None
visited = set()
queue = [start]
unset = []
while queue:
vertex = queue.pop(0)
if vertex not in visited:
visited.update(vertex)
unset.append(vertex)
queue.extend(self.graph[vertex] - visited)
return unset
#Should work but not tested
def findpath(self,v1, v2):
m = bfs(v1)
if v2 in m:
return m[:m.index(v2)+1]
return None | https://codeandsmile.wordpress.com/tag/programming-2/ | CC-MAIN-2018-43 | refinedweb | 408 | 51.24 |
Good Morning All,
I am not a programming expert by any stretch of the imagination, but if there is one thing I know it’s that getting the code to work is the first step and optimizing is the second step.
With that being said I have decided to share all the code I am using for my current project and hope it can help someone or someone can help me make it better. Regardless, the game I am working on is a Platformer/RPG so there will be a lot of systems happening.
The first code piece I would like to share is the MoveTowardPlayer script that determines if the player is on the Left or Right of whatever GameObject this script is attached to and will move the host toward the player. If the player crosses its path, the enemy will flip its X-Axis to face the player.
Below is the script I use to accomplish this effect.
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MoveTowardPlayer : MonoBehaviour { public Transform target; public float speed; private void Start() { //This finds the GameObject that has the PlayerController script attached. //This is assuming there is only one PlayerController. target = FindObjectOfType<PlayerController>().transform; } void Update() { float step = speed * Time.deltaTime; transform.position = Vector3.MoveTowards(transform.position, target.position, step); #region \/-----Face Right-----\/ if(transform.position.x < target.position.x) { GetComponent<SpriteRenderer>().flipX = true; } #endregion #region \/-----Face Left-----\/ else if(transform.position.x > target.position.x) { GetComponent<SpriteRenderer>().flipX = false; } #endregion } }
***As of 04/13/18, this is the current script I am using. If I update it I will update this post.*** | http://shadowpeakstudios.com/tag/snippet/ | CC-MAIN-2020-24 | refinedweb | 274 | 53.81 |
Introduction
Microsoft introduced Declarative Programming Style with release of MTS and COM+. MTS and COM+ provided many configurable services. E.g. "Transactional" attributes, Synchronization attributes, etc. The best thing about all these services is that it requires minimum efforts on developer side. All the services are configurable using the attributes. But we could never really add to set of attributes that MTS or COM+ provided. To some extent it helped us to visualize the capabilities of the future application frameworks. In this article we are going to look at some features of .Net framework, which enable us to build highly configurable applications. We can build application frameworks, which help the developer to concentrate on developing the core business related functionality. Developers can invoke the services just by configuring/declaring few attributes. Developer can be ignorant of underlying framework plumbing.But before we go to these features we need to understand concept called as Aspect Oriented Programming. What is AOP?
Reusability is not new to us and we all make conscious efforts to achieve high degree of reusability. Lets look at the way we use the reusable components. Lets take a scenario where we want to create a trace of an application execution. We want to log the name of each and every method that is executed and some other statistics such as how much time it took to execute the method.So we write a simple logger class. We may provide features to log the details in a file or database table. We provide some methods to log details such as "BeginLog", "EndLog". Our program calls these methods. Each method that we want to execute, calls a method such as "BeginLog". To take a step further, we may use the magic of reflection to know which method has called the component method. At the end of the method we call the "EndLog" method to end the trace for the same method.So even after having reusable component, developer needs to do lot of coding. But how about marking the method with just an attribute/aspect such as "LogEnable" and rest of the things are taken care by the underlying components? Well if you like this concept, then Welcome to Aspect Oriented Programming.Aspect-oriented Programming (AOP) was invented at Xerox PARC in the 1990s.In Aspect oriented programming, we provide the Attribute/Aspects to the class at various levels such as class/method/ property, etc. We can treat this aspect as metadata about the class. The run time can discover the metadata and provide the services required by the component.How AOP works?
Looking at COM+ objects, we can think of attributes, such as Transaction, Security, Synchronization attributes, as aspects. The COM+ runtime provides stacks of objects, called as interceptors. These interceptors get in between the client and server and provide services such as Security, Transaction, Synchronization, etc. The AOP framework works in the similar way. To design AOP framework we need the ability to Create Runtime that binds object and client together.Describe the Metadata of the object. This metadata will provide the Aspect for the object. AOP framework works solely depends on the interception and delegation. AOP framework performs interception and delegation at two levels-Object activation and Method Invocation.At the time of object activation, run time uses the metadata (Aspects/Attributes) of the object to compose the stack of interceptors. The metadata helps to identify the services requested by the object. The interceptors are responsible to provide requested service. The runtime returns the reference to the interceptor instead of reference of the object, to the client. When client calls methods on the object, the interceptors intercept the call to do some pre processing. All the interceptors are chained to each other. The last interceptor in the chain directs the call to object. When the call is finished, all the interceptors get chance to post-process the method call.The set of aspects together form the context for the class. The context helps to decide the right environment for the method execution. We will see in more details about contexts later.AOP allows for better separation of tasks, which are commonly used. The AOP approach has a number of benefits. First, it improves performance because the operations are more succinct. Second, it allows programmers to spend less time rewriting the same code. Overall, AOP enables better encapsulation of distinct procedures and promotes future interoperation.AOP and .Net
One of the reasons why we can build the AOP oriented components in .Net is that it allows us to extend the .Net framework. .Net framework allows us provide the metadata for each component. To provide the custom attribute we need to develop custom attributes.As you can see, the attribute class itself has some attributes. The AttributeTarget attribute will control the application of the attribute to class/method/property and so on.
Now we can specify the metadata for the component using these attributes.
public class ContextClass: ContextBoundObject{ }
Contexts in .Net
Now we have to look at the concept called as Contexts in .Net.Context is a logical grouping of the objects that have same aspect values. With help of contexts we establish interceptors to intercept the calls on the objects. Two objects with different contexts communicate to each other using .Net context architecture. Though we do not want to go into the details of context architecture we need to understand its basics.Basics of Context architecture
Two objects with different contexts communicate to each other using the messages. These messages are passed thro' several message sinks.These message sinks can be custom built. These sinks are chained to each other and these sinks pass the message to next sink till they reach the end of the chain. We can build the custom sinks and introduce them in the chain. This gives us the opportunity to intercept the message.There are two processes that take place:Firstly when we create a context bound object, the run time sets up the chain of message sinks. This chain is used when two objects from different contexts communicate to each other. Secondly, when two objects in different contexts communicate to each other, the runtime forms proxy object between the caller and callee. The proxy is of two types - Transparent proxy and Real Proxy. The runtime forwards the message to the transparent proxy. This proxy serializes the stack in to message and passes it to the real proxy. The real proxy takes the message and sends it to first message sink in the channel. The first message sink intercepts the call. Message sink can preprocess the message. This message sink then passes the message to the next message sink. This process continues till the last sink i.e. Stack builder sink is reached. This sink de-serializes the message into the stack and calls on the method of the object. After the method call, the same sink again serializes the parameter values and return value into the stack and returns it to the previous sink. Each sink in the chain gets its turn to post process the message. The sequence of flow is illustrated in Figure 1.The messages are of 3 types - Construction messages, Method call message, and Response message.From the above discussion its very clear that to intercept the calls on the object we need to build our custom sinks and link in the chain of sink at proper position.Prerequisites
With all this we need to know what all classes we need to create to build our custom interceptors.We need to use following namespaces -
using
First of all to make our class aware of "context" our class should inherit from "ContextBoundObject" .Net runtime will automatically create a separate context for it to live in whenever we create object of that class. .Net runtime establishes the proxies to participate in the calls across the contexts. Secondly we need to build the ASPECTS. We need the attributes that we can apply to the class. So we have to create a class that implements IContextAttribute interface. It should also inherit from Attribute framework class. This class will define the attributes or the aspects that we want to apply to the class. Next we want to define Context Properties. Based on the context properties, runtime will differentiate between two contexts. To create context properties, we need to implement "IContextProperty" interface and "IContributeObjectSink" interface.We are only half done with all these classes. We will have classes required to define the contexts.After this we need to define our own Message Sink. To do that we need to create a class that implements the "IMessageSink" interface. Lets take look at all these steps in detail.Implementation Detail
First we need to derive our class from ContextBoundObjects.
[ContextAtrb(@"c:\ContextClass.txt")]public class ContextClass: ContextBoundObject{}
In the above example, the "ContextAtrb" attribute is the aspect provided for the class. This is called custom attribute. We have seen how to develop this custom attribute.
IContextAttribute interface
For this CustomAttribute to participate in this process of interception it should implement IContextAttribute interface. This interface has two methods
The method IsContextOk provides us with opportunity to decide if the object being created should have the same context or not. The parameter ctx is the context of the caller. If we return the "true" value the object being created will posses the same context as that of the caller. The other parameter "msg" will be the message. This message can be Constructor message only as this method is called only at the time of the construction of the class.GetPropertiesForNewContext
This method is called only when the IsContextOk method returns false. This method gives us opportunity to create the property for the context. These properties can be implemented in a separate class. This class should be derived from two interfaces - IContextProperty, IContributeObjectSink. The context property allows us to link our own message sink in the chain of existing message sink. As we discussed earlier, the interception mechanism works in two steps. The first step is to setup the required message sinks. The second step involves the actual interception.This property class that implement IContributeObjectSink interface helps us to setup the required message sinks.IContextProperty interface
IContextProperty has three methods.
string Name {get;}public bool IsNewContextOK(Context ctx)void Freeze (Context ctx)
Name This is a read only property and returns the name of the property. The context class provided by .Net will add this property in its collection using this name. We can access this property using the method GetProperty of the context class.IsNewContextOK If this method returns true, then only the activation of the object will continue. If it returns false, the exception will be raised. This method is called after the context properties are created. Hence it gives the opportunity to check if the properties created are right for new context.IContributeObjectSink interface
IcontributeObjectSink interface is most important interface. This interface will allow us to hook our own message sinks in the chain of the message sinks. We need to implement one method i.e.IMessageSink GetObjectSink(MarshalByRefObject o, IMessageSink m_Next)GetObjectSinkThis method creates the message sink and returns it.IMessageSink interface
Now the only part left is to create the message sink. To do so we need to write a class deriving from interface IMessageSinkThis interface has methods IMessageSink NextSinkIMessage SyncProcessMessage(IMessage imCall)IMessageCtrl AsyncProcessMessage(IMessage im, IMessageSink ims)In addition to all these methods we also have to implement the constructor.Constructor
The constructor of the class should have a parameter of type IMessageSink. This parameter is the next message sink in the chain. The framework passes the next message sink in the chain to the class. This message sink should be returned in the method NextSink. The class has the freedom to change the message sink and return some other message sink as well. This next message sink will be linked as the next message sink in the chain.SyncProcess
This method is called for each method call on the object. im parameter represents the messages of type Method call.The sink gets created when the GetObjectSink method for context property is called. And the methods of this interface are called when the methods on the object are executed.Implementation for all these interfaces is available in Listing 1.Applications of AOP
This style of programming has found many applications. To start with the example of logging that we have seen in the beginning can be over simplified with this approach. We have to develop classes such as LogginAttribute, LoggingFileProperty and LogginSink. The LoggingSink class will intercept the call and do the logging. We can mark each class and its methods with the LogginAttribute. At the time of interception, the SyncProcessMessage method will find out the current method being called. It will check if the method has attribute "LoggingAttribute" and accordingly log the method details such as parameters and its values etc. Thus developers will just have to mark the methods with attribute and rest will be taken care by the framework.The same applies for role-based security, declarative transactions and so on. The list is never ending.
Appendix
Listing 1
Working with Win32 API in .NET
Virchk.cs: A C# file Scan Utility for Generating MD5 Signature Footprints | http://www.c-sharpcorner.com/UploadFile/raviraj.bhalerao/aop12062005022058AM/aop.aspx | CC-MAIN-2013-48 | refinedweb | 2,218 | 58.58 |
Tried … now client.connect() brings RED S.O.S
Tried … now client.connect() brings RED S.O.S
You mean adding
SYSTEM_THREAD(ENABLED) did cause that?
Could you post your current code again?
Not directly … SYSTEM_THREAD(ENABLE) itself is no problem.
But if I decomment the client.connect() it (SystemThread) change the failure from green breathing to red s.o.s
This time I post the complete code with all comments, tryings, and so on:
#include "thermistor-library/thermistor-library.h" #include "MQTT/MQTT.h" #include <string> SYSTEM_MODE(SEMI_AUTOMATIC); SYSTEM_THREAD(ENABLED) // Analog pin the thermistor is connected to int thermPin = A0; // Voltage divider resistor value int thermRes = 10000; float TempPool; // Configure the Thermistor class Thermistor Thermistor(thermPin, thermRes); // globals void callback(char* topic, byte* payload, unsigned int length); /** * if want to use IP address, * byte server[] = { XXX,XXX,XXX,XXX }; * MQTT client(server, 1883, callback); * want to use domain name, * MQTT client("", 1883, callback); **/ byte server[] = { 192,168,184,170 }; MQTT client(server, 1883, callback); // recieve message void callback(char* topic, byte* payload, unsigned int length) { /** char p[length + 1]; memcpy(p, payload, length); p[length] = NULL; String message(p); [...] **/ } /** void connect_MQTT(){ if (WiFi.ready()){ if (!client.isConnected()) { client.connect("bunker"); Spark.publish("MQTT","TryToConnectMQTT"); } else { Spark.publish("MQTT","Connected"); } } } */ void TempPoolV(){ TempPool=Thermistor.getTempC(true); Spark.publish("TempPool", String(TempPool)); client.publish("TempPool1", String(TempPool)); } Timer TempPoolT(5000, TempPoolV); Timer connectTimer(20000, connect); void setup() { WiFi.on(); //RGB.control(true); // Initialize the Thermistor class connectTimer.start(); Thermistor.begin(); TempPoolT.start(); } //Thermistor.getTempC() void loop() { if (client.isConnected()) client.loop(); //RGB.color(0,0,duty); //StatusBWM = digitalRead(PinBWM); } void connect() { // first start connecting (and don't retrigger while trying!) if (!Particle.connected()) Particle.connect(); // some later visit to this callback (after connection got established) if (WiFi.ready() && !client.isConnected()) { client.connect("bunker"); //<==== THIS CAUSE THE ERROR!!! } } /** void connect() { if (Particle.connected() == false) { Particle.connect(); //waitUntil(Particle.connected); } // connect to the server if (client.isConnected() == false ) { //client.connect("bunker"); // publish/subscribe/ if (client.isConnected()) { // client.subscribe("pool_temp"); Spark.publish("MQTT","isConnected"); } } } */
I’ll repeat myself here
The
client.connect() is obviously blocking too long and hence causes the SOS.
Try removing this part from your callback completely and put this in
loop() instead (and add
pinMode(D7, OUTPUT); in
setup() for debugging)
void loop() { if (WiFi.ready()) { digitalWrite(D7, HIGH); if (client.isConnected()) client.loop(); else client.connect("bunker"); digitalWrite(D7, LOW); } //RGB.color(0,0,duty); //StatusBWM = digitalRead(PinBWM); delay(1000); }
The time the blue onboard LED stays on shows how uncooperative that MQTT library is in case of a missing MQTT server (which I haven’t got at your address).
It actually never seems to return from
client.connect() if it can’t find the server.
I guess this is something you don’t want to happen either.
IT WORKS
The first version, before you edited
Sorry, I am not understand not using blocking code. g I will research.
Thanks very much … I know you have invested many time for me.
Actual Version:
void loop() { if (WiFi.ready()) { if (client.isConnected()) client.loop(); else client.connect("bunker"); } } void connect() { if (!Particle.connected()) Particle.connect(); }
The problem you still might run into (hence my edit above) is that in case your WiFi is present but your MQTT server isn’t your code will still be blocked and your intended fallback solution will fail due to MQTT library not behaving very cooperative.
There should be some sensible and/or user controlable timeout for any connection attempt.
Just try switching off your MQTT or setting a different IP for it and see how the blue LED never goes out.
You couldn’t do a lot about that, since this would need to be built into the library.
Yes, I understand.
I will try to contact the library author.
My MQTT Server is very stable and the few times in year I restart it, I will restart the particle too. The Wifi in the garden is not so stable g I have also a monitoring for my home-automatic, so I will see it soon.
It is not working over night
Cyan Breathing and no cloud connection, but MQTT works.
Than Cyan Breathing and nothing works anymore. Not even Reading and Writing Pins.
Than Cyan blinking like trying to connect and nothing works.
As written yesterday I will contact the library author … Without MQTT everything works fine and with MQTT chaos.
I will also check if there is another way to talk with my OpenHAB Server.
Yup, that is what I experienced. Once the MQTT
client.connect() stalls nothing else works - not even OTA flashing.
No good citizen behaviour of the library IMHO
If you want to use particle functions, here is an example project that works with semi automatic mode.
You can use mobicle.io for an interface. It works great.
I am currently expanding the system and have some slightly newer code.
The DHT sensor is not currently working but is on the list. Do not use the adafruit dht library, I know there are problems with it. I am using the original hot tub thermistors for water temp feedback and control.
Thanks, But I try to use “CURL” to transfer values between Particle Photon and OpenHAB.
Would the work around for that be to wrap all of the MQTT functions in:
waitFor(MQTT_call, 10000);
Do you think that would offer suitable forced timeouts?
I’m not sure what prerequisits a function needs to satisfy for it to work with
waitFor() (would need to look into the implementation). But one thing for sure: If the active
MQTT_call is blocking and won’t bail out by itselft, your
waitFor() will never get the chance to do its waiting. Typically with
waitFor() you call the respective active function (e.g.
Particle.connect()) first and then
waitFor(Particle.connected, timeout) but if
Particle.connect() already blocks, the subsequent “outcome-check” won’t ever be reached.
Also note that
waitFor() does not allow to pass any parameters to the function to check, that limits the potential to use it to
bool MQTT_call(void) functions.
I’d rather go the elaborate route and implement the timeouts the old fashined way - especially when you want to do something related to the library’s tasks while waiting around.
Ahh, that makes sense!
In other words, ask the library developer to adjust the client.connect() code?
That’s probably the only viable route.
You could of course fork the library and do the adjustments yourself - and maybe even contribute the enhanced version to the public library repo - but having the original adapted would be best.
I’ve not checked the library, but I’d no limit the focus to
client.connect() but check for potential blockages everywhere.
Hi, I’m having problems with the library. my application does not connect with my broker. Can you tell me if client.connect (“myParticle”); It’s working correctly ? I’m using the mqtttest.ino example. Thank you.
Hello! I know that it’s an old thread, but did you find any solution about the .connect blocking function?
I have not dug into the issue back then but I just had a look at the library repository and found this pull request which may help
This with this other suggestion from an earlier post in this thread
hi,
If you running
SYSTEM_THREAD(ENABLED) you have to set 4-th parameter in your client initialization
MQTT client("sample.com", 1883, callback, true);
here from official example:
In this case even if your broker is not available the code will not block
Thanks. Never saw that. Was using code that was working in a Proton. Problem ending up being a firewall issue.
5310 | https://community.particle.io/t/mqtt-library-and-semi-automatic/22875/25 | CC-MAIN-2022-27 | refinedweb | 1,288 | 59.6 |
%}
You can mix variables and strings:
{%>
would output:
%}
debug¶
Outputs a whole load of debugging information, including the current context and imported modules.
extends¶.
A string argument" %}
The ability to use relative paths was added.
filter¶.
firstof¶
Outputs the first argument variable that is not
False..
The “as” syntax was added.
for¶¶¶
{{ athlete_list|length }} variable.
As you can see, the
if tag may take one or several
{% elif %}
clauses, as well as an
{% else %} clause that will be displayed if all
previous conditions fail. These clauses are optional.
Boolean operators¶ %}
is operator¶ operator¶ %}
Filters¶
You can also use filters in the
if expression. For example:
{% if messages|length >= 100 %} You have lots of messages today! {% endif %}
Complex expressions¶ %}
ifequal and
ifnotequal¶
{%¶¶" %}
A string argument may be a relative path starting with
./ or
../ as
described in the
extends tag.
The ability to use a relative path was added.is set to
"John"and variable
greetingis set to
"Hello".
Template:
{% include "name_snippet.html" %}
The
name_snippet.htmltemplate:
{{ %}
If the included template causes an exception while it’s rendered (including
if it’s missing or has syntax errors), the behavior varies depending on the
template engine's
debug option (if not
set, this option defaults to the value of
DEBUG). When debug mode is
turned on, an exception like
TemplateDoesNotExist or
TemplateSyntaxError will be raised. When debug mode
is turned off,
{% include %} logs a warning to the
django.template
logger with the exception that happens while rendering the included template
and returns an empty string.
Template logging now includes the warning logging mentioned above.¶¶¶:
- India
- Mumbai: 19,000,000
- Calcutta: 15,000,000
- USA
- New York: 20,000,000
- Chicago: 7,000,000
- Japan
- Tokyo: 33,000,000. Each group object has two attributes:
grouper– the item that was grouped by (e.g., the string “India” or “Japan”).
list– a list of all items in this group (e.g., a list of all cities with country=’India’).:
- India
- Mumbai: 19,000,000
- USA
- New York: 20,000,000
- India
- Calcutta: 15,000,000
- USA
- Chicago: 7,000,000
- Japan
- Tokyo: 33,000,000 %}
Grouping on other properties¶ %}
{{ country.grouper }} will now display the value fields from the
choices set rather than the keys.
spaceless¶
Removes whitespace between HTML tags. This includes tab characters and newlines.
Example usage:
{%¶ %}
url¶:
('^client/([0-9]+)/$', app_views.client, name=.
verbatim¶¶
For creating bar charts and such, this tag calculates the ratio of a given value to a maximum value, and then applies that ratio to a constant.
For example:
¶ %}
Built-in filter reference¶
add¶.'.
In older versions, the
DATE_FORMAT setting (without
localization) is always used when a format string isn’t given. the string
"nothing".
dictsort¶" }}
The ability to order a list of lists was added.
&
The escaping is only applied when the string is output, so it does not matter
where in a chained sequence of filters you put
escape: it will always be
applied as though it were the last filter. If you want escaping to be applied
immediately, use the
force_escape filter. %}
Deprecated since version 1.10: The “lazy” behavior of the
escape filter is deprecated. It will change
to immediately apply
conditional_escape() in
Django 2.0.
escapejs¶
Escapes characters for use in JavaScript strings. This does not make the string safe for use in HTML, but does protect you from syntax errors when using templates to generate JavaScript/JSON.
For example:
{{¶¶
Returns the first item in a list.
For example:
{{ value|first }}
If
value is the list
['a', 'b', 'c'], the output will be
'a'.
floatformat¶¶¶.
iriencode¶".
join¶
Joins a list with a string, like Python’s
str.join(list)
For example:
{{ value|join:" // " }}
If
value is the list
['a', 'b', 'c'], the output will be the string
"a // b // c".
Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (
<br />) and a new line
followed by a blank line becomes a paragraph break (
</p>).
For example:
{{ value|linebreaks }}
If
value is
Joel\nis a slug, the output will be
<p>Joel<br />is a
slug<
¶")." }}
In older versions, the
TIME_FORMAT setting (without
localization) is always used when a format string isn’t given.
timesince¶¶
Similar to
timesince, except that it measures the time from now until the
given date or datetime. For example, if today is 1 June 2006 and
conference_date is a date instance holding 29 June 2006, then
{{ conference_date|timeuntil }}¶.
For example:
{{ value|truncatewords_html:2 }}
If
value is
"<p>Joel is a slug</p>", the output will be
"<p>Joel is ...</p>".
Newlines in the HTML content will be preserved.
unordered_list¶ }}"></img>
In older versions, you had to use
{% load static from staticfiles %} in
your template to serve files from the storage defined in
STATICFILES_STORAGE. This is no longer required.
get_static_prefix¶¶. | https://docs.djangoproject.com/en/1.10/ref/templates/builtins/ | CC-MAIN-2017-51 | refinedweb | 797 | 66.33 |
Difference between revisions of "MSM8916 Mainlining"
Latest revision as of 20:58, 20 October 2020
- 3.1 Requirements
- 3.2 Before you start
- 3.3 Preparations
- 3.4 lk2nd
- 3.5 Device Package
- 3.6 Build Kernel
- 3.7 Initial Device Tree
- 3.8 Regulators
- 3.9 USB
- 3.10 eMMC
- 3.11 SD card
- 3.12 Buttons
- 3.13 Finishing up
- 4 Reference
- 5 Glossary
- 6 Documentation...)
- Audio
- Buttons
- Modem (SMS, voice calls with audio, mobile data).
The
qcom,board-id property allows the bootloader to select the correct device tree. MSM8916 devices usually use QCDT (multiple device tree blobs (dtb) are packaged in one Android boot image). You should be able to find the
qcom,board-id in the downstream
.dts file for your device.
qcom,board-id. In that case, the device cannot be detected only based on the selected DTB. For Samsung devices,
msm8916-samsung-r0x.dtscovers multiple devices - the actual device is then detected using
androidboot.bootloaderversion passed by the Samsung bootloader./testing/testing/device-<vendor>-<codename>/deviceinfo:
# Reference: <> # Please use double quotes only. You can source this file in shell scripts. deviceinfo_format_version="0" deviceinfo_name="Device Name" deviceinfo_manufacturer="Vendor" deviceinfo_codename="<vendor>-<codename>" deviceinfo_year="<release year>" deviceinfo_dtb="qcom/msm8916-<vendor>-<codename>" deviceinfo_append_dtb="true" deviceinfo_modules_initfs="" deviceinfo_arch="aarch64" # Device related deviceinfo_chassis="handset" deviceinfo_keyboard="false" deviceinfo_external_storage="true" deviceinfo_screen_width="720" deviceinfo_screen_height="1280" deviceinfo_getty="ttyMSM0;115200" # MSM DRM cannot take over the framebuffer from the bootloader at the moment deviceinfo_no_framebuffer="true" # Bootloader related deviceinfo_flash_method="fastboot" deviceinfo_kernel_cmdline="earlycon console=ttyMSM0,115200 PMOS_NO_OUTPUT_REDIRECT" deviceinfo_generate_bootimg=. Mainlining#Materials_to_look_into for introductions). Components provided by the SoC (MSM8916) are described in the common include
msm8916.dtsi. Components provided by the PMIC (PM8916) are described in
pm8916.dtsi. Finally, the combination of both is described in
msm8916-pm8916.dtsi.
You need to create a new-pm8916.dtsi" / { model = "Device Name"; // FIXME compatible = "<vendor>,<codename>", "qcom,msm8916"; // FIXME aliases { serial0 = &blsp1_uart2; }; chosen { stdout-path = "serial0"; }; }; &blsp1_uart2 { status = "okay"; };
We see two different kind of device tree nodes here. There is the root device tree node (
/), which we use to set up some configuration in the
chosen node. Then there is the
&blsp1_uart2 node. This is a reference to a device tree node that was defined somewhere under the root node by one of the includes. In this case,
msm8916.dtsi sets up lots of pre-defined devices (e.g. for UART, eMMC, SD card, ...). We don't care exactly where or how they are defined. We just want to enable them and (if necessary) add device-specific configuration to them.
We can reference existing device tree nodes using labels. The original device tree node for
blsp1_uart2 in
msm8916.dtsi looks like this:
/ { /* ... */ soc { /* ... */ blsp1_uart2: serial@78b0000 { compatible = "qcom,msm-uartdm-v1.4", "qcom,msm-uartdm"; /* ... */ status = "disabled"; }; /* ... */ }; /* ... */ };
The part before the colon (
blsp1_uart2:) is the label we can use to reference the node. We can use that to add additional properties or to change one of the existing ones.
In particular, we can see that
msm8916.dtsi declares
blsp1_uart2 (one of the UART ports) as disabled by default. We want to enable the UART port so we override
status = "disabled" with
status = "okay".
Finally, the combination of the
aliases and
chosen node selects
blsp1_uart2 as default console output.
blsp1_uart2). Typically, this is the UART port that is used for debug console output. However, there are also some devices that have UART on GPIO 0 and GPIO 1 instead. In that case, you would use
blsp1_uart.
Regulators
As next steps we would like to enable internal/external storage (eMMC/SD card) and make USB gadget mode work. This will allow you to attach your device to a PC and get a debugging console.
However, a requirement of both of these hardware components is that you have some voltage regulators set up properly. Hardware components have different power supply requirements, so usually the PMIC(s) used together with a SoC provide several different regulators that can be configured to produce a voltage level within a specified range.
Let's take a quick look at
msm8916-pm8916.dtsi. As a reminder: This include contains common definitions that apply to most devices that pair MSM8916 (the SoC) with PM8916 (the PMIC). Most interesting for us are the references to
sdhc_1/2 (the SD Host Controller) and
usb_hs_phy (a part of the USB controller):
&sdhc_1 { vmmc-supply = <&pm8916_l8>; vqmmc-supply = <&pm8916_l5>; }; &sdhc_2 { vmmc-supply = <&pm8916_l11>; vqmmc-supply = <&pm8916_l12>; }; &usb_hs_phy { v1p8-supply = <&pm8916_l7>; v3p3-supply = <&pm8916_l13>; };
pm8916_l5,
pm8916_l11 etc are some of the regulators that are provided by PM8916. As you can see they are configured as supplies for both eMMC/SD card and USB.
All these regulators can be configured to a large voltage range, so it is very important that we set up voltage constraints carefully! The voltage constraints specify the allowed voltage range that can be set for a particular regulator. Once we have set them up properly, we can be reasonably sure that accidental mistakes cannot easily destroy one of the hardware components in a device.
Let's get back to the device tree for your device. We extend the initial UART example from the previous section with new device tree nodes to set up the voltage constraints. A typical set of voltage constraints for PM8916 looks like this:
// FIXME: Verify all regulators with downstream &smd_rpm_regulators { vdd_l1_l2_l3-supply = <&pm8916_s3>; vdd_l4_l5_l6-supply = <&pm8916_s4>; vdd_l7-supply = <&pm8916_s4>;>; }; };
You should paste this at the end of your device tree and then go through all the voltages and compare them what you see in your downstream reference kernel. Here are some tips and tricks:
- Downstream regulators look a bit different, but they are usually defined in
msm8916-regulators.dtsi. Note that some device trees may override the regulator voltages in a device-specific
.dts(i).
s1(
smpa1and
l3(
ldoa3) are missing in the voltage constraints because they are managed separately as power domains. Simply put, these two regulators are used by many components in the SoC. Instead of picking an exact voltage, we vote for a particular performance state. On downstream this is called voltage corner. There is a special Resource Power Manager (RPM) co-processor that collects all the votes and then decides for a particular voltage to use.
- There is no need to set up voltage constraints for these because there is no way to set an dangerous voltage through the corner interface.
s2(
spm-regulator) is special (used to control the voltage for the CPU cores) and is not touched by mainline at the moment. Just ignore it.
- Also ignore the
-aoand
-soregulators (usually just on
l7)
regulator-system-loadon
l11in the snippet above is for stability of the SD card[1]. This is declared in a different place on downstream, but most likely you can just keep it as-is.
vdd_l1_l2_l3-supplyetc does not exist on downstream, but you can also keep it as-is. It is extremely unlikely that this is different for a particular device. Most important is validating the voltages.
USB
Theoretically, enabling USB would be as simple as adding:
&usb { status = "okay"; };
However, due to an implementation detail USB only works if the USB controller is notified when you actually insert an USB cable. On mainline, these notifications come from the extcon (external connector) subsystem. Unfortunately, how we can detect that an USB cable was inserted differs quite significantly between devices. Sometimes (mainly on Samsung devices), there is some kind of Micro-USB Interface Controller that sits between USB and the SoC, which can detect various different cable types (connected to PC, connected to charger adapter, USB-OTG, ...). In most other cases, this notification comes from the charger driver, which is usually quite hard to get working (see #Battery/Charging).
How to handle some of the common variants is described here. Feel free to ask in the chat for further help.
ID pin
This is the easiest solution if you have some kind of USB ID GPIO defined downstream. Usually it's called
qcom,usbid-gpio under the
&usb_otg node but the name varies a bit sometimes. The USB ID pin is used to differentiate between:
- Gadget mode (where you connect the device to a PC)
- Host mode (where you use a special USB-OTG adapter to connect other USB devices, e.g. an USB keyboard)
It can only detect these two cases, so it does not allow us to detect that an USB cable is actually inserted. However, as a start we can pretend that an USB cable is inserted whenever we are not in host mode (i.e. whenever there is no USB-OTG adapter inserted). This means that the USB controller will stay active all the time. This is not much of a problem for getting started, right? :)
For this example, there was
qcom,usbid-gpio = <&msm_gpio 110 0>; defined downstream, so the USB ID pin is connected to GPIO 110. Now we declare a new device tree node, which sets up an extcon device using the USB ID GPIO. We put this under the root node (
/) because it is an entirely new node (previously we were mainly re-configuring existing device nodes):
#include <dt-bindings/gpio/gpio.h> / { /* ... */ usb_id: usb-id { compatible = "linux,extcon-usb-gpio"; id-gpios = <&msmgpio 110 GPIO_ACTIVE_HIGH>; pinctrl-names = "default"; pinctrl-0 = <&usb_id_default>; }; };
Something we have not seen before in this guide is pinctrl (or Pin Control): As mentioned earlier, MSM8916 has 122 GPIO pins that can be configured with different functions. The idea is that there are only so many physical pins you can afford to have on an SoC, but you want to expose a lot of features. Thankfully, most of the time you won't need to use all of the features in the same device, which is why SoC manufatcturers get away with multiplexing multiple functions behind one physical pin. The most common use of a pin is as a GPIO (basically a digital input/output line that can be either set high or low, respectively can be sensed to determine the level it was set to by something outside the SoC). But it's also possible to configure other functions (e.g. UART or I²C) for some of the pins. Additionally, pins can be configured with pull-up/pull-down resistors or with a particular drive strength. In the Linux kernel, the Pin Control Subsystem (pinctrl) handles that configuration.
In most cases you don't need to figure out yourself if you need pull-down/pull-up or a particular drive strength. We can check on downstream how the pins were configured and translate that to a similar configuration on mainline. While downstream may contain errors (like enabling an internal pull-up on a line with external one), it's proven to work reliably. When in doubt, a datasheet is of immense help. In our example here we find the following line downstream:
pinctrl-0 = <&usbid_default>;. We can then search for
usbid_default: in the related device tree files (if it exists multiple times, check which includes are actually used for your device). In this case, we find it in
msm8916-pinctrl.dtsi and it looks like:
usb-id-pin { qcom,pins = <&gp 110>; qcom,num-grp-pins = <1>; qcom,pin-func = <0>; label = "usb-id-pin"; usbid_default: default { drive-strength = <8>; bias-pull-up; }; };
The pin is configured as GPIO (
qcom,pin-func = <0>) with pull-up and a drive-strength of 8mA.
We can easily define a similar configuration on mainline: To do that, we define a new pin configuration as part of the
&msmgpio node, and then reference it with
pinctrl-names/
pinctrl-0 as seen above. The above example translates to the following:
&msmgpio { usb_id_default: usb-id-default { pins = "gpio110"; function = "gpio"; drive-strength = <8>; bias-pull-up; }; };
Finally, we assign our new extcon device to both
&usb and
&usb_hs_phy, and then USB should be working. :)
&usb { status = "okay"; extcon = <&usb_id>, <&usb_id>; }; &usb_hs_phy { extcon = <&usb_id>; };
&usbnode, the first extcon should point to the one that detects USB gadget mode, while the second one should detect USB host mode. In our case, our extcon device forces USB gadget mode as long as you don't connect an USB-OTG adapter. Later these would potentially be separate extcon devices. For
&usb_hs_phyonly the one for USB gadget mode should be specified.
MUIC
Especially Samsung devices do not have the USB ID pin connected to a GPIO like explained in the previous section. Instead, there is an additional chip that sits between the USB connector and the USB controller: a Micro-USB Interface Controller (or: MUIC). The MUIC handles all USB cable related detection and therefore pretty much represents an extcon device as we have set up manually using the USB ID GPIO in the last section.
The disadvantage is that we now need a special driver for the MUIC. Many different chips exist so often a driver is not available immediately, since you usually don't want to write an entire new driver before you know if mainline is booting on your device at all. Anyway, if there is a driver for it already, the approach to make it work would be the following:
- Identify the MUIC chip. Usually you can find it by searching for
muicin the downstream device tree. In this example we will use SM5502, which has the
extcon-sm5502.cdriver in mainline.
- Identify the I²C bus it is connected to. (it will probably be an I²C bus, but in theory it might be e.g SPI.) Samsung tends to use i2c-gpio, which emulates the I²C protocol on GPIO pins using bit banging. Note that sometimes they use i2c-gpio even when there is a hardware I²C bus available on the same pins. Not sure why they do that. They also sometimes add i2c-gpio-specific dts properties to hw I²C nodes. You can compare the SDA/SCL GPIO with the pins of the hardware I²C controllers and if it matches it is probably better to use the hardware I²C controller instead of i2c-gpio.
- Declare a new device tree node for the MUIC device (and eventually the i2c-gpio bus) and reference it as extcon for
&usb/
&usb_hs_phylike in the
usb_idexample above.
If the MUIC chip is not supported by a mainline driver (yet), check out the next section (#Otherwise) for now.
Let's get to the example. The downstream device tree contains:
i2c_9:i2c@9 { /* SM5502 GPIO-I2C */ compatible = "i2c-gpio"; i2c-gpio-scl = <&msm_gpio 3 0x00>; i2c-gpio-sda = <&msm_gpio 2 0x00>; /* ... */ sm5502@25 { compatible = "sm5502,i2c"; reg = <0x25>; interrupt-parent = <&msm_gpio>; interrupts = <12 0>; /* ... */ }; };
As mentioned earlier, there is actually a hardware I²C bus available on these pins (
blsp_i2c1) so we have two options. We can use the hardware I²C bus (preferred if possible):
&blsp_i2c1 { status = "okay"; muic: extcon@25 { compatible = "siliconmitus,sm5502-muic"; reg = <0x25>; interrupt-parent = <&msmgpio>; interrupts = <12 IRQ_TYPE_EDGE_FALLING>; pinctrl-names = "default"; pinctrl-0 = <&muic_int_default>; }; };
... or we can use i2c-gpio like Samsung:
#include <dt-bindings/gpio/gpio.h> / { /* ... */ i2c-muic { compatible = "i2c-gpio"; sda-gpios = <&msmgpio 2 (GPIO_ACTIVE_HIGH|GPIO_OPEN_DRAIN)>; scl-gpios = <&msmgpio 3 (GPIO_ACTIVE_HIGH|GPIO_OPEN_DRAIN)>; pinctrl-names = "default"; pinctrl-0 = <&muic_i2c_default>; #address-cells = <1>; #size-cells = <0>; /* muic: extcon@25 as above... */ }; };
How to define the pinctrl for these nodes is left as an exercise for the reader (see #ID pin for explanations). Ask if you need any help!
Otherwise
If you have neither USB ID GPIO nor MUIC, none of the options above will work for you. For now, please use the following hack for initial bringup:
/ { /* ... */ usb_vbus: extcon-usb-dummy { compatible = "linux,extcon-usb-dummy"; }; }; &usb { status = "okay"; extcon = <&usb_vbus>; dr_mode = "peripheral"; }; &usb_hs_phy { extcon = <&usb_vbus>; };
This is just meant as a simple way to get started with USB working. Please ask in the chat later how to clean this up properly. Once a better solution exists this section will be updated.
Testing
If you do not have (easy) access to UART, you now have the chance to boot your kernel for the first time!
- Make sure to build the kernel (see #Build Kernel).
- Create a postmarketOS installation:
pmbootstrap install
- Enable the
debug-shellhook. This will provide a telnet console via USB without having to flash the root file system to the internal storage.
- Boot the kernel using
pmbootstrap flasher boot. (Alternatively you could flash it using
pmbootstrap flasher flash_kerneland reboot, but that's not nearly as convenient during development...)
- With a bit of luck, the device should show up on telnet via USB after booting. Take a look at
dmesgto see the kernel log of mainline booting on your device!
Note that you need to remove the
debug-shell hook explicitly using
pmbootstrap initfs hook_del debug-shell before attempting to boot with the rootfs in the next section.
eMMC
If you have USB working, it's time to get the eMMC (internal storage) working next. This will allow you to flash the postmarketOS rootfs to get access to SSH instead of the minimal telnet session you had so far.
In most cases, enabling the eMMC should be as simple as adding:
&sdhc_1 { status = "okay"; pinctrl-names = "default", "sleep"; pinctrl-0 = <&sdc1_clk_on &sdc1_cmd_on &sdc1_data_on>; pinctrl-1 = <&sdc1_clk_off &sdc1_cmd_off &sdc1_data_off>; };
In this case, you don't need to write the pinctrl nodes yourself. Almost all of the devices use the same configuration here so these are shared for all devices in
msm8916-pins.dtsi.
That's it! Now you can build the kernel again, flash the rootfs using
pmbootstrap flasher flash_rootfs and boot as above. Make sure to remove the
debug-shell hook first using
pmbootstrap initfs hook_del debug-shell. With a bit of luck, you might boot straight into postmarketOS with working SSH! :)
SD card
Your device probably has a (micro) SD card slot. If you would like to keep your Android installation, you can flash the postmarketOS rootfs there alternatively. Or you can use it as extra/removable storage for some special files. It should be almost as simple as getting the eMMC working, so grab a micro SD card for testing and try to get it working:
#include <dt-bindings/gpio/gpio.h> &sdhc_2 { status = "okay";: Pick one! See below and compare with downstream... //cd-gpios = <&msmgpio 38 GPIO_ACTIVE_LOW>; //non-removable; };
Please take a close look at the comments here. The implementation of SD card detection varies depending on the device. The following two types are common:
- Hotplug detection using
cd-gpios(card detect): This allows detecting if the SD card is removed at runtime, so this is often used if the SD card is removable without turning off the device.
- Scanning for a SD card once during bootup: The assumption is that the device is
non-removableat runtime, e.g. because it is not accessible without removing the battery. In that case, they were able to omit the card-detect GPIO.
Check your downstream device tree for
cd-gpios (usually on the
&sdhc_2 node). If it exists, uncomment it here and also add
&sdc2_cd_on/off to the pinctrl lines. Otherwise, uncomment
non-removable.
That's it! Try to boot it and see if the SD card shows up in
lsblk or
dmesg. If you want, you can also try to mount it and read/write some files.
Buttons
As a last part of this guide, let's try to get the hardware buttons working. Your device probably has at least a (mechanical) Power, Volume Up and Volume Down button.
The Power and Volume Down buttons are usually connected to the PMIC (PM8916). The Power button is - obviously - used to power on the device. Volume Down is used in combination with the Power button to force a reboot (technically, this behavior is somewhat configurable, but thankfully it is usually set up like this), essentially simulating removing the battery and putting it back in. On devices without removable battery holding these two buttons allows rebooting ("resetting") the device.
On mainline, the
pm8941-pwrkey driver implements support for these two buttons. The power button is set up by default in the common
pm8916.dtsi include. As mentioned, the Volume Down button is typically connected to the "reset input" (resin). Theoretically, a device could have any button (or even some test points on the mainboard) connected there so we need to enable it explicitly and assign
KEY_VOLUMEDOWN:
&pm8916_resin { status = "okay"; linux,code = <KEY_VOLUMEDOWN>; };
Volume Up and other additional keys (e.g. Home on Samsung devices) are usually connected to a GPIO pin on the SoC. Therefore, setting them up is trivial using gpio-keys. Try to find the GPIOs in the downstream device tree and set up something like:
#include <dt-bindings/gpio/gpio.h> / { /* ... */ gpio-keys { compatible = "gpio-keys"; pinctrl-names = "default"; pinctrl-0 = <&gpio_keys_default>; label = "GPIO Buttons"; volume-up { label = "Volume Up"; gpios = <&msmgpio 107 GPIO_ACTIVE_LOW>; linux,code = <KEY_VOLUMEUP>; }; }; };
Make sure to set up pinctrl properly: typically these buttons need to be configured with
bias-pull-up.
To test the buttons,
apk add evtest. Then you can select the input devices in
evtest and see if an input event show up when you press them..
Device Tree Structure
So far you have assembled your device tree from various examples shown in this guide. For consistency with the other MSM8916 device trees, please make sure to put your device tree in the following order:
// SPDX-License-Identifier: GPL-2.0-only /dts-v1/; #include ... / { model = "Device Name"; // FIXME compatible = "<vendor>,<codename>", "qcom,msm8916"; // FIXME aliases { serial0 = &blsp1_uart2; }; chosen { stdout-path = "serial0"; }; /* Alphabetically ordered list of new device tree nodes */ }; /* Alphabetically ordered list of device tree node references, e.g. */ &blsp1_uart2 { status = "okay"; }; &usb { status = "okay"; }; /* Regulators and pinctrl always come last */ &smd_rpm_regulators { /* ... */ }; &msmgpio { /* ... */ };
Patch Requirements
To maintain the quality, all patches are required to:
- Compile without warnings
- Have no critical (
Firmware
Unfortunately, some components in the SoC rely on proprietary firmware to work properly:
- WiFi/Bluetooth (wcnss)
- Modem (modem)
- Hardware-accelerated video codecs (venus)
Perhaps more unfortunately, typically the firmware is signed with a device-specific key, which means you are forced to continue using the potentially outdated/buggy firmware provided by the stock firmware of your device manufacturer. This means that the firmware must be packaged separately for each device. The following files are needed:
wcnss.mdtplus all related segments (
wcnss.b00, ...) (usually installed on a separate firmware (
NON-HLOS) partition)
WCNSS_qcom_wlan_nv.bin(usually installed on the system partition, e.g.
/system/etc/firmware/wlan/prima/WCNSS_qcom_wlan_nv.bin)
mba.mbn,
modem.mdt,
modem.b00, ... (usually installed on a separate firmware (
NON-HLOSor
modem) partition)
venus.mdt,
venus.00, ... (usually installed on a separate firmware (
NON-HLOS) partition, or in
/system/etc/firmware/)
First, create a new firmware
APKBUILD." }
WiFi/Bluetooth
WiFi/Bluetooth are usually provided by the Qualcomm Wireless Connectivity Subsystem (WCNSS), which is partially built into the SoC but paired with an external RF module ("iris").[2] Therefore, enabling it is usually as simple as enabling the
&pronto node in the device tree:
&pronto {:
&pronto { status = "okay"; iris { compatible = "qcom,wcn3660b"; }; };
A few more notes:
- likely add the display panel to your device tree. The panel driver generator also generates a device tree fragment in the
.dtsi file that you can use as a base. Typically you just need to fill in the
reset-gpios, which can be found downstream. You should also add pinctrl to the
&dsi0 node. See commits for other devices for examples.
Note: If you have
qcom,regulator-ldo-mode defined downstream you should add (do not add it if you do not have this property downstream!):
&dsi_phy0 { qcom,dsi-phy-regulator-ldo-mode; };
In some cases, you may need to turn on a GPIO to enable the power supply of the panel. On mainline, this is implemented using a fixed regulator, which represents the hw component that creates the required voltage. You can then use the
--regulator option in the panel driver generator to add code to automatically turn on that GPIO.
Some devices have an extra backlight IC that needs to be controlled separately in the kernel. The easy case is where it is simply enabled using a GPIO: in this case one can simply treat it like a fixed regulator. (It may, in fact, actually be one.) of
The touchscreen is usually connected to an I²C bus, e.g.
blsp_i2c5. Often it is either supplied by some PM8916 regulators or a set of fixed regulators. (This is often visible when the touchscreen has some "enable" GPIOs listed downstream; those usually represent a chip that can be enabled through a GPIO and then supplies a fixed voltage to the touchscreen...) This is where similarities end. There can be all sorts of touchscreens connected to the I²C bus and manufacturers like to use many different ones. Look through the supported touchscreen in mainline to see if a driver exists already, or can be modified eventually to support another version of a similar chip. Otherwise, you may need to write a simple driver yourself.
Sensors
Like the touchscreen, sensors are usually connected to.
Testing
- The sensor should show up in sysfs (
/sys/bus/iio/devices/...). Usually there are some
in_*_rawfiles you can read for initial testing.
- Accelerometer: The accelerometer is used for automatic screen rotation, so let's make sure that works correctly.
- Install
iio-sensor-proxy(note: need to restart after installing it), start it (
rc-service iio-sensor-proxy start) and use
monitor-sensor.
- Check if the orientations are reported correctly. See File:PhoneRotation.png for a visualization of the different orientations.
- If the orientations are not correct you need a
mount-matrixin your device tree. See e.g. [this explanation].
- Interrupts: If your sensor has interrupts listed downstream you should also add them on mainline and check if they work correctly.
- Install
linux-tools-iio, then use
sudo iio_generic_buffer -a -c -1 -N <num>where
<num>is the number of the IIO device in sysfs (e.g.
/sys/bus/iio/devices/iio:deviceN.
- It should continuously print weird values.
- Check
/proc/interruptsif some interrupts were triggered for the sensor.
Audio
Audio functionality is split up in 3 main blocks (4 when using the modem):
- LPASS (Low Power Audio Subsystem): The "sound card". Reads/writes digital audio data from/to memory and transmits it via I²S.
- Digital Codec (
msm8916-wcd-digital): Accepts digital audio via I²S, post-processes it (e.g. to change volume). Transmits it via PDM to analog codec. (A proprietary Qualcomm protocol but perhaps there are similiarities to Pulse-density modulation...)
- Analog Codec (
msm8916-wcd-analog): Integrated into PMIC (PM8916). Contains DACs (playback) and ADCs (capture) and amplifiers for Speaker, Earpiece and Headphones.
- Audio DSP (
qdsp6): Can optionally sit between CPU and LPASS to offload audio decoding (e.g. MP3, AC, ...). Also handles voice call audio.
Here is diagram how the blocks relate to each other:
+---------------------------------------------+ | MSM8916 GPIO| Some devices use | | a custom speaker | +--------+ |Quaternary amplifier! | +-------+ | Modem | +-------+ | MI²S +-------------+ | | |<-->| (ADSP) |<-->| |<--> 112|<---->| Digital | | | Linux | +--------+ | LPASS |<--> 117|<---->| Audio Codec |--> Speaker | | (CPU) | Memory | |<--> 118|<---->| + Amplifier | | | |<---------------->| |<--> 119|<---->+-------------+ | +-------+ +-------+ | | Primary | ^ Tertiary | +---------------+ | MI²S | | MI²S | | PM8916 | | v | |PDM | | | +-------+<---> 63|<-->|CLK +--------+| | | |<---> 64|<-->|SYNC | ||<-- Microphone 1 | |Digital|<---> 65|<---|TX | Analog ||<-- Microphone 2 | | Codec |<---> 66|--->|RX0 | Codec ||--> Earpiece | | |<---> 67|--->|RX1 | ||--> Headphones | +-------+<---> 68|--->|RX2 +--------+|--> Speaker +---------------------------------------------+ +---------------+
Note: MI²S (multichannel I²S) is basically I²S with multiple data lines. This allows using more audio channels, although this is typically not used on MSM8916.
Custom Speaker Amplifier
The analog codec in PM8916 contains a mono Class-D (audio) amplifier. However, there are several devices that do not make use of it. Perhaps because the manufacturer thought it's not powerful enough, or because they wanted to include stereo speakers. In that case they have likely included a custom speaker amplifier. There are two types of this:
- Digital codec + speaker amplifier: This can be seen in the diagram above. It's connected via the Quaternary MI²S interface and contains it's own digital-to-analog converter (DAC).
- Sometimes they are just enabled with a GPIO, sometimes (especially TFA* amplifiers from NXP/Goodix) they are controlled via I²S and may even include their own audio DSP.
- A typical property of these is that it's difficult to control the audio volume in hardware. Instead, the digital audio data needs to be adjusted in software (typically handled by PulseAudio.)
- You need to add the amplifier to the device tree and then set up a DAI link for Quaternary MI²S.
- Example with enable GPIO:
arm64: dts: qcom: apq8016-samsung-matissevewifi: add sound
- Example with I²C:
arm64: dts: msm8916-samsung-a2015: Add sound card(Note: You typically need a driver specific to your amplifier in this case...)
- Analog speaker amplifier: This one sits behind the analog codec in PM8916 and just further amplifies the (analog) output signal. The speaker output is not suitable for this so most devices have the speaker amplifier connected additionally to one of the headphones output, i.e.
HPH_L(left channel) or
HPH_R(right channel). Typically they are activated using a GPIO. Sometimes there is an extra switch for the headphones as well, to make sure they don't activate when we just want to activate the speaker.
- You need to add the amplifier to the device tree (and eventually fixed regulators required for it). Then add it as
aux-devsto the sound card and set up
audio-routing.
- Example with amplifier connected to HPH_R and extra headphones switch:
arm64: dts: qcom: msm8916-wingtech-wt88047: Add sound
- Example with special amplifier connected to HPH_R without headphones switch:
arm64: dts: qcom: msm8916-bq-paella: Add sound
Testing
Please try to test as many of the features below as possible. If you don't have headphones or a headset you can obviously not test that.
- Speaker/Earpiece/Headphones audio playback
- Mic1/Mic2/Headset audio recording
- Note: Some devices only have one integrated microphone.
- Enable microphone via ALSA UCM / PulseAudio, then use (for example):
arecord -f dat -Dplughw:0,1 test.wav, then
aplay test.wavand check if you hear something.
- Audio jack detection
- Plug in/out headphones and check for
SW_HEADPHONE_INSERTin
evtest. It should be 1 when inserted, 0 otherwise. (Make sure it's not inverted!)
- Plug in/out headset and check for
SW_MICROPHONE_INSERTadditionally.
- If the headset has buttons, try pressing them and see if they show up in
evtest.
Modem
Camera
Battery/Charging
Although PM8916 provides a linear charger for batteries only few devices actually make use of it. This might be because it is comparatively inefficient compared to a switching mode battery charger. Therefore most devices actually have custom chips that manage the battery and charging. Usually it is separated in:
- Fuel gauge: Measures the remaining charge of the battery.
- Charger: Handles charging the battery.
Similar to the sensors, battery/charger are usually connected to an I²C bus. Look through the supported drivers in mainline (
drivers/power/supply) to see if a driver exists already, or can be modified eventually to support another version of a similar chip. Compare with the downstream driver just to be sure.
Glossary
- PM8916
- The PMIC used together with MSM8916.
- BAM
- Bus Access Manager, some kind of DMA (Direct Memory Access) engine. Basically it can copy data from memory to devices (e.g. UART, USB, ...) more quickly.
- BAM DMUX
- BAM Data Mux, a network protocol built using BAM that is used as a network interface to the modem.
- BLSP
- "BAM-enabled low-speed peripheral". Controllers for UART, I²C and SPI.
- LPASS
- Low-power audio subsystem
- MDSS
- Mobile Display Subsystem - the hardware that manages the display.
- MDP
- Mobile Display Processor - Part of MDSS that manages display panels.
- DSI
- MIPI Display Serial Interface (DSI) - used for communication with display panel.
- CAMSS
- Camera Subsystem
- SPMI
- System Power Management Interface - used for communication between MSM8916 and PM8916.
Remote Processors
- WCNSS
- Wireless Connectivity Subsystem (WCNSS). Provides WiFi and Bluetooth.
- Venus
- Provides hardware-accelerated video encoding/decoding.
- Modem
- Provides mobile connectivity and Audio DSP (ADSP). Note: On MSM8916, modem and ADSP are one remote processor, but the ADSP is usually separate on Qualcomm SoCs.
- Hexagon
- Microarchitecture for DSPs, used for ADSP/Modem/Sensor Hub/...
Documentation
- Specifications
- Register Descriptions
- Snapdragon 410E Technical Reference Manual (provides explanations for many hardware blocks)
- More documentation: APQ8016E Tools & Resources | https://wiki.postmarketos.org/index.php?title=MSM8916_Mainlining&curid=1143&diff=14961&oldid=14909 | CC-MAIN-2020-50 | refinedweb | 5,336 | 55.64 |
- I assume you have Eclipse installed
- I assume you have downloaded the Selenium RC
- The files selenium-server.jar and selenium-java-client-driver.jar will be needed
- In Eclipse create a new Java Project
- Pick a name for the project, set anything else you think you'll need on the first page
- On the next page, go to the Libraries tab and add the two selenium jar files to the project
- Finish
- Right click on the src folder and create a new JUnit Test Case
- Select JUnit 3, pick a package if you want (can be changed later), pick a name, tick setUp and tearDown, click Finish
- It should ask you if you want to add the JUnit 3 library to the project. Answer yes.
- You should now be looking at the JUnit test case class in the editor
- Change the class so it 'extends SeleneseTestCase
- You should get a warning on the SeleneseTestCase
- Hover over it and you should get the option to import com.thoughtworks.selenium.SeleneseTestCase which you should do
- In the setUp() method, the body should be:
- super.setUp(url, browser); where url is the URL of you web site being tested and browser is something like "*firefox", "*iehta" or "*safari"
- For example, super.setUp("", "*safari");
- The setUp method should now look like:
public void setUp() throws Exception { super.setUp("", "*safari"); }
- In the tearDown() method the body should be:
- super.tearDown();
- The tearDown method should now look like:
public void tearDown() throws Exception { super.tearDown(); }
- Now we can add a test case. It might look like:
- To run this, you'll need to start the Selenium Server.
- Go to a command line and enter:
- You might need some more command line switches like -firefoxProfileTemplate or -trustAllSSLCertificates. To see help on the server use:
- Once you have the server running, in Eclipse you want to run the test case as a JUnit Test
public void testAGoodDescriptionOfWhatWeAreTesting() throws Exception { selenium.open("/"); System.out.println(selenium.getHtmlSource()); }
java -jar selenium-server.jar
java -jar selenium-server.jar -help
NOTE: the SeleneseTestCase is a JUnit 3 TestCase. It assumes the names of the methods are fixed and does not use annotations. You have to use setUp, tearDown and all test cases need to start with 'test'. If you want to create the same thing as JUnit 4 you can use:
import org.junit.After; import org.junit.Before; import org.junit.Test; import com.thoughtworks.selenium.DefaultSelenium; import com.thoughtworks.selenium.Selenium; public class Whatever { Selenium selenium; @Before public void setUp() throws Exception { selenium = new DefaultSelenium("localhost", 4444, "*firefox", ""); } @Test public void whatever() throws Exception { selenium.open("/"); System.out.println(selenium.getHtmlSource()); } @After public void tearDown() throws Exception { selenium.close(); selenium.stop(); } }
And there is a simple test case create in Eclipse.
4 comments:
nicely explained..thank uuuuuuu
Hi bro, I'm a new commer to this one, I still haven't know what is Junit 3 .
I tried to do as you post, with the extends Testcase.
All I got after "run as" is run1/1 and failure 1/1 (your example).
Is it right ?
And why can't I use Extends SeleneseTestCase ?
Could you explain me a little bit here ?
My basic is just Java and a little html.
Dung,
Creating test automation with Selenium is programming and requires a certain amount of programming knowledge. The larger you expect the project to become, the more development skill you will need to exhibit.
You need to learn Java, Eclipse, JUnit and then learn Selenium.
If you want to learn Java, check out.
If you want to learn about Eclipse, check out.
If you want to learn about JUnit, check out..
Additionally, all these examples assume Selenium 1.0. Selenium 2.0 is very different. Look for posts from 2011 for examples of Selenium 2.0.
Thanks for your answer, I would start from Junit .
Could I ask you some more question .
BTW love your blog . | http://darrellgrainger.blogspot.com/2010/02/creating-selenium-test-case-in-java.html | CC-MAIN-2017-51 | refinedweb | 657 | 58.18 |
ESP8266 Overview
As I have already said, the main hardware part which we will give us connectivity is the ESP8266. What is it actually? You have probably used or at least heard of Arduino – a microcontroller platform people use to build all kind of electronics projects. Imagine a tiny chip that can be used for the same purposes like Arduino, plus it has built-in Wi-Fi capabilities and it can be acquired for roughly 2$! Also, it has considerably stronger processor – 32-bit, comparing to Arduino’s 8-bit. It outperforms Arduino in terms of processor speed and RAM memory. Unfortunately, it has limited number of GIPOs (General Purpose Input Output) and only one ADC (analog to digital converter). If there is a need for a higher number of GPIOs or ADCs, connecting an external microcontroller such as Arduino over some communication protocol (UART, I2C or SPI) solves a problem. Here is a more detailed specs list:
The ESP8266 is designed by a Chinese company Espressif and the production started in 2014. Thanks to its great features, this microcontroller attracted attention of many people – engineers, hobbyists, makers etc. There is even a blog dedicated to it.
Placing the ESP8266 on a Breadboard
We don’t use ESP8266 in our projects straight out from a factory. Other companies put chips together with some other components (flash memory, antenna, LEDs…) on breakout boards, which are then used as modules. Depending on the size and the number of exposed pins, there are many models available that are labeled as ESP-01, ESP-02, ESP-03… The most popular one is the ESP-12.
ESP-01
ESP-12
If you are building a very simple application or you want to add a connectivity to another microcontroller, you can use model ESP-01, which is very limited in terms of number of exposed pins, but even this model sometimes can be enough.
In case you want a board that doesn’t need any additional circuitry, doesn’t require any soldering and that you can start using by just plugging a USB cable, like the Arduino, than you can buy a board like this one. Also, companies like Sparkfun or Adafruit have their own breakout boards. However, I want to show you how you can set-up a bare module (ESP-12).
We have to add some additional circuitry to the module to work properly. First of all, you need to power your chip. These chips require 3.3V, and you shouldn’t apply higher voltage levels or you can damage your microcontroller! Also, you have to be careful if you are interfacing the ESP8266 with a device that uses 5V signal levels. A very convenient way to power your circuit is a board like this one, that is breadboard friendly and can be used to supply both 3.3V and 5V on the same breadboard. Then, you need a USB to TTL converter for programing the chip, like this one. It converts a signal that comes from a USB port of your computer to a signal suitable for the UART port of the ESP8266. Make sure that all signals are at the 3.3V level. Programs are stored in an external flash memory. In order to program the ESP8266, you need to connect a ground of the USB-TTL converter to a ground of the ESP8266. Then, connect TX and RX pins of the converter to RX and TX pins of the ESP8266, respectively. There are a few more steps to be done. The GPIO 2 should be high on boot. The GPIO 0 should be low while uploading a new program (flash update), and high on boot. If you are using the model ESP-12, then GPIO 15 should be low on boot as well. Connections should be done via resistors. I have used 2.2K resistors for this purpose. CH_PD pin which is chip-enable pin should be always high. I suggest you to add a reset button as well. Your circuit should look like this:
Circuit design
Here is the pinout for the ESP 12 model:
Pinout for ESP 12 model
You have probably noticed that the voltage level at GIPO 0 depends on whether you want to upload a new program, or to read an old program from flash memory. This means that you have to switch that one resistor from GND to Vcc and vice versa each time you want to upload a new program. If you want to avoid this, then you can build a small circuit shown in the following scheme. You need a USB – TTL converter that has DTR and RTS pins. You can also use some other BJT transistors than those in the scheme, I used 2n3904. Check the third scheme.
If you want to use any other module except ESP-01, you will have to acquire an adapter board on wich you solder your chip. Adapter board allows you to connect a chip to a breadboard. Also, you can solder jumper wires to directly to pins and avoid using the adapter board, although it is not that elegant solution. If you want to use ESP-01 module, you don't need the adapter board, but you will still need to use jumper wires because this module is not breadbord friendly.
Configuring the Arduino IDE
As I have already mentioned, we will use the Arduino IDE to program the ESP8266. If you don't have it installed, you can download it here. Make sure that your version is 1.6.4 or newer. The main reason for using the Arduino IDE for the ESP8266 over the original SDK is its simplicity and huge community.
Now you need to add an extension to the Arduino IDE so you can use it to program the ESP8266. Go to File > Preferences and in the Additonal Boards Managers URLs enter the URL for the ESP8266 package. Then go to Tools > Board and open Boards Manager. Find esp8266 by ESP8266 community and install it. Go to Tools > Board and select appropriate board (Generic ESP8266 module if you are using model ESP-01). You are ready to upload your first program. You can choose a simple program (Blink for example) from File > Examples and upload it to verify that you have configured everything properly. The upload process takes some time and after it finishes, the bottom part of the window should look like this:
Window
So far I explained the minimum work you have to do to start programming and running the ESP8266. As I have already said, this was just a brief explanation and I assumed that you have some experience with electronics and microcontrollers. If you are missing some information or have any troubles setting everything up, feel free to ask here. Also, if you want more detailed instructions on these topics and many others, you can check this free book written by Neil Kolban.
Thingspeak
After successfully uploading and running a blink sketch, now you want do something more challenging. You want to communicate to the net and exchange data. When you add the extension for the ESP8266 to the Arduino IDE, go to File > Examples and you can see dozens of example programs intended for this microcontroller. I suggest you to go through several programs to familiarize yourself with common function blocks for connecting to a network, connecting to a server, setting up a client or webserver, sending HTTP requests etc. The ESP8266 is a versatile chip, with broad range of possible applications. It can function as a station connecting to a local access point, as an access point, or both at the same time, which can be handy in some applications. You can see extensive list of Arduino functions for the ESP8266 in the book by Neil Kolban.
If you search for the ESP8266 tutorials online, you will probably come across many tutorials that explain how to connect the ESP8266 to a platform called Thingspeak. This is open source IoT platform that allows you to connect your devices, collect and visualize data. Communication is conducted over the HTTP protocol. It gives you possibility to write Matlab code to manipulate received data, which is very handy. You can also use it to easily fetch any data from a webpage. As there are already plenty resources on this, I will not cover it here, instead, I will give you an example code that sends POST requests with ADC (Analogue to Digital Converter) values which are plotted on your Thingspeak channel (note that the ADC on the ESP8266 is 10-bit with 1V maxim voltage). I have connected a potentiometer to the ADC for this purpose (I’ve used 1k potentiometer with two 1k resistors in series to limit maximum output).
Circuit design
Thingspeak offers a possibility to set reacts that are triggered on particular data changes. For example, turn on the cooler when the temperature rises above certain level. Since it is open source, there is a limit of the exchanged data over time.
After you make an account at, go to Channels > My Channels and click New Channel. Give it appropriate name and description if needed. Then, check the box for a field and give it a name, for example, ADC Value. We need only one field for this demonstration. There are also some other options like making the channel public or adding latitude and longitude values. After filling these values, click Save Channel. Under Private View, you should see a chart corresponding to the first field from our channel we named ADC value. Now go to API keys. We want to send a number (ADC value) over POST request. Since we want to write to a channel, we need the Write API Key that will be specified in the body of a request. This API Key serves as an authentication method. Copy and save this string. Then go to Data Import/Export. On the right side you see a list of available API (Application Programing Interface) calls. You can see a format of a POST request we want to send. We have to specify API key and field value. This format is used in the following code:
#include <ESP8266WiFi.h> //enter your values for ssid and password const char* ssid = ""; const char* password = ""; const char* host = "api.thingspeak.com"; //enter write API key String api_key = ""; void setup() { Serial.begin(115200); // We start by connecting to a WiFi network Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } void loop() { int ADC_value = analogRead(A0); // Use WiFiClient class to create TCP connections WiFiClient client; const int httpPort = 80; if (!client.connect(host, httpPort)) { Serial.println("connection failed"); return; } // We now create a URI for the request String url = "/update.json"; String content = String("api_key=") + api_key + "&" + "field1=" + ADC_value; int content_length = content.length(); Serial.print("Requesting URL: "); Serial.println(url); client.print(String("POST ") + url + " HTTP/1.1" + "\r\n" + "Host: " + String(host) + "\r\n" "Content-Length: " + content_length + "\r\n\r\n" + content + "\r\n\r\n" ); int _time = millis(); while(!client.available()){ delay(1); if(millis()-_time>3000){ //wait 3 seconds max for response Serial.println("No response."); break; } } while(client.available()){ String line = client.readStringUntil('\r'); //print response Serial.print(line); } client.stop(); Serial.println("closing connection"); delay(15000); //thingspeak limit }
After uploading this program, you should see points on the graph that represent ADC values. Right now, minimum time between two requests is 15 seconds.
ADC values
Now you can attach a sensor to your ADC to monitor some physical parameter, for example, a temperature sensor. I advise you to go to Apps and play around to see how you can extend your system. Add a Matlab code to manipulate data (visualize, store, convert, calculate mean values etc.), or set reacts that are triggered by your sensor values.
Power management is a very important aspect of the Internet of Things. Fortunately, there is a way to reduce power consumption of the ESP8266. It supports several sleep modes (modem, light and deep). The most efficient one is a deep sleep mode and radio capabilities are disabled when the chip goes in this mode. Power consumption drops dramatically to only 10 uA according to the documentation (around 70mA in normal operation), which can extend a battery life significantly. You can check the documentation for more details about different sleep modes.
If we want our chip to go to the deep sleep mode in the previous example, we could put this line of code ESP.deepSleep(15000000, WAKE_RF_DEFAULT) instead of delay(15000). Note that in this function time is set in microseconds. After 15 seconds, we want our chip to wakes up. We have to do a small hardware modification for this. You have to put a capacitor (I have used a 10uF electrolytic capacitor) between RST and GPIO 16 pins, and that’s it, we reduced power consumption of our chip significantly.
Circuit design
You have built your first IoT application! In the next posts, we will explore other communication protocols and IBM Bluemix platform that will allows us to build much more complex systems. | https://tuts.codingo.me/introduction-to-esp8266-module/ | CC-MAIN-2017-34 | refinedweb | 2,212 | 64.41 |
Odoo Help
Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps:
CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc.
Writing tests with new v8 api?
I want to write tests on v8 modules, but dont seem to find a way to use new api. In all examples I see that cr, uid is still used etc. Is it possible to write tests with new api. If so how (any references etc)?
Hello Andrius Laukavičius,
Yes, you can write tests using all new api stuff.
like,
from openerp.tests import common
class testPartnerCreate(common.TransactionCase):
def setUp(self):
super(testPartnerCreate, self).setUp()
def test_create(self):
res_partner = self.env['res.partner']
test_partner1 = res_partner.create(
dict(
name="Demo bhai",
city="test city",
))
......
Hope this will help.
Regards....
About This Community
Odoo Training Center
Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now | https://www.odoo.com/forum/help-1/question/writing-tests-with-new-v8-api-63413 | CC-MAIN-2017-51 | refinedweb | 160 | 63.05 |
Link Copied
Unfortunately I cant do what you suggest because my version of Parallel studio provides no such option. Under Configuration Properties my options are General, Debugging, Intel Debugging, c/c++, Linker, Manifest Tool, Browse Information, Build Events, Custom Build Step.
I would post a screen capture but the website does not seem to want to display a screen capture.
I have the same error running the following on terminal:
icc -c -xAVX optimizedV6.c
I get:
optimizedV6.c(12): catastrophic error: cannot open source file "mkl.h"
#include "mkl.h"
^
compilation aborted for optimizedV6.c (code 4)
Last time I ran the exact same line on terminal for version 4 and the code compiled perfectly in the same directory. I also tried removing the previously compiled code from the directory, but I am still getting the same problem. | https://community.intel.com/t5/Intel-oneAPI-Math-Kernel-Library/catastrophic-error-cannot-open-source-file-quot-mkl-h-quot/td-p/786175 | CC-MAIN-2021-21 | refinedweb | 139 | 58.08 |
The purpose of this article is to show how you can implement a table with the full set of data management functionalities in ASP.NET MVC using jQuery/AJAX with various plug-ins. Here is a list of the aimed functionalities:
My intention is to show how you can implement these functionalities with minimal effort using a jQuery DataTables Editable plug-in and thereby easily extending DataTable CRUD functionalities. Example of such kind of table is shown on the figure below:
All functionalities you see in the figure are pure JavaScript enchancement - on the server-side you just need to generate a pure HTML table. Everything you see in the table is implemented on the client-side using the following JavaScript call:
$('table#myDataTable').dataTable().makeEditable();
This line of code finds a table with id "myDataTable", and applies two JQuery plugins that add to the table all functionalities shown above. In the rest of the article I will show you how you can implement and customize this plugin.
This article might be considered as a second part in the series of articles that describes how to implement effective Web 2.0 interfaces with jQuery, ASP.NET MVC, and the jQuery DataTables plugin. In my previous article, I described how you can implement a DataTable with server-side pagination, filtering, and sorting which enables you to implement high-performance table operations. In this article, server-side actions are not described again, and focus is on the data management functionalities only. These two articles can help you to create effective Web 2.0 data tables with fully AJAXified functionalities.
A common requirement in web projects is to create a table where besides listing data, the user should be able to edit information, and add new or delete existing records. When a fully functional data table/data grid needs to be implemented, my choice is the jQuery DataTables plug-in. This plug-in takes a plain HTML table and adds several functionalities such as pagination, ordering by column, filtering by keyword, changing the number of records that should be displayed per page, etc. All you need to do is to include a single JavaScript call:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#myDataTable').dataTable();
});
</script>
In the example, myDataTable is the ID of the table that should be enhanced with the DataTables plug-in. Full description of the jQuery DataTables features can be found here. The picture that follows shows a plain HTML table after applying the DataTables plug-in.
myDataTable
DataTables itself provides a very good API for data manipulation (adding rows, deleting rows, etc.). However, a drawback is that you will need to learn the API functions and implement CRUD functionalities yourself because there is no out-of-the-box solution that enables you to easily implement CRUD functionalities. This might make one think of moving from DataTables to some other plug-in such as jqGrid (which is also a good plug-in, similar to DataTables) just because it has out-of-the-box configuration for CRUD functionalities. Therefore, my goal was to encapsulate the jQuery DataTables functionalities that are needed for the standard CRUD operations into a separate plug-in which adds CRUD functionalities on top of the standard set of DataTables functionalities and makes it possible for a developer to activate it as easily as possible. Code to initialize an editable data table is shown below:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#myDataTable').dataTable().makeEditable();
});
</script>
This line of code would result in a table that allows the user to edit data by double clicking on a cell, select and delete any row in the table, and add a new record. An example of the enhanced table can be found on the live demo site. Beside this, you'll need to create server-side code that accepts AJAX calls sent by the plug-in when the user changes some record and this article will guide you through this task.
For illustrative purposes, we'll use a simple ASP.NET MVC web application to list companies, delete them, add new or update existing company information. The first thing you need to do is to create a standard ASP.NET Model-View-Controller structure. There are three steps required for this setup:
In the beginning, we'll just display company information in a table. Then, this simple table will be enhanced with the jQuery DataTables Editable plug-in. The following JavaScript components need to be downloaded:
These files should be stored in the local file system and included in the HTML page that is rendered on the client. Example of usage of these files is explained below.
The model comes to a simple class containing company data. The fields that we need are company ID, name, address, and a town. The source code for the company model class is shown below:
public class Company
{
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Town { get; set; }
}
View is used to render data on the server-side and send HTML code to the browser. The example includes three different view pages that show different usage and configuration of the plug-in. There's one layout page that will be used by all these pages. This layout page is shown below:
<!DOCTYPE html>
<html>
<head>
<title>Customization of Editable DataTable</title>
>
<script src="@Url.Content("~/Scripts/jquery.jeditable.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.dataTables.editable.js")"
type="text/javascript"></script>
@RenderSection("head", required: false);
</head>
<body>
<div id="container">
<a href="/Company/Index">Basic Example</a>
<a href="/Company/Ajax">Getting data with Ajax</a>
<a href="/Company/Customization">Customization</a>
@RenderBody()
</div>
</body>
</html>
This layout page does not have any presentation logic - it just includes all the necessary JavaScript files and contains links to all the pages used in this example. Page specific content will be rendered when the @RenderBody() call is executed. In addition, this layout page allows you to include custom JavaScript that is specific to the pages in the "head" section. Note that the last JavaScript file is the DataTables Editable plug-in which covers the CRUD functionalities that will be presented in this example. The layout page is not required for your projects, but it allows to simplify the views so that they contain only code that is relevant for the examples. The view that renders the table is shown in the listing below:
@RenderBody()
@{
Layout = "~/Views/Company/JQueryDataTableEditableLayout.cshtml";
}
@section head{
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#myDataTable').dataTable().makeEditable();
});
</script>
}
<div id="demo">
<h1>Basic Example</h1>
<table id="myDataTable" class="display">
<thead>
<tr>
<th>Company name</th>
<th>Address</th>
<th>Town</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr id="@item.ID">
<td>@item.Name</td>
<td>@item.Address</td>
<td>@item.Town</td>
</tr>
}
</tbody>
</table>
<div class="add_delete_toolbar" />
</div>
This view uses the layout page described above, and puts the initialization JavaScript in the header that initializes the data table and makes it editable. The body contains a table with a company name, address, and town. The ID of each company is placed in an ID attribute of the surrounding <tr> tag - this is a place where the DataTables Editable plug-in expects to find the ID of the record that will be edited or deleted. Also, there is a <div> element with a class "add_delete_toolbar" which tells the DataTables Editable plug-in where it should place the auto-generated add and delete buttons.
<tr>
<div>
add_delete_toolbar
When a page is required by the user, the controller returns a company list that will be rendered in the view. Instead of a database, there is the DataRepository class that just returns a list of all the companies. An example of the controller with one action method that reacts to the /Company/Index request is shown below:
DataRepository
public class CompanyController : Controller
{
public ActionResult Index()
{
var companies = DataRepository.GetCompanies();
return View(companies);
}
}
When the "/Company/Index" request is sent from the client, this action method is executed and a set of all the companies from the repository is sent to the view.
The only thing you need to do is to create server-side actions that handle the add, delete, and update requests sent by the plug-in. These actions can be added as controller actions:
public class CompanyController : Controller
{
public string DeleteData(int id){ ... }
public string UpdateData(int id, string value, int? rowId,
int? columnPosition, int? columnId, string columnName){ ... }
public int AddData(string name, string address, string town, int? country){ ... }
}
The DeleteData action accepts the ID of the deleted row as a parameter and returns an "ok" string if the update is successful. Any other string value represents an error message that will be shown to the user.
DeleteData
The UpdateData action accepts the ID of the updated cell, a value entered by the user, and the position of the cell (column and row ID). The action should return text equal to the value input parameter. Any other string value represents an error message that will be shown to the user.
UpdateData
value
The AddData action has custom parameters representing all the information that should be saved when a new record is added. The given example uses the name, address, town, and country in the new company record, but in the other implementations, you will use arbitrary parameters, so you will need to create a custom form for adding a new record. The DataTables Editable plug-in handles opening your custom form in the dialog and posting form values to the server-side action shown above.
AddData
In the next section, I will explain how this plug-in is integrated in the example attached to this article.
The code described in the previous sections is necessary for rendering data and initializing the DataTables Editable plug-in. Once it's initialized, the plug-in allows you to perform the following functionalities:
The picture below shows the trace of AJAX calls that are sent to the server when these operations are performed by the user. The actions "DeleteData", "AddData", and "UpdateData" are the default AJAX URLs that are called by the plug-in and can be modified if necessary.
The following sections describe the implementation of the needed server-side actions that actually perform these operations on the real data.
Updating cells is done by using an inline editable plug-in called Jeditable. The DataTables Editable plug-in is internally configured to replace the cell content with an editable textbox when the user double clicks on the cell. The following figure shows how the user can edit data:
When the user finishes cell editing and presses Enter, the plug-in sends the AJAX call with the information about the edited value. The new cell content is sent to the server with a new value, the ID of the record, and the coordinates of the cell. The AJAX call that is sent to the server-side is shown below:
The AJAX request contains the following parameters:
id
ID
columnName
rowId
columnPosition
columnId
You will also need a controller action that will accept the request described above, receive information sent from the plug-in, update actual data, and return response. Example:
public class CompanyController : Controller
{
/// <summary>Action that updates data
/// </summary>
/// <param name="id">Id of the record</param>
/// <param name="value">Value that should be set</param>
/// <param name="rowId">Id of the row</param>
/// <param name="columnPosition">Position of the
/// column(hidden columns are not counted)</param>
/// <param name="columnId">Position of the column(hidden columns are counted)</param>
/// <param name="columnName">Name of the column</param>
/// <returns>value if update suceed - any other value
/// will be considered as an error message on the client-side</returns>
public string UpdateData(int id, string value, int? rowId,
int? columnPosition, int? columnId, string columnName)
{
var companies = DataRepository.GetCompanies();
if (columnPosition == 0 && companies.Any(
c => c.Name.ToLower().Equals(value.ToLower())))
return "Company with a name '" + value + "' already exists";
var company = companies.FirstOrDefault(c => c.ID == id);
if (company == null)
{
return "Company with an id = " + id + " does not exists";
}
switch (columnPosition)
{
case 0:
company.Name = value;
break;
case 1:
company.Address = value;
break;
case 2:
company.Town = value;
break;
default:
break;
}
return value;
}
}
This action accepts information about the ID of the updated record, the iD of the row where the updated cell is placed, and ID, position, and name of the column where the updated cell is placed. The code is simple. The company is found by using the ID, and one of the properties of the found record is updated depending on the position of the column. Instead of the column position, column name can be used - it depends on the server-side logic. If everything is fine, the returned value should be the same as a value sent by the plug-in in the request. Otherwise, the DataTables Editable plug-in will assume that the update has failed and that the returned text is an error message that should be shown to user. Hence, to notify the plug-in that an error occurred, the only thing you need to do is to return an error message (as shown in the example).
The DataTables Editable plug-in enables row selection and initializes a delete button. When the user selects a row, the delete button gets enabled, and after it's pressed, an AJAX request with an ID of the currently selected row will be sent to the server. The ID is taken from the id attribute of the <tr> tag. The AJAX request that is sent by the plug-in to the server-side page is shown below:
The server-side page should return an "ok" string if the record is successfully deleted, or an error message that should be shown to the user.
The Controller action that accepts an ID of the row that needs to be deleted and actually deletes a row is given in the following example:
public class CompanyController : Controller
{
/// <summary>
/// Method called but plugin when a row is deleted
/// </summary>
/// <param name="id">Id of the row</param>
/// <returns>"ok" if delete is successfully performed - any other
/// value will be considered as an error message on the client-side</returns>
public string DeleteData(int id)
{
try
{
var company =
DataRepository.GetCompanies().FirstOrDefault(c => c.ID == id);
if (company == null)
return "Company cannot be found";
DataRepository.GetCompanies().Remove(company);
return "ok";
}
catch (Exception ex)
{
return ex.Message;
}
}
}
If everything is fine, an "ok" string is returned back. Any other string that is returned from the code such as "Company cannot be found" or an exception message will be shown on the client-side as an error message, and deleting will be canceled.
Adding a new record is a bit complicated - in this case, it is not enough just to add one action in the controller. For adding a new record, it is necessary to add an HTML form that will be used for adding a new record. This form should have the id "formAddNewRow" and should contain the input elements that the user needs to populate. An example of the form is shown in the listing below:
formAddNewRow
<form id="formAddNewRow" action="#" title="Add new company">
<label for="name">Name</label><input type="text"
name="name" id="name" class="required" rel="0" />
<br />
<label for="name">Address</label><input type="text"
name="address" id="address" rel="1" />
<br />
<label for="name">Postcode</label><input
type="text" name="postcode" id="postcode"/>
<br />
<label for="name">Town</label><input
type="text" name="town" id="town" rel="2" />
<br />
<label for="name">Country</label>
<select name="country" id="country">
<option value="1">Serbia</option>
<option value="2">France</option>
<option value="3">Italy</option>
<br />
</form>
When the DataTables Editable plug-in detects the Adding new record form, the "Add" button will be auto-generated. When a user presses the "Add" button, the DataTables Editable plug-in opens a form in the new dialog window where the user can enter information about the new record (the dialog is shown below).
This form cannot be auto-generated because I assume that in each add functionality, you will need some custom form with various elements such as textboxes, calendars, etc. Therefore, I assume that it will be easier that you add a plain HTML form that suites you best and style it, rather than use some auto-generated functionality. In this form, it is important to add rel attributes to the input elements that should be copied to the table when a record is added. The rel attributes are used by the DataTable Editable plug-in to map values of the new record with the columns in the table. In the example given above, the values that will be entered in the name, address, and town inputs will be mapped to the columns 0, 1, and 2 of the table - rel attributes are used for this mapping.
rel
As it can be seen, OK and Cancel buttons do not need to be added in the form - the DataTables Editable plug-in adds them automatically as the last elements in the form. The form is automatically validated on the client-side using a jQuery validation plug-in. Therefore, you can add the "required", "email", "date", and other CSS classes to automatically implement client-side validation. In the above example, name is marked as required field and a client-side error message will be shown if this field is not populated. You can see what validation rules can be used on the jQuery validation plug-in site. When the DataTables Editable plug-in detects the "Add new record" form, it will enable the user to add a new record via that form and post elements found in the form to the server-side. When the user presses the "OK" button, an AJAX request is sent to the server and if everything is fine, the dialog is closed and a new row is added to the table. An example of the AJAX request that is sent from the form displayed above is shown on the following figure:
name
The AJAX call sends all the values of the input elements in the form and expects to get the ID of the new row back. Once the ID is returned, the new row is added, populated with the values from the form, and the returned ID of the record is set as an ID attribute of the new row.
DataTables Editable handles common operations such as opening a dialog, posting a request to the server, closing a dialog when Cancel is pressed, and adding a row in the table if an operation is successful. The only thing that needs to be done is creating a plain HTML form as a template for adding a new record, and a server-side action that accepts information about the new record.
The Controller action that accepts the data entered in the form is shown below:
public class CompanyController : Controller
{
public int AddData(string name, string address, string town, int country)
{
var companies = DataRepository.GetCompanies();
if (companies.Any(c => c.Name.ToLower().Equals(name.ToLower())))
{
Response.Write("Company with the name '" + name + "' already exists");
Response.StatusCode = 404;
Response.End();
return -1;
}
var company = new Company();
company.Name = name;
company.Address = address;
company.Town = town;
companies.Add(company);
return company.ID;
}
}
The signature of the method depends on the form parameters - for each parameter that is posted to the server, one argument in the method should be added. As the name, address, town, and country are posted from the client, these parameters are added in the method call. The Action method returns an integer value that represents the ID of the new record. If any error occurs (such as duplicate name constraint violation as shown in the example), an error message should be returned as a response text. Also, the status code of the response should be set to some HTTP error status. The actual value is irrelevant however, it is necessary to return some of the status codes in the 4xx or 5xx family to notify the DataTables Editable plug-in that the error occurred while trying to add a record. In this case, I used a 404 error message but the actual code is irrelevant - the only thing that is needed is that the plug-in detects that the error occurred and that it shows the response text to the user.
The DataTables plug-in can use either a row in the table as a source of data or it can be configured to use a JSON source from the server-side page. In the server-side mode, only data that should be shown on the current page is returned from the server and displayed in the table. The standard DataTables functionalities such as filtering, ordering, and pagination just forward the request to the server-side where the information is processed and returned back to the DataTables plug-in. This mode requires some server-side development but can significantly increase the performance. The DataTables Editable plug-in can detect whether the DataTables plug-in is used in server-side mode and support AJAX based functionalities. In this section, I will show you what modifications should be done in the DataTables Editable plug-in to work in this mode.
In the server-side mode, the model is not changed - the same company class is used as in the previous example.
I have created a different view page that renders the output to match the DataTables AJAX mode. The view is shown below:
@{
Layout = "~/Views/Company/JQueryDataTableEditableLayout.cshtml";
}
@section head{
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$('#myDataTable').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": 'TableData',
"aoColumns": [
{ "sName": "ID",
"bSearchable": false,
"bSortable": false,
"bVisible": false
},
{ "sName": "COMPANY_NAME" },
{ "sName": "ADDRESS" },
{ "sName": "TOWN" }
]
}).makeEditable();
});
</script>
}
<div id="demo">
<h2>Ajax example</h2>
<table id="myDataTable" class="display">
<thead>
<tr>
<th>ID</th>
<th>Company name</th>
<th>Address</th>
<th>Town</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
In the DataTables call in JavaScript are added the bServerside and sAjaxSource parameters. Also, columns are explicitly defined where you can see that the ID of the column is added as a hidden column. In the AJAX mode, you cannot easily put the ID of the record as an id attribute of the <TR> tag that surrounds a Company. Therefore, in the AJAX mode, the ID of each record that will be edited or deleted must be placed in the first hidden column of the table. The table body is empty because it is not generated on the server. Each time data is required, the DataTables plug-in calls the sAjaxSource page to get the JSON array that will be dynamically injected into the table body on the client-side. The only difference that should be done is in the "Add new row" form. As we have the first column to be the ID of the company, we need to put a matching input element with rel="0" in the form for adding a new row. The most convenient thing to do is to add this element as a hidden input without a name (so it will not be sent to the server), with some dummy value. This element is required so adding a new row in the table would not break due to the fact that the number of inputs in the form and columns in the table do not match. The value of this hidden field is irrelevant as the ID will be taken from the server and set in the table as an ID when a row is added. An example of the "Add new row" form is shown below:
bServerside
sAjaxSource
<TR>
</form>
In my previous article, I explained how you can implement a controller to work with DataTables in server-side mode. In short, two major differences are:
Integration of the DataTables plug-in with server-side code is not covered here, but you can find how this can be implemented in the article Integrating the jQuery DataTables plug-in into an ASP.NET MVC application. In this article, you can find how to replace client-side pagination, filtering, and ordering functionalities used in this article, with server-side actions, in order to improve the performance of DataTables.
In the examples above, I have shown a few out of the box functionalities of the DataTable Editable plug-in that can be used without any change. However, similar to the original DataTables plug-in, the DataTables Editable plug-in allows you to configure properties of the plug-in and customize it. In this section, I will explain how this plug-in can be customized.
The first thing you might want to change are URLs that will be called to update, delete, or add data. By default, if the URL of the page where the table is rendered is /Company/Index, URLs for data management operation will be /Company/UpdateData, /Company/AddData, and /Company/DeleteData. This is very convenient for ASP.NET MVC applications because these actions can be placed inside the same controller. If you have a different controller or set of views, e.g., /Employee/List or /Manager/Details, where the editable data table is placed, you will just add UpdateData, DeleteData, and AddData into the appropriate controllers and each page will call its data management action. However, you are able to completely customize data management URLs and put any URL you want. The example below shows how you can configure the DataTables Editable table to use PHP pages instead of ASP.NET MVC pages. You can put any value instead of these (other MVC pages, ASPX pages, etc.).
$('#myDataTable').dataTable().makeEditable({
sUpdateURL: "/Home/UpdateData.php",
sAddURL: "/Home/AddData.php",
sDeleteURL: "/Home/DeleteData.php"
});
You saw that lot of elements such as buttons are auto-generated by the plug-in. The only thing you need to do is to define an element with class "add_delete_toolbar" that will be the placeholder for Add and Delete buttons. If you want full control over the content, you can put these buttons directly in the view page. If DataTables Editable finds that buttons already exists, new ones will not be generated and event handlers will be attached to the existing ones. The only thing you need to do is to put the expected IDs into the HTML elements you want to use so DataTables Editable can find them. The default IDs of the elements are:
btnAddNewRow
btnAddNewRowOk
btnAddNewRowCancel
btnDeleteRow
Note that these elements do not need to be <button> HTML elements - you can place anything you want, e.g., <a>, <span>, <input>, <img>, etc. The only requirement is that these elements have expected IDs. If you do not like these IDs, you can change them too. This is suitable if you have two different tables you enhanced with the DataTables Editable plug-in on the same page and you do not want to mix their control buttons. An example configuration of the DataTables Editable plug-in with the definition of IDs of the control buttons is shown below:
<button>
<a>
<span>
<input>
<img>
$('",
sDeleteRowButtonId: "btnDeleteCompany",
});
To use this configuration, you will need to place elements with exactly same IDs and position them into the page wherever you like. If you don't want a placeholder for adding Add and Delete buttons to be a div with class add_delete_toolbar, you can change this too. The configuration I frequently use to inject the buttons in the table header on the right side of "Show XXX entries per page" is shown in the example below:
div
$('#myDataTable').dataTable().makeEditable({
'sAddDeleteToolbarSelector': '.dataTables_length'
});
The DataTables plug-in places "Show XXX entries per page" into the div with class "datatable_length". If I put this class as a selector for the toolbar, the DataTables Editable plug-in will inject Add and Delete buttons in that div.
datatable_length
If you don't like the standard browser's message box that is shown when an error occurs, you can change this behaviour. In the DataTables Editable initialization, you can pass your custom error function. This function should accept two parameter messages that will be shown and the action that caused an error. An example of using a custom show message function is shown in the example below:
$('#myDataTable').dataTable().makeEditable({
fnShowError: function (message, action) {
switch (action) {
case "update":
jAlert(message, "Update failed");
break;
case "delete":
jAlert(message, "Delete failed");
break;
case "add":
$("#lblAddError").html(message);
$("#lblAddError").show();
break;
}
}
});
In this example, when an error occurs when adding a new record, a message is placed in the error label with an ID "lblAddError" (the assumption is that this label is placed in the form that will be shown in the dialog and that it is initially hidden). For update and delete, error messages are used in a custom jAlert plug-in that shows a "fancy" message box instead of the standard one. You can use any other plug-in you want instead of this one. An example of implementation of custom messages can be found on this live demo site.
lblAddError
Editing cells using textboxes is default behaviour for the Jeditable but this plug-in enables you to use different editors for each column. As an example, in some cases, you will want to use a TextArea or select list for inline editing instead of a textbox.
If you pass aoColumns parameter to the datatable's initialization function, you will be able to configure the editors for each column in the table. The parameter aoColumns represents an array of objects containing the properties of the inline editor. An example of the implementation of custom editors can be found in this live demo site. Configuration of the custom column editors is shown in the script below:
aoColumns
$('#myDataTable').dataTable().makeEditable({
'}"
}
]
});
The first object in the aoColumns array definition is an empty object {}. If you pass an empty object as a configuration parameter for some column, the default editor will be used. The second object in the array is a null value. This value makes the column read-only, i.e., the editable plug-in will not be applied on the cells in the second column. This is useful if you have HTML links in some cells and you do not want to allow the user to edit them.
{}
null
The third element is the most interesting one. Here is placed a configuration object for the Jeditable editor that will be applied on the cells in the third column. The editor that will be used on the cells in the third column will be a select list (type: 'select') with the list elements defined in the data property. The inline select list that will be shown when the user click on the cells in the third column is shown in the following figure:
data
The data property contains a set of value:label pairs that will be used to build a list. A label will be shown in the list and the value will be used to update the cell content and it will be sent to the server-side. Submitting the selected value happens when the user clicks on any other cell causing the onblur event. The configuration is set so that the onblur selected value should be submitted to the server (onblur:'submit'). If you do not want this behaviour, you can remove the onblur:'submit' option and place the submit:'Ok' option in the configuration. This will add a submit button with the label 'Ok' to the left of the select list and the value will be submitted to the server when the user presses this button. You can even use a server-side page as a data source for the list if you put the loadurl parameter instead of the data parameter. This configuration forces the the loadurl parameter to read values for the select list from the URL instead of the local data array.
onblur
onblur:'submit'
submit:'Ok'
loadurl
Other parameters in the column configuration set the tooltip and text that will be shown while the editor is processing results using the AJAX call. The configuration parameters that can be used for the individual editor setup can be found on the Jeditable site, therefore it might be good to take a look at this site first if you are going to configure the individual editors per column.
Jeditable is av ery powerfull plugin that has a lot of plugins for custom input types so you can use date/time pickers, masked inputs, AJAX uploads, or even easily create your own editor. You can see the various input types on the Jeditable custom input demo site.
This article shows you how to create a datatable that has integrated add, edit, and delete functionalities using the jQuery Datatables Editable plug-in. This plug-in enables you to focus just on the server-side functionalities that handle data management requests and implement only code that is specific for your application. The complete example can be downloaded from above..
The plug-in with documentation is hosted here so you can take the plug-in or example of usage and include it in your project.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
public void AddStandard(int UnitID = 0, int NewLevel = 0, string NewStandard = "", string NewConcept = "", int NewSkill = 0, int NewDoK = 0)
{
var essentialstandard = new EssentialStandard();
essentialstandard.UnitID = UnitID;
essentialstandard.CommonCoreLevelID = NewLevel;
essentialstandard.CommonCoreStandardID = NewStandard;
essentialstandard.SkillID = NewSkill;
essentialstandard.Concepts = NewConcept;
essentialstandard.DOKID = NewDoK;
CFdb.EssentialStandards.Add(essentialstandard);
CFdb.SaveChanges();
}
loadurl : '/Company/Options',
Quote: // StartingYoA indicator: 'Saving...', tooltip: 'Click to edit', loadtext: 'loading...', type: 'select', onblur: 'cancel', submit: 'Ok', loadurl: '@Url.Action("GetYoAData")', loadtype: "GET"
Quote:{"":"","2020":"2020","2019":"2019",...}
<script type="text/javascript">
$('#formAddNewRow').dialog({ minWidth: 700, height: 400, autoOpen: false });
</script>
General News Suggestion Question Bug Answer Joke Praise Rant Admin
Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. | https://www.codeproject.com/articles/165410/asp-net-mvc-editable-datatable-jquery-datatables-a?msg=4257617 | CC-MAIN-2017-13 | refinedweb | 5,722 | 50.67 |
Asynchronously read from a file
#include <aio.h> int aio_read( struct aiocb * const aiocbptr ); int aio_read64( struct aiocb64 * const aiocbptr );
libc
Use the -l c option to qcc to link against this library. This library is usually included automatically.
The aio_read() function asynchronously reads aio_read64() function is a large-file support version of aio_read(). undefined. by read(), or one of the following:
The following condition may be detected synchronously or asynchronously:
aio_read() is POSIX 1003.1; aio_read64() is Large-file support
The first time you call an aio_* function, a thread pool is created, making your process multithreaded if it isn't already. The thread pool isn't destroyed until your process ends. | http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.neutrino.lib_ref/topic/a/aio_read.html | CC-MAIN-2018-43 | refinedweb | 113 | 64.41 |
- Declare a variable in a switch
- Terminate Boost::Thread
- C++ text file
- make an ide
- #define
- Using my own method in a constructor...
- linux C++ IDE with this particular feature:
- recursive help!!
- string manipulation question with strcpy and strcat and alike
- Making items in a set do stuff
- CPP Libraries to make charts
- Important info!
- How can i put standart input's every word to a vector?
- Class and Thread
- Standart Input?
- Running program on other computers
- Auto Calling Derived Fun
- Messy but C++, a lot of pointers.
- I don't know...
- A question about Vectors
- program run as service
- Update code for Vista 64
- image to array
- object missing in reference to `Window::border'
- Help for the basics
- declaring large array
- Vector Consists of Both Int and String, HELP
- Passing reference from a iterator
- Not inlined?
- exceptions
- Get processor info
- Linked List & Seg Fault
- An interesting code about a constructor calling a constructor
- help about 2d water
- translation!!
- templates and nameless namespaces
- Help: Convert C to C++
- RST problem ;\
- Hello Uncles and Aunties!
- Simple answer for intersecting lines?
- c++ stacked bar graph
- string manipulation problems
- getchar() and variant
- Problem compiling files that store functions
- problems in compiling svn from source...
- pointers
- Threading Question
- Wierd Problem with inputting.
- Is there any hidden complication?
- Prime Sieve Optimization | http://cboard.cprogramming.com/sitemap/f-3-p-299.html | CC-MAIN-2014-35 | refinedweb | 216 | 57.16 |
In Michael Dawson's book, " Beginning C++ Game Programming ", there was and exercise saying to rewrite a hangman game learned earlier in the book using functions. I tried all i could to get it run correctly, but i got nowhere. Can someone tell me what I am doing wrong?
I'm a little new to programming, so what i did probably looks dumb. Haha.
well here it is....
All help appreciated, thank you.All help appreciated, thank you.Code:#include <iostream> #include <string> #include <vector> #include <algorithm> #include <ctime> #include <cctype> using namespace std; const int MAX_WRONG = 8; int WRONG; string Guess(string soFar, string used); string check_guess(string guess, string used, string soFar, string THE_WORD); int main() { vector<string> words; words.push_back("AMAZING"); words.push_back("DIFFICULT"); words.push_back("COMPATABLE"); srand(time(0)); random_shuffle(words.begin(), words.end()); const string THE_WORD = words[0]; WRONG = 0; string soFAR(THE_WORD.size(), '-'); string used = ""; cout << "Welcome to Hangman. Good luck!\n"; while ((WRONG < MAX_WRONG) && (soFAR != THE_WORD)) { string guess(string soFar, string used); string check_guess(string guess, string used); } if (WRONG == MAX_WRONG) { cout << "\nYou've been hanged!"; } else { cout << "\nYou guessed it!"; } cout << "\nThe word was " << THE_WORD << endl; return 0; } string Guess(string soFar, string used) { cout << "\n\nYou have " << (MAX_WRONG - WRONG) << " incorrect guesses left."; cout << "\nYou've used the following letters:\n" << used << endl; cout << "\nSo far, the word is:\n" << soFar << endl; char guess; cout << "\n\nEnter your guess: "; cin >> guess; guess = toupper(guess); while (used.find(guess) != string::npos) { cout << "\nYou've already guessed "; cout << "Enter your guess: "; cin >> guess; guess = toupper (guess); } used += guess; return guess, used; } string check_guess(string guess, string used, string soFar, string THE_WORD) { if (THE_WORD.find(guess) != string::npos) { cout << "That's right! " << guess << " is in the word."; for (int i = 0; i < THE_WORD.length(); ++i) { cout << THE_WORD[i]; } } else { cout << "Sorry, " << guess << " isn't in the word."; ++WRONG; } return guess; } | https://cboard.cprogramming.com/cplusplus-programming/128626-hangman-functions-assignment-michael-dawsons-book.html | CC-MAIN-2017-22 | refinedweb | 315 | 67.45 |
Longest Palindromic Substring using Palindromic Tree | Set 3
Given a string, find the longest substring which is palindrome. For example, if the given string is “forgeeksskeegfor”, the output should be “geeksskeeg”.
Prerequisite : Palindromic Tree | Longest Palindromic Substring ‘u’ is already a palindrome, hence the resulting string at node v will also be a palindrome. x will be a single character for every edge. Therefore, a node can have max 26 insertion edges (considering lower letter string). create all the palindromic substrings and then return the last one we got, since that would be the longest palindromic substring so far.
Since a Palindromic Tree stores the palindromes in order of arrival of a certain character, so the Longest will always be at the last index of our tree array.
Below is the implementation of above approach :
C++
Python3
# Python3 code for Longest Palindromic
# substring using Palindromic Tree
# data structure
class Node:
def __init__(self, length = None,
suffixEdge = None):
# store start and end indexes
# of current Node inclusively
self.start = None
self.end = None
# Stores length of substring
self.length = length
# stores insertion Node for all
# characters a-z
self.insertionEdge = [0] * 26
# stores the Maximum Palindromic
# Suffix Node for the current Node
self.suffixEdge = suffixEdge
# Function to insert edge in tree
def insert(currIndex):
global currNode, ptr
# Finding X, such that s[currIndex]
# + X + s[currIndex] is palindrome.
temp = currNode
while True:
currLength = tree[temp].length
if (currIndex – currLength >= 1 and
(s[currIndex] == s[currIndex –
currLength – 1])):
break
temp = tree[temp].suffixEdge
# Check if s[currIndex] + X +
# s[currIndex] is already Present in tree.
if tree[temp].insertionEdge[ord(s[currIndex]) –
ord(‘a’)] != 0:
currNode = tree[temp].insertionEdge[ord(s[currIndex]) –
ord(‘a’)]
return
# Else Create new node
ptr += 1
tree[temp].insertionEdge[ord(s[currIndex]) –
ord(‘a’)] = ptr
tree[ptr].end = currIndex
tree[ptr].length = tree[temp].length + 2
tree[ptr].start = (tree[ptr].end –
tree[ptr].length + 1)
# Setting suffix edge for newly Created Node.
currNode = ptr
temp = tree[temp].suffixEdge
# Longest Palindromic suffix for a
# string of length 1 is a Null string.
if tree[currNode].length == 1:
tree[currNode].suffixEdge = 2
return
# Else
while True:
currLength = tree[temp].length
if (currIndex – currLength >= 1 and
s[currIndex] == s[currIndex –
currLength – 1]):
break
temp = tree[temp].suffixEdge
tree[currNode].suffixEdge = \
tree[temp].insertionEdge[ord(s[currIndex]) – ord(‘a’)]
# Driver code
if __name__ == “__main__”:
MAXN = 1000
# Imaginary root’s suffix edge points to
# itself, since for an imaginary string
# of length = -1 has an imaginary suffix
# string. Imaginary root.
root1 = Node(-1, 1)
# NULL root’s suffix edge points to
# Imaginary root, since for a string of
# length = 0 has an imaginary suffix string.
root2 = Node(0, 1)
# Stores Node information for
# constant time access
tree = [Node() for i in range(MAXN)]
# Keeps track the Current Node
# while insertion
currNode, ptr = 1, 2
tree[1] = root1
tree[2] = root2
s = “forgeeksskeegfor”
for i in range(0, len(s)):
insert(i)
# last will be the index of our
# last substring
last = ptr
for i in range(tree[last].start,
tree[last].end + 1):
print(s[i], end = “”)
# This code is contributed by Rituraj Jain
geeksskeeg
Recommended Posts:
- Suffix Tree Application 6 - Longest Palindromic Substring
- Longest Palindromic Substring | Set 2
- Longest Non-palindromic substring
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 4
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 2
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 3
- Manacher's Algorithm - Linear Time Longest Palindromic Substring - Part 1
- Make palindromic string non-palindromic by rearranging its letters
- Longest Palindromic Subsequence | DP-12
- Minimum cuts required to convert a palindromic string to a different palindromic string
- Palindromic Tree | Introduction & Implementation
- Palindromic Primes
- Lexicographically first palindromic string
- Number of palindromic permutations | Set 1
- Palindromic Selfie | https://www.geeksforgeeks.org/longest-palindromic-substring-using-palindromic-tree-set-3/ | CC-MAIN-2019-26 | refinedweb | 627 | 53.92 |
No Record Selector Functions
This proposal is a precursor to overloaded record fields. It's also a modest step towards freeing up the namespace, without in any way pre-judging how the 'narrow namespace issue' might get addressed. Ticket #5972.
There is to be a compiler flag -XNoRecordSelectorFunctions. (Default value ‑XRecordSelectorFunctions, to give H98 behaviour.)
-XNoRecordSelectorFunctions suppresses creating the field selector function from the field name in a record-style data declaration.
Suppressing the function frees up the namespace, to be able to experiment with various record/field approaches -- including the 'cottage industry' of Template Haskell solutions.
In particular, this means we can declare more than one record type within a module using the same field name.
-XNoRecordSelectorFunctions implies -XDisambiguateRecordFields -- otherwise the only way to access record fields would be positionally. It also implies ‑XNamedFieldPuns and ‑XRecordWildCards to support field access and update. (IMHO, suppressing the field selector function should always have been part of -XDisambiguateRecordFields. I'm by no means the first to make that observation.)
- Note that the field name is still valid within the scope of a pattern match, or record update inside the MkT{...} explicit constructor syntax.
- But record update won't work, because the field name alone doesn't uniquely identify the record type.
(That is, the syntax with a record or expression prefix to the braces e{ x = True } -- there might be multiple record types declared in the module with field name x.)
Example use case: (referred from an old Wiki discussion on TDNR .)
See also thread starting: (and continuing through February), which initially considers nested modules as an approach for namespacing.
Import/Export and Representation hiding
Since there is no field selector function created, it can't be exported or imported.
If you say:
{-# OPTIONS_GHC -XNoRecordSelectorFunctions #-} module M( T( x ) ) where data T = MkT { x, y :: Int }
then the existence of field y is hidden; type T and field label x are exported, but not data constructor MkT, so x is unusable.
(Without the ‑XNoRecordSelectorFunctions flag, field selector function x would be exported.)
There's an effect on importing modules even if they don't set -XNoRecord..., so that they are generating selector functions for record types they declare:
- The record types imported do not have field selector functions, so compilation must not generate code to (try to) use them.
- But other uses of the field name must still work: (pattern matching, punning and wildcards, record creation using explicit data constructor (and -XDisambiguateRecordFields).
- Record update e{ x = True } won't work. | https://ghc.haskell.org/trac/ghc/wiki/Records/DeclaredOverloadedRecordFields/NoMonoRecordFields?version=5 | CC-MAIN-2016-18 | refinedweb | 418 | 54.32 |
Big O Analysis a tutorial: of Big O analysis would be this: it measures the efficiency of an algorithm based on thetime it takes for the algorithm to run as a function of the input size. Think of the input simply as what goes into a function whether it be an array of numbers, a linked list, etc. Sounds quite boring, right? Its really not that bad at all and it is something best illustrated by an example with actual code samples. Example of Big O Analysis Lets suppose that we are given a problem in which we want to create a function that, when given an array of integers greater than 0, will return the integer that is the smallest in that array. In order to best illustrate the way Big-O analysis works, we will come up with twodifferent solutions to this problem, each with a different Big-O efficiency. Heres our first function that will simply return the integer that is the smallest in the array. The algorithm will just iterate through all of the values in the array and keep track of the smallest integer in the array in the variable called curMin. Lets;
// iterate through array to find smallest value for (x = 1; x < 10; x++) { if( array[x] < curMin) { curMin = array[x]; } }
As promised, we want to show you another solution to the problem. In this solution, we will use a different algorithm. What we do(isMin) break; }
return array[x]; } Now, you've seen 2 functions that solve the same problem - but each one uses a different algorithm. We want to be able to say which algorithm is more efficient, and Big-O analysis allows us to do exactly that. Big O analysis in action ) algorithm. Big O analysis measures efficiency.
DFS (Depth First Search) and BFS (Breadth First Search) are search algorithms used for graphs and trees. When you have an ordered tree or graph, like a BST, its quite easy to search the data structure to find the node that you want. But, when given an unordered tree or graph, the BFS and DFS search algorithms can come in handy to find what youve levels child nodes while searching that level. The pointers are stored in FIFO (First-In-First-Out) queue. This, in turn, means that BFS uses a large amount of memory because we have to store the pointers. Subscribe to our newsletter on the left to receive more free interview questions! An example of BFS He.
An example of DFS Heres an example of what a DFS would look like. The numbers represent the order in which the nodes are accessed in a DFS:
Comparing BFS and DFS, the big advantage of DFS is that it has much lower memory requirements than BFS, because its not necessary to store all of the child pointers at each level. Depending on the data and what you are looking for, either DFS or BFS could be advantageous. For example, given a family tree if one were looking for someone on the tree whre looking for. What.
A binary search tree is a sorted data structure trees O(log(n)) will definitely be fast enough. So, given all that information, a binary search tree is the data structure that you should use in this scenario, since it is a better choice than a hash table. Suppose that you are given a linked list that is either circular or or not circular (another word for not circular is acyclic). Take a look at the figures below if you are not sure what a circular linked list looks like.
Write a function that takes as an input a pointer to the head of a linked list and determines whether the list is circular or if the list has an ending node. If the linked list is circular then your function should return true, otherwise your function should return false if the linked list is not circular. You can not modify the linked list in any way. This is an acyclic (non. Too difficult a solution nodes pointer to the previous nodes directly. So, for the nth node, we just compare its next pointer to see if it points to any nodes from 1 to n 1. If any of those nodes are equal then we know that we have a circular linked list. Lets. Try using 2 pointers. So, this is another solution, and here is the pseudocode for this problem: 2 pointers travelling at different speeds start from the head of the linked list Iterate through a loop If the faster pointer reaches a NULL pointer then return If we write the actual code for this, it would look like this: bool findCircular(Node *head) { Node *slower, * faster; slower = head; faster = head;, whats the worst case if we know that the list is circular? In this case, the slower pointer will never go around any loop more than once so it will examine a maximum of n nodes. The faster pointer, however, will examine 2n nodes and will have pass the slower pointer regardless of the size of the circle which makes it a worse case of 3n nodes. This is O(n). And what about the worst case when the list is not circular acyclic? Then the faster pointer will have come to the end after examining n nodes, while the slower pointer will have examined n/2 nodes for a total of 3/2n nodes, which is also O(n). Thus, the algorithm is O(n) for both worst case scenarios. Suppose..
Lets its left child is printed out before the subtree of its right child. This sounds like a legitimate algorithm, so we can say that when doing a preorder traversal, for any node we would print the node itself, then follow the left subtree, and after that follow the right subtree. Lets. psuedocode: public class Node {
public Node leftNode() {return left;} public Node rightNode() {return right;}
} Given the Node class above, lets write a recursive method that will actually do the preorder traversal for us. In the code below, we also assume that we have a method called printNodeValue which will print out the Nodes value for us. void preOrder (Node root) {
root.printNodeValue();
} Because every node is examined once, the running time of this algorithm is O(n). Suppose that you are given a binary tree like the one shown in the figure below. Write some code in Java that will do a postorder traversal for any binary tree and print out the nodes as they are encountered. So, for the binary tree in the figure below, the algorithm will print the nodes in this order: 2, 5, 11, 6, 7, 4, 9, 5, 2 where the very last node visited is the root node
When trying to figure out what the algorithm for this problem should be, you should take a close look at the way the nodes are traversed there is a pattern in the way that the nodes are traversed. If you break the problem down into subtrees you can see that these are the operations that are being performed recursively at each node: 1. 2. 3. Traverse the left subtree Traverse the right subtree Visit the root postorder traversal for us. In the code below, we also assume that we have a method called printNodeValue which will print out the Nodes value for us. void postOrder (Node root) {
} Because every node is examined once, the running time of this algorithm is O(n).
Suppose that you are given a binary tree like the one shown in the figure below. Write some code in Java that will do an inorder traversal for any binary tree and print out the nodes as they are encountered. So, for the binary tree in the figure below, the algorithm will print the nodes in this order: 2, 7, 5, 6, 11, 2, 5, 4, 9 note that the very first 2 that is printed out is the left child of 7, and NOT the 2 in the root node
When. Lets Nodes value. This is what it would look like in Java psuedocode: inorder traversal for us. In the code below, we also assume that we have a method called printNodeValue which will print out the Nodes value for us. void inOrder (Node root) { if(root == null) return; inOrder( root.leftNode() ); root.printNodeValue(); inOrder( root.rightNode() ); } Because every node is examined once, the running time of this algorithm is O(n).
How do threads interact with the stack and the heap? How do the stack and heap work in multithreading?In a multi-threaded application, each thread will have its own stack. But, all the different threads will share the heap. Because the different threads share the heap in a multi-threaded application, this also means that there has to be some coordination between the threads so that they dont try to access and manipulate the same piece(s) of memory in the heap at the same.
How long does memory on the stack last versus memory on the heapOnce a function call runs to completion, any data on the stack created specifically for that function call will automatically be deleted. Any data on the heap will remain there until its manually deleted by the programmer.
Can the stack grow in size? Can the heap grow in size?
The stack is set to a fixed size, and can not grow past its. 2. 3. 4. 5. 6. 7. 8.
Compiler Design, Operating System, Database Management System, Statistical analysis package, Numerical Analysis, Graphics, Artificial Intelligence, Simulation
3. What are the major data structures used in the following areas : RDBMS, Network data model and Hierarchical data model.
1. 2. 3.
RDBMS = Array (i.e. Array of structures) Network data model = Graph.
Two. One queue is used for actual storing of data and another for storing priorities.?
8. Convert the expression ((A + B) * C - (D - E) ^ (F + G)) to equivalent Prefix and Postfix notations.
1. 2..
1. 2. 3. 4.
12. List out few of the applications that make use of Multilinked Structures?
13. In tree construction which is the suitable efficient data structure? (Array, Linked list, Stack, Queue)
14. What is the type of the algorithm used in solving the 8 Queens problem?
Backtracking.. 2. 3. 4. 5. 6. 7.
Direct method, Subtraction method, Modulo-Division method, Digit-Extraction method, Mid-Square method, Folding method, Pseudo-random method.
18. What are the types of Collision Resolution Techniques and the methods used in each of the type?
Open addressing (closed hashing), The methods used include: Overflow block.. What is a spanning Tree? A spanning tree is a tree associated with a network. All the nodes of the graph appear on the tree once. A minimum spanning tree is a spanning tree organized so that the total edge weight between nodes is minimized. 21..
Data-structure Test
FILO
FIFO
LILO
Yes
No
Insertion
Deletion
Updation
Retrieval
The left subtree of a node contains only nodes with keys less than the node's key
The right subtree of a node contains only nodes with keys greater than the node's key.
Noth left and right subtree nodes contains only nodes with keys less than the node's key
6. The time required in best case for search operation in binary tree is
O(n)
O(log n)
O(2n)
O(log 2n)
In red-black trees, the leaf nodes are not relevant and do not contain data.
In red-black trees, the leaf nodes are relevant but do not contain data.
11. Which of the following linked list below have last node of the list pointing to the first node?
random
order of priority
False
True
Binary trees
Stacks
Graphs
15. A ___________ tree is a tree where for each parent node, there is only one associated child node
degenerate tree
16. In graphs, A hyperedge is an edge that is allowed to take on any number of _____________
Vertices
edges
labels
nodes
data
address
Hash tables
Heaps
Both a and b
Skip list
19. In a heap, element with the greatest key is always in the ___________ node
leaf
root
20. In _____________tree, the heights of the two child subtrees of any node differ by at most one
Binary tree
Splay tree
AVL tree
Correct 8. What is the pecularity of red blac trees? You answered: In red-black trees, the leaf nodes are relevant but do not contain data. Incorrect Correct answer: In red-black trees, the leaf nodes are not relevant and do not contain data. 9. Which of the following ways below is a pre order traversal? Correct 10. Which of the following ways below is a In order traversal? Correct 11. Which of the following linked list below have last node of the list pointing to the first node? You answered: circular linked list Incorrect Correct answer: circular singly linked list 12. Items in a priority queue are entered in a _____________ order You answered: order of priority Incorrect Correct answer: random 13. A tree cannot contain cycles. Correct 14. Breadth First search is used in You answered: Both a and c above Incorrect Correct answer: Graphs 15. A ___________ tree is a tree where for each parent node, there is only one associated child node Correct 16. In graphs, A hyperedge is an edge that is allowed to take on any number of _____________ You answered: both a and b above Incorrect Correct answer: edges 17. An empty list is the one which has no Correct 18. Key value pair is usually seen in Correct 19. In a heap, element with the greatest key is always in the ___________ node Correct 20. In _____________tree, the heights of the two child subtrees of any node differ by at most one. | https://it.scribd.com/document/69149252/Data-Structures | CC-MAIN-2020-40 | refinedweb | 2,311 | 69.11 |
- Articles
- Documentation
- Distributions
- Forums
- Sponsor Solutions.
Soothsayer is a library with many plugins which
can be configured to create a predictive system tailored to your text
entry task. If you are entering text in a language Soothsayer does not
know or you are planning to use Soothsayer in a specialized domain
containing special words or an abnormal distribution of the more
common words, then
text2ngram
can be used to produce a custom n-gram database that is
tailored to your needs.
There are no Soothsayer binary packages for Ubuntu, Fedora or
openSUSE in the standard repositories. For this article I'll use version
0.6.1 and build from source on a Fedora 8 machine. Building Soothsayer
requires the SQLite development
packages to be installed. Soothsayer uses autotools to build with the
standard
./configure; make; sudo make install process.
The Soothsayer distribution includes a few demonstration programs,
shown below is
soothsayerDemo after typing
hi
t and pressing F3 to complete the word "there". The vertical bars
represent word separations. As Soothsayer offers new predictions the
older ones are moved to the right. When you first start soothsayerDemo,
a bar and an initial off the bat prediction is shown. These are the two
rightmost rectangles in the screenshot below. Typing "hi " accounts for
the next two rectangles and the space rectangle shown in the middle of
figure. Note that once I pressed space Soothsayer attempted to guess
what might be the next word and presented the top six predictions.
Typing the "t" gave Soothsayer enough information to suggest the word
"there" so I hit F3 to complete. Soothsayer then inserted that text
together with a space and again offered a prediction as to what might be
the next word after the space.
/--------------------------------------------------------------------------------\ |hi there | | | | | \--------------------------------------------------------------------------------/ /--\ /----\ /-\ /-----\ /---\ /-\ /-------\ /----\ /---\ /-\ |F1| |was | ||| |that | |the| ||| |himself| |he | |the| ||| |F2| |is | ||| |t | |and| ||| |hideous| |his | |and| ||| |F3| |are | ||| |there| |of | ||| |hidden | |had | |of | ||| |F4| |were| ||| |they | |to | ||| |history| |him | |to | ||| |F5| |had | ||| |them | |a | ||| |high | |have| |a | ||| |F6| |and | ||| |this | |i | ||| |hide | |her | |i | ||| \--/ \----/ \-/ \-----/ \---/ \-/ \-------/ \----/ \---/ \-/ Last selected word: there
Notice that the words Soothsayer offers after the space character are different in the last (leftmost) rectangle. This is because many of the common words that were offered after space was initially input do not make sense after the text "hi there". With the setup that Soothsayer comes with initially the word "was" is the most likely word at this point in input.
Soothsayer offers both a C++ and Python programmer interface. A fairly concise example of usage from C++ is given in the doc/getting_started.txt file of the distribution. Below is a similar program with a leaner while loop to make the core processing more obvious. For each new character that you type soothconsole.cpp will try to complete the next word for you and show you what it thinks you after after.
// soothconsole.cpp #include "soothsayer.h" #include <iterator> #include <iostream> #include <sstream> #include <vector> #include <string> using namespace std; #include <termios.h> #include <unistd.h> int main( int, char** ) { char c; stringstream ss; Soothsayer soothsayer; struct termios tio; tcgetattr(STDIN_FILENO,&tio); tio.c_lflag &=(~ICANON & ~ECHO); tcsetattr(STDIN_FILENO,TCSANOW,&tio); while( cin >> noskipws >> c ) { if( c == '\n' ) ss << ' '; else ss << c; vector<string> p = soothsayer.predict ( ss.str() ); cerr << "Predictions for:" << ss.str() << endl; copy( p.begin(), p.end(), ostream_iterator<string>(cerr,"\n")); } return 0; }
As mentioned above, you can create custom predication models using
the text2ngram program. Soothsayer is configured using a default XML
file which a
make install will have placed on your
machine. If you copy that XML file into your home directory you can
modify the default ngram prediction model that Soothsayer will use for
you. In the example below I create a new model from the text of Alice in
Wonderland. As you can see, the predictions offered strongly reflect
what has been used to create the prediction model used by Soothsayer.
Normally a single "a" would not complete to "alice," but in the data
used to generate this particular prediction model that word has been
flagged as an important word starting with the letter "a."
$ cp /usr/local/etc/soothsayer.xml ~/.soothsayer.xml $ vi ~/.soothsayer.xml ... <Plugins> <SmoothedNgramPlugin> <LOGGER>ERROR</LOGGER> <DBFILENAME>/home/ben/alice-ngram.db</DBFILENAME> ... $ for i in `seq 1 4` do text2ngram -n $i -l -f sqlite -o ~/alice-ngram.db alice13a.txt done $ soothconsole Predictions for:a and a alice as at all ... Predictions for:alice in w which with without waiting wonderland was
The Soothsayer plugin system gives you flexibility to modify Soothsayer to give predictions based on different methods. The ability to train Soothsayer with text from the domain that you want to use it with should let you see more effective completion offerings, especially for words that occur frequently in your domain but not in common English. As you can see in the Alice in Wonderland example, using a prediction model that is tailored to the text you are intending to type greatly effects the predictions that Soothsayer makes, and can lead to more efficient completions.. | http://www.linux.com/archive/feature/135093 | crawl-002 | refinedweb | 842 | 53.92 |
Have you looked to see if the number of Lua owned blocks is going up during execution? In debug mode lua keeps a count and mem size (see lmem.h): #ifdef LUA_DEBUG extern unsigned long memdebug_numblocks; extern unsigned long memdebug_total; extern unsigned long memdebug_maxmem; extern unsigned long memdebug_memlimit; #endif Probably there are references accumulating that lua doesn't think it can release and it just has to traverse them all. Why they are accumulating is the real question but my crystal ball is not working right now. ;-> Russ > From: "Martin Stone" <Martin.Stone@creations-group.com> > Reply-To: lua-l@tecgraf.puc-rio.br > Date: Tue, 5 Feb 2002 16:53:54 -0000 > To: Multiple recipients of list <lua-l@tecgraf.puc-rio.br> > Subject: Garbage collection slowdown > > Hello everyone. I wonder if anyone can help me... > > I'm repeatedly forcing garbage collection every frame (in a game) like this: > > lua_setgcthreshold(L, 0); > > The time taken for this function to complete seems to increase with each call. > In between calls the same lua function is called every frame, generating > (presumably) a fixed amount of garbage each time. > > Does anyone know what I can do about this? > > Thanks, > > Martin. > > | http://lua-users.org/lists/lua-l/2002-02/msg00065.html | CC-MAIN-2016-44 | refinedweb | 198 | 56.45 |
Scala FAQ: Can you share some examples of how to implement break and continue functionality in Scala?Back to top
Introduction
Sure. The example Scala code below shows both a break and a continue example. As you can see from the
import statement, it uses the code in the Scala
util.control.Breaks package.
To understand how this works, let's first look at the code, and then the output.
First, here's the code:
package com.alvinalexander.breakandcontinue import util.control.Breaks._ object BreakAndContinueDemo extends App { // 1) BREAK: this example breaks out of the for loop when (i > 4) println("\n=== BREAK EXAMPLE ===") breakable { for (i <- 1 to 10) { println(i) if (i > 4) break // break out of the for loop } } // 2) CONTINUE: this example acts like a Java continue statement // "A continue statement skips the current iteration of a for, while , or do-while loop." println("\n=== CONTINUE EXAMPLE ===").") }
Here's the output from the code:
=== BREAK EXAMPLE === 1 2 3 4 5 === CONTINUE EXAMPLE === Found 9 p's in the string.
To understand how this code works, let's break it down a little bit.
The break example
The Scala break example is pretty easy to reason about. Again, here's the code:
breakable { for (i <- 1 to 10) { println(i) if (i > 4) break // break out of the for loop } } // more code here ...
In this case, when
i becomes greater than
4, the
break word (a method, actually) is reached. At this point an exception is thrown, and the
for loop is exited. The
breakable word (also a method) catches the exception, and the code continues with anything else that might be after the
breakable block.
The continue example
If you read the explanation for the
break example, you should be able to reason about how the
continue example works. First, here's the code:.")
Following the earlier explanation, as we walk through the characters in the String variable named
searchMe, if the current character is not the letter
p, we break out of the if/then statement, and the loop continues executing.
What really happens here is that the
break keyword is reached, an exception is thrown, and that exception is caught by
breakable. The exception serves to get us out of the if/then statement, and catching it allows the loop to continue executing with the next element.
About that continue example
I know that
continue example is pretty lame, but it's all I could come up with. It's a variation of the Java continue example at.
If you know Scala, you know that there are much better ways to write this example in Scala. A direct solution is to use the
count method:
val count = searchMe.count(_ == 'p')
When this code is run,
count will be
9.
Another 'continue' example
While testing the “continue” approach, I just came up with the following example, which prints the numbers "1,3,5,7,9":
import util.control.Breaks._ object BreakTests extends App { for (i <- 1 to 10) { breakable { if (i % 2 == 0) break println(i) } } }
Hopefully seeing that simpler example will also be helpful.Back to top
Scala breakable and break - A little more information
If you dig into the source code for the util.control.Breaks package, you'll see that
breakable is defined like this:
def breakable(op: => Unit) { try { op } catch { case ex: BreakControl => if (ex ne breakException) throw ex } }
You'll also see that
break is defined like this:
def break(): Nothing = { throw breakException }
I encourage you to dig into that source code to learn a little more about how this works.
Summary
If you needed to see some Scala break and continue examples, I hope this tutorial has been helpful.Back to top
Add new comment | http://alvinalexander.com/scala/scala-break-continue-examples-breakable | CC-MAIN-2017-30 | refinedweb | 631 | 61.26 |
Introduction: In previous Asp.Net MVC articles i explained What is Asp.Net MVC? Its work flow,goals and advantages and Difference between Asp.Net Webforms and Asp.Net MVC and Asp.Net MVC 4 application to Create,Read,Update,Delete and Search functionality using Razor view engine and Entity Framework .
In this article i am going to explain How to solve the following Asp.net MVC errors:
In this article i am going to explain How to solve the following Asp.net MVC errors:
- The type or namespace name 'DbContext' could not be found (are you missing a using directive or an assembly reference?)
- The type or namespace name 'DbSet' could not be found (are you missing a using directive or an assembly reference?)
Implementation: Follow the steps mentioned below to resolve the error:
1. Select the Project Name in Solution Explorer.
2. From the Tools Menu of visual studio, select Library Package Manager which has a sub-menu.
3. From the sub-menu select Package Manager Console.
4. Package manager console will open in the bottom of the visual studio screen
5. At the Package manager console prompt type install-package EntityFramework and then hit enter. (Note: Internet Connection is required while running this command because it downloads the EntityFramework package.
6. It will download and install the required Entity Framework.
After successfully completing the above steps right click on your project in Solution Explorer and Select Add reference -> Select the .NET tab and then scroll down and select System.Data.Entity and Click Ok button. It will add the reference of required Entity.
Now you just need to add the reference
using System.Data.Entity;
in the model class where you are facing error and the bug will be gone.
using System.Data.Entity;
in the model class where you are facing error and the bug will be gone.
Now over to you:
" I hope you have got the way to resolve the errors
Muito obrigado.Reply
Your welcome..stay connected and keep reading for more useful updates like this..:)Reply
greatReply
Thanks for the appreciation..:)Reply
THANK YOU!!Reply
Your welcome..stay connected for more useful updates..).. | https://www.webcodeexpert.com/2013/11/the-type-or-namespace-name-dbcontext.html | CC-MAIN-2021-43 | refinedweb | 361 | 60.82 |
Password-Less Authentication in Rails
Authentication is one of the key elements of many web applications. It is the stone wall between the application and its users, so it’s important that the authentication approach is secure and easy to use. But, what is this “authentication”? It’s a way of ensuring only users authorized by our application are allowed to use the application. As I am sure you know, there are many ways to authenticate a user, such as Email/Password, OpenID Connect, SAML, SSO, and so on.
Today, we’re going to take a look at another approach: Password-less authentication.
What is Password-less Authentication?
When a user registers for a website, the application allows the user to chose their credentials, usually a username or email/password. The user can then enter those credentials anytime to login to the application. Password-less authentication is basically eliminating the password part and using just the email to both register and login.
How this works is, when a user registers to our application, an email is sent to activate their account. This allows us to verify if the email belongs to the user. Now that we have a verified email, the next time that user tries to login, we will send them an email with the token for the user to use to sign into the app. Once the user clicks on the link with the token, the application will authenticate the user.
Let’s get started. Initialize your rails application:
$ rails new passwordless $ cd passwordless
To get a clearer sense of what’s really happening, we won’t be using any libraries or gems for this tutorial.
Creating the Model
Let’s start with creating the model necessary for our application. We are going to call this model
User since it’s users we are authenticating. But you are free to use anything that works.
$ rails g scaffold user fullname username:uniq email:uniq login_token token_generated_at:datetime $ rails db:create && rails db:migrate
The
fullname and
username are optional. We’ve added
username to enable users to login via either
username. We also have couple of other columns,
login_token and
token_generated_at, which are basically the one time password we generate for our users, along with when it was generated.
There’s a unique constraint at the table level, but let’s also add the ActiveRecord validations for the model. Add the following to the app/models/user.rb:
validates :email, :username, uniqueness: true, presence: true
Along with this, let’s also add a before filter to format the
username and
... before_save :format_email_username def format_email_username self.email = self.email.delete(' ').downcase self.username = self.username.delete(' ').downcase end
Here we basically strip the spaces in
username and
Since we’re going to allow for users to login via username and email, let’s add a helper method that fetches the user record based on either:
... def self.find_user_by(value) where(["username = :value OR email = :value", {value: value}]).first end
With the model done and in place, let’s go ahead and create our controller file and the necessary routes. Before we go about creating the registration controller, quickly create a static page to show messages:
$ rails g controller static home
Add the below route to config/routes.rb:
root 'static#home'
Along with this, also add the following line to your app/views/layouts/application.html.erb, which is used to display messages to the user:
... <body> <p id="notice"><%= notice %></p> ...
Generate a users controller:
$ rails g controller users
In config/routes.rb, add the following routes which we’ll use for user registration:
resources :users, only: [:create] get '/register', to: 'users#register'
Now, let’s add the code in app/controllers/users_controller.rb that corresponds to the routes declared above:
def register @user = User.new end def create @user = User.new(user_params) if @user.save redirect_to root_path, notice: 'Welcome! We have sent you the link to login to our app' else render :register end end private def user_params params.require(:user).permit(:fullname, :username, :email) end
Now, create the view file for registration under app/views/users/register.html.erb and add the this form to it:
<h1>Register</h1> <%= form_for(@user) do |f| %> <% if @user.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@user.errors.count, "error") %> prohibited this @user from being saved:</h2> <ul> <% @user.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :fullname %> <%= f.text_field :fullname %> </div> <div class="field"> <%= f.label :username %> <%= f.text_field :username %> </div> <div class="field"> <%= f.label :email %> <%= f.text_field :email %> </div> <div class="actions"> <%= f.submit 'Register' %> </div> <% end %>
Noting special in this form. This is a standard Rails, scaffole-generated form which captures the
fullname,
username, and
create endpoint. Start the Rails server and head over to
/register and see the registration is live now!
Login Link
Let’s get to the meaty part of the application: sending login emails. Basically, when a new user registers or whenever they request to login, we’d have to send them a login link with a token. When the link is clicked, the app will login the user. Begin by adding the following helper methods to our apps/models/user.rb for sending emails:
... def send_login_link generate_login_token template = 'login_link' UserMailer.send(template).deliver_now end def generate_login_token self.login_token = generate_token self.token_generated_at = Time.now.utc save! end def login_link "{self.login_token}" end def login_token_expired? Time.now.utc > (self.token_generated_at + token_validity) end def expire_token! self.login_token = nil save! end private def generate_token SecureRandom.hex(10) end def token_validity 2.hours end end
Please don’t get hung up on where the code that sends the mail lives. I am trying to keep the noise down as much as possible and focus on the higher-level concepts. I would never put a
UserMailer, for example, in a model, but this is for demonstration purposes only.
So, we have the
send_login_link method which we’ll make use of shortly to send the login link for a user. Before storing it to our database, we are actually hashing it using BCrypt which makes it more secure in case of a data breach. Along with this also add the gem ‘bcrypt’ to your Gemfile.
Once we generate the login token, send it to the user in an email using ActionMailer
UserMailer. Setting up the mailing functionality is skipped in this tutorial since there are many good tutorials out there that explain how to do them according to your email provider. Just make sure you include the link argument that we pass to the UserMailer in `send_login_link` method in your email template that you send to the user.
The
login_link is configured with a
localhost url, but change it accordingly for your application. Also, the
token_validity duration is set to 2 hours, but you are free to change it, obviously. Finally, add this line to the app/controllers/users_controller.rb
create action right after the
@user.save line:
... if @user.save @user.send_login_link ...
Now that we have the necessary helper methods in place, let’s add the receiving route to handle the login link we send in the email.
Session Controller
Start by generating the controller for session.
$ rails g controller session auth
Update in the config/routes.rb file, changing
get 'session/auth' to
get '/auth/:user_id/:token', to: 'session#auth'. In the generated session_controller.rb file, add this code:
def auth token = params[:token].to_s user_id = params[:user_id] user = User.find_by(id: user_id) if !user || !user.valid_token? redirect_to root_path, notice: 'It seems your link is invalid. Try requesting for a new login link' elsif user.login_token_expired? redirect_to root_path, notice: 'Your login link has been expired. Try requesting for a new login link.' else sign_in_user(user) redirect_to root_path, notice: 'You have been signed in!' end end
Using the helper method, check whether the token is a valid or if it’s expired. If it’s not valid, redirect to the home page with the appropriate messages. There is a helper method we have used,
sign_in_user, which we have to create. Open up app/controllers/application_controller.rb and add:
def sign_in_user(user) user.expire_token! session[:email] = user.email end def current_user User.find_by(email: session[:email]) end
We basically expire the token of the user and store the user’s email to the session. Also, we have added a helper method to retrieve the user from the session. The password-less functionality is ready, go ahead and try registering for a new user for testing the login functionality.
As a final step, we’ll make use of our helper methods to do the user login. Start by adding these routes to the config/routes.rb file:
resources :session, only: [:new, :create]
and add the below code to the /app/controllers/session_controller.rb file:
def new end def create value = params[:value].to_s user = User.find_user_by(value) if !user redirect_to new_session_path, notice: "Uh oh! We couldn't find the username / email. Please try again." else user.send_login_link redirect_to root_path, notice: 'We have sent you the link to login to our app' end end
We have just made use of the
send_login_link to do the heavy lifting. The final piece of the app is the login form. Create the file app/views/session/new.html.erb and add the following form:
<%= form_tag "/session" do %> <label> Email / Username </label> <%= text_field_tag "value" %> <%= submit_tag "Login" %> <% end %>
It’s just a simple form that does the job for us.
Conclusion
With that, we have arrived at the conclusion of the tutorial. Password-less login is really picking up these days and it provides our users with a less distracting and more convenient way to authenticate. Oh, and it also provides less overhead for everyone involved. I encourage you to try the password-less login approach for your application, at least as a supplemental method for login. That would be a start!
All the sample code used in this tutorial is available on Github, feel free to fork and play with it. I thank you for reading the tutorial and I hope it served your purposes. | https://www.sitepoint.com/password-less-authentication-in-rails/ | CC-MAIN-2018-47 | refinedweb | 1,689 | 58.89 |
How to solve machine learning problems in the real world
Becoming a machine learning engineer pro is your goal? Sure, online ML courses and Kaggle-style competitions are great resources to learn the basics. However, the daily job of a ML engineer requires an additional layer of skills that you won’t master through these approaches.
By Pau Labarta Bajo, mathematician and data scientist.
So, you want to become a professional machine learning engineer? Tempted to take (yet another) online course on ML to land that first job
Online courses on Machine Learning and Kaggle-style competitions are great resources to learn the fundamentals of machine learning. However, the daily job of a machine learning engineer requires an additional layer of skills that you won’t master there.
In this article, I will give you 4 tips to help you solve ML problems in the real world. I have learned them (the hard way) while working as a freelance ML engineer at Toptal. By the way, if you would also like to work on a freelance basis (highly recommended!) you can check my blog post on how to become one.
Photo by Valdemaras D. from Pexels.
The gap between machine learning courses and practice
Completing many online courses on ML seems like a safe path to learning. You follow along with the course code on Convolutional Nets, you implement yourself, and voila! You become an expert in Computer Vision!
Well, you don’t.
You are missing 4 key skills to build successful ML solutions in a professional environment.
Let’s start!
1. Understand the business problem first, then frame it as a Machine Learning problem.
When you follow an online course or participate in a Kaggle competition, you do not need to define the ML problem to solve.
You are told what to solve for (e.g., predict house prices) and how to measure how close you are to a good solution (e.g., mean squared error of the model predictions vs. actual prices). They also give you all the data and tell you what the features are, and what is the target metric to predict.
Given all this information, you jump straight into the solution space. You quickly explore the data and start training model after model, hoping that after each submission, you climb a few steps in the public leaderboard. Technical minds, like software and ML engineers, love to build things. I include myself in this group. We do that even before we understand the problem we need to solve. We know the tools, and we have quick fingers, so we jump straight into the solution space (aka the HOW) before taking the time to understand the problem we have in front of us (aka the WHAT).
When you work as a professional data scientist or ML engineer, you need to think of a few things before building any model. I always ask 3 questions at the beginning of every project:
- What is the business outcome that management wants to improve? Is there a clear metric for that, or do I need to find proxy metrics that make my life easier?
It is crucial you talk with all relevant stakeholders at the beginning of the project. They often have much more business context than you and can greatly help you understand what the target you need to shoot at is. In the industry, it is better to build an okay-ish solution for the right problem than a brilliant solution for the wrong problem. Academic research is often the opposite.
Answer this first question, and you will know the target metric of your ML problem.
- Is there any solution currently working in production to solve this, like another model or even some rule-based heuristics?
If there is one, this is the benchmark you have to beat in order to have a business impact. Otherwise, you can have a quick win by implementing a non-ML solution. Sometimes you can implement a quick and simple heuristic that already brings an impact. In the industry, an okay-ish solution today is better than a brilliant solution in 2 months.
Answer this second question, and you will understand how good the performance of your models needs to be in order to make an impact.
- Is the model going to be used as a black-box predictor? Or do we intend to use it as a tool to assist humans in making better decisions?
Creating black-box solutions is easier than explainable ones. For example, if you want to build a Bitcoin trading bot, you only care about the estimated profit it will generate. You backtest its performance and see if this strategy brings you value. Your plan is to deploy the bot, monitor its daily performance, and shut it down in case it makes you lose money. You are not trying to understand the market by looking at your model. On the other hand, if you create a model to help doctors improve their diagnosis, you need to create a model whose predictions can be easily explained to them. Otherwise, that 95% prediction accuracy you might achieve is going to be of no use.
Answer this third question, and you will know if you need to spend extra time working on the explainability, or you can focus entirely on maximizing accuracy.
Answer these 3 questions, and you will understand WHAT the ML problem you need to solve is.
2. Focus on getting more and better data
In online courses and Kaggle competitions, the organizers give you all the data. In fact, all participants use the same data and compete against each other on who has the better model. The focus is on models, not on the data.
In your job, the exact opposite will happen. Data is the most valuable asset you have that sets apart successful from unsuccessful ML projects. Getting more and better data for your model is the most effective strategy to improve its performance.
This means two things:
- You need to talk (a lot) with the data engineering guys.
They know where each bit of data is. They can help you fetch it and use it to generate useful features for your model. Also, they can build the data ingestion pipelines to add 3rd party data that can increase the performance of the model. Keep a good and healthy relationship, go for a beer once in a while, and your job is going to be easier, much easier.
- You need to be fluent in SQL.
The most universal language to access data is SQL, so you need to be fluent at it. This is especially true if you work in a less data-evolved environment, like a startup. Knowing SQL lets you quickly build the training data for your models, extend it, fix it, etc. Unless you work in a super-developed tech company (like Facebook, Uber, and similar) with internal feature stores, you will spend a fair amount of time writing SQL. So better be good at it.
Machine Learning models are a combination of software (e.g., from a simple logistic regression all the way to a colossal Transformer) and DATA (capital letters, yes). Data is what makes projects successful or not, not models.
3. Structure your code well
Photo by Igor Starkov from Pexels.
Jupyter notebooks are great to quickly prototype and test ideas. They are great for fast iteration in the development stage. Python is a language designed for fast iterations, and Jupyter notebooks are the perfect match.
However, notebooks quickly get crowded and unmanageable.
This is not a problem when you train the model once and submit it to a competition or online course. However, when you develop ML solutions in the real world, you need to do more than just training the model once.
There are two important aspects that you are missing:
- You must deploy your models and make them accessible to the rest of the company.
Models that are not easily deployed do not bring value. In the industry, an okay-ish model that can be easily deployed is better than the latest colossal-Transformer that no one knows how to deploy.
- You must re-train models to avoid concept drift.
Data in the real-world changes over time. Whatever model you train today is going to be obsolete in a few days, weeks, or months (depending on the speed of change of the underlying data). In the industry, an okay-ish model trained with recent data is better than a fantastic model trained with data from the good-old-days.
I strongly recommend packaging your Python code from the beginning. I directory structure that works well for me is the following:
my-ml-package ├── README.md ├── data │ ├── test.csv │ ├── train.csv │ └── validation.csv ├── models ├── notebooks │ └── my_notebook.ipynb ├── poetry.lock ├── pyproject.toml ├── queries └── src ├── __init__.py ├── inference.py ├── data.py ├── features.py └── train.py
Poetry is my favorite packaging tool in Python. With just 3 commands you can generate most of this folder structure.
$ poetry new my-ml-package $ cd my-ml-package $ poetry install
I like to keep separate directories for the common elements to all ML projects: data, queries, Jupyter notebooks, and serialized models generated by the training script:
$ mkdir data queries notebooks models
I recommend adding a
.gitignore file to exclude
data and
models from source control, as they contain potentially huge files.
When it comes to the source code in
src/ I like to keep it simple:
data.pyis the script that generates the training data, usually by quering an SQL-type DB. It is very important to have a clean and reproducible way to generate training data, otherwise you will end up wasting time trying to understand data inconsistencies between different training sets.
features.pycontains the feature pre-processing and engineering that most models require. This includes things like imputing missing valus, encoding of categorical variables, adding transformations of existing variables, etc. I love to use and recommend scikit-learn dataset transformation API.
train.pyis the training script that splits data into train, validation, test sets, and fits an ML model, possibly with hyper-parameter optimization. The final model is saved as an artifact under
models/
inference.pyis a Flask or FastAPI app that wraps your model as a REST API.
When you structure your code as a Python package your Jupyter notebooks do not contain tons of function declarations. Instead, these are defined inside
src and you can load them into the notebook using statements like
from src.train import train.
More importantly, clear code structure means healthier relationships with the DevOps guy that is helping you and faster releases of your work. Win-win.
4. Avoid deep learning at the beginning
Nowadays, we often use the terms Machine Learning and Deep learning as synonyms. But they are not. Especially when you work on real-world projects.
Deep Learning models are state-of-the-art (SOTA) in every field of AI nowadays. But you do not need SOTA to solve most business problems.
Unless you are dealing with computer vision problems, where Deep Learning is the way to go, please do not use deep learning models from the start.
Typically, you start an ML project, you fit your first model, say a logistic regression, and you see the model performance is not good enough to close the project. You think you should try more complex models and neural networks (aka deep learning) are the best candidates. After a bit of googling, you find a Keras/PyTorch code that seems appropriate for your data. You copy and paste it and try to train it with your data.
You will fail. Why? Neural networks are not plug-and-play solutions. They are the opposite of that. They have thousands/millions of parameters, and they are so flexible that they are a bit tricky to fit in your first shot. Eventually, if you spend a lot of time, you will make them work, but you will need to invest too much time.
There are plenty of out-of-the-box solutions, like the famous XGBoost models, that work like a charm for many problems, especially for tabular data. Try them before you get into the Deep Learning territory.
Conclusion
The job of a professional ML engineer is more complex than what you will learn in any online course.
I would love to help you become one, so if you want to learn more go subscribe to the datamachines newsletter or check out my blog.
Original. Reposted with permission.
Bio: Pau Labarta Bajo is a mathematician and data scientist with over 10 years of experience crunching numbers and models for different problems, including financial trading, mobile gaming, online shopping, and healthcare.
Related: | https://www.kdnuggets.com/2021/09/solve-machine-learning-problems-real-world.html | CC-MAIN-2022-21 | refinedweb | 2,126 | 64 |
!
So, what is currying? I guess it's one of those words you hear from Haskell programmers all the time (after monad, of course). Essentially, the definition of the term is pretty simple, so those readers who have already written on ML type languages or Haskell, or who knows what it means from elsewhere, feel free to skip this section.
Currying - is the technique of transforming a function that takes N arguments into one function, which takes a single argument and returns the function of the next argument, and it goes on and one until we return the last argument's function, which is going to represent the overall result. I think it helps if I show you examples:
int sum2(int lhs, int rhs) {
return lhs + rhs;
}
Here we have a binary addition function. And what if we want to turn it into single variable function? It's actually very simple:
auto curried_sum2(int lhs) {
return [=](int rhs) {
return sum2(lhs, rhs);
};
}
No, what did we do? We took a value based on a single argument called lambda that in turn takes the second argument and performs the addition itself. As the result, we can apply the curried function curried_sum2 to our arguments one by one :
curried_sum2
// output: 42
std::cout << sum2(40, 2) << std::endl;
std::cout << curried_sum2(40)(2) << std::endl;
And that's actually the whole point of currying operation. Of course, it's possible to do it with functions of any arity - it's going to work absolutely the same way. We will return a curried function of N-1 arguments every time we take the value from another argument:
auto sum3(int v1, int v2, int v3) {
return v1 + v2 + v3;
}
auto curried_sum3(int v1) {
return [=](int v2){
return [=](int v3){
return sum3(v1, v2, v3);
};
};
}
// output: 42
std::cout << sum3(38, 3, 1) << std::endl;
std::cout << curried_sum3(38)(3)(1) << std::endl;
Partial application - is a way of calling functions of N arguments when they take only a part of the arguments and return another function of the remaining arguments.
In this regard it should be noted that in languages like Haskell this process works automatically, behind a programmer's back. What we're trying to do here is to perform it explicitly, i.e. to call our sum3 function like this: sum3(38,3)(1) or maybe like this: sum3(38)(3,1). On top of that, if one function returns another function that has been curried, it can be also called using the list of the first function's arguments. Let's see the example:
sum3
sum3(38,3)(1)
sum3(38)(3,1)
int boo(int v1, int v2) {
return v1 + v2;
}
auto foo(int v1, int v2) {
return kari::curry(boo, v1 + v2);
}
// output: 42
std::cout << kari::curry(foo)(38,3,1) << std::endl;
std::cout << kari::curry(foo)(38,3)(1) << std::endl;
std::cout << kari::curry(foo)(38)(3,1) << std::endl;
We actually have got a little ahead of ourselves here, showing an example of kari.hpp usage, so yes, it does that.
Before we write something, it's necessary (or desirable) to understand what we want to have in the end. And we want to have an opportunity to curry and partially apply any function that can be called in C++. Which are:
Variadic functions can be curried by specifying an exact number of arguments we want to curry. Standard interaction with std::bind and its results are also desirable. And of course, we need an opportunity to apply multiple-variable functions and call nested functions so that it would seem like we've been working with one curried function.
And we must not forget about performance, too. We need to minimize computational costs of wrappers, transfer of arguments and their storage. It means we have to move instead of copying, store only what we really need, and return (with further removal) the data as fast as possible.
std::bind
Yes, and no. std::bind is undoubtedly a powerful and proven tool, and I don't intend to write its murderer or alternative. Yes, it can be used for currying and explicit partial application (with specifying exactly what arguments we're applying, and where, and how many). But it sure it not the most convenient approach, not to mention that it's not always applicable since we have to know the arity of function and write specific bindings depending on that. For example:
int foo(int v1, int v2, int v3, int v4) {
return v1 + v2 + v3 + v4;
}
// std::bind
auto c0 = std::bind(foo, _1, _2, _3, _4);
auto c1 = std::bind(c0, 15, _1, _2, _3);
auto c2 = std::bind(c1, 20, 2, _1);
auto rr = c2(5);
std::cout << rr << std::endl; // output: 42
// kari.hpp
auto c0 = kari::curry(foo);
auto c1 = c0(15);
auto c2 = c1(20, 2);
auto rr = c2(5);
std::cout << rr << std::endl; // output: 42
namespace kari {
template < typename F, typename... Args >
constexpr decltype(auto) curry(F&& f, Args&&... args) const;
template < typename F, typename... Args >
constexpr decltype(auto) curryV(F&& f, Args&&... args) const;
template < std::size_t N, typename F, typename... Args >
constexpr decltype(auto) curryN(F&& f, Args&&... args) const;
template < typename F >
struct is_curried;
template < typename F >
constexpr bool is_curried_v = is_curried<F>::value;
template < std::size_t N, typename F, typename... Args >
struct curry_t {
template < typename... As >
constexpr decltype(auto) operator()(As&&... as) const;
};
}
kari::curry(F&& f, Args&&... args)
Returns a function object of curry_t type (a curried function) with optional arguments args applied or with the result of application of the arguments to the given function f (is the function is nullary, or the arguments transferred were enough to call it).
curry_t
args
f
If f parameter contains the function that has already been curried, it returns its copy with the arguments args applied.
kari::curryV(F&& f, Args&&... args)
Allows to curry functions with variable number of arguments. After that these functions can be called using () operator with no arguments. For example:
()
auto c0 = kari::curryV(std::printf, "%d + %d = %d");
auto c1 = c0(37, 5);
auto c2 = c1(42);
c2(); // output: 37 + 5 = 42
If f parameter contains a function that has already been curried, it returns its copy with altered type of application for variable number of arguments with the arguments args applied.
kari::curryN(F&& f, Args&&... args)
Allows to curry functions with variable number of arguments by specifying an exact number N of arguments we want to apply (except those given in args). For example:
N
char buffer[256] = {'\0'};
auto c = kari::curryN<3>(std::snprintf, buffer, 256, "%d + %d = %d");
c(37, 5, 42);
std::cout << buffer << std::endl; // output: 37 + 5 = 42
If f parameter contains a function that has already been curried, it returns its copy with altered type of application for N arguments with the arguments args applied.
kari::is_curried<F>, kari::is_curried_v<F>
Some auxiliary structures for checking if a function has already been curried. For example:
const auto l = [](int v1, int v2){
return v1 + v2;
};
const auto c = curry(l);
// output: is `l` curried? no
std::cout
<< "is `l` curried? "
<< (is_curried<decltype(l)>::value ? "yes" : "no")
<< std::endl;
// output: is `c` curried? yes
std::cout
<< "is `c` curried? "
<< (is_curried_v<decltype(c)> ? "yes" : "no")
<< std::endl;
kari::curry_t::operator()(As&&... as)
The operator allowing a full or partial application of a curried function. Returns the curried function of remaining arguments of the initial function F, or value of this function obtained by its application on the backlog of old arguments and new arguments as. For example:
F
as
int foo(int v1, int v2, int v3, int v4) {
return v1 + v2 + v3 + v4;
}
auto c0 = kari::curry(foo);
auto c1 = c0(15, 20); // partial application
auto rr = c1(2, 5); // function call - foo(15,20,2,5)
std::cout << rr << std::endl; // output: 42
If you call a curried function with no arguments using curryV or curryN, it will be called if there are enough arguments. Otherwise, it will return a partially applied function. For example:
curryV
curryN
auto c0 = kari::curryV(std::printf, "%d + %d = %d");
auto c1 = c0(37, 5);
auto c2 = c1(42);
// force call variadic function std::printf
c2(); // output: 37 + 5 = 42
When giving you details of implementation, I'm going to use C++17 in order to keep the text of the article short and avoid unnecessary explanations and piled SFINAE, as well as examples of implementations I had to add within the C++14 standard. All these you can find in the project repository, where you can also add it to your favourites :)
make_curry(F&& f, std::tuple<Args...>&& args)
An auxiliary function that creates a function object curry_t or applies the given function f to the arguments args.
template < std::size_t N, typename F, typename... Args >
constexpr auto make_curry(F&& f, std::tuple<Args...>&& args) {
if constexpr ( N == 0 && std::is_invocable_v<F, Args...> ) {
return std::apply(std::forward<F>(f), std::move(args));
} else {
return curry_t<
N,
std::decay_t<F>,
Args...
>(std::forward<F>(f), std::move(args));
}
}
template < std::size_t N, typename F >
constexpr decltype(auto) make_curry(F&& f) {
return make_curry<N>(std::forward<F>(f), std::make_tuple());
}
Now, there are two interesting things about this function:
struct curry_t
The function object supposed to store the backlog of arguments and the function we will call when applying it in the end. This object is what we're going to call and apply partially.
template < std::size_t N, typename F, typename... Args >
struct curry_t {
template < typename U >
constexpr curry_t(U&& u, std::tuple<Args...>&& args)
: f_(std::forward<U>(u))
, args_(std::move(args)) {}
private:
F f_;
std::tuple<Args...> args_;
};
There's a number of reasons why we store the backlog of arguments args_ in std::tuple:
args_
1) situations with std::ref are handled automatically to store references when we need to, by default based on the value 2) convenient application of a function according to its arguments (std::apply) 3) it's readymade, so you don't have to write it from scratch :)
We have store the object we call and the function f_ by its value, too, and be careful when choosing the type when creating one (I'm going to expand on this issue below), or moving, or copying it using universal reference in the constructor.
f_
A template parameter N acts as an application counter for variadic functions.
curry_t::operator()(const As&...)
And, of course, the thing that makes it all work - the operator which calls the function object.
template < std::size_t N, typename F, typename... Args >
struct curry_t {
// 1
constexpr decltype(auto) operator()() && {
return detail::make_curry<0>(
std::move(f_),
std::move(args_));
}
// 2
template < typename A >
constexpr decltype(auto) operator()(A&& a) && {
return detail::make_curry<(N > 0 ? N - 1 : 0)>(
std::move(f_),
std::tuple_cat(
std::move(args_),
std::make_tuple(std::forward<A>(a))));
}
// 3
template < typename A, typename... As >
constexpr decltype(auto) operator()(A&& a, As&&... as) && {
return std::move(*this)(std::forward<A>(a))(std::forward<As>(as)...);
}
// 4
template < typename... As >
constexpr decltype(auto) operator()(As&&... as) const & {
auto self_copy = *this;
return std::move(self_copy)(std::forward<As>(as)...);
}
}
The calling operator has four functions overloaded.
A function with no parameters allowing to start applying the variadic function (created by curryV or curryN). Here we decrement the application counter down to zero, making it clear that the function is ready to be applied, and then we give everything that's required for that to make_curry function.
make_curry
A function of a single argument that decrements the application counter by 1 (if it's not at zero) and puts our new argument a in the backlog of arguments args_ and transfers all this to make_curry.
a
A variadic function that is actually a trick for partial application of various arguments. What it does is applies them recursively, one by one. Now, there are two reasons why they can't be applied all in once:
The last function acts as a bridge between calling curry_t using lvalue and calling functions using rvalue.
The tags of ref-qualified functions make the whole process almost magical. To put it short, with their help we get to know that an object was called using rvalue reference and we can just move the arguments instead of copying them in the end calling function make_curry. Otherwise we'd have to copy the arguments in order to still have an opportunity to call this function again, making sure the arguments are still there.
Before proceeding to the conclusion, I would like to show you a couple of examples of the syntactic sugar they have in kari.hpp which can be qualified as bonuses.
The programmers who've already worked with Haskell should be familiar with operator sections allowing to give a short description of the operators applied. For instance, structure (*2), generates a single-argument function, returning the result of multiplication of this argument by 2. So, what I wanted was to try writing something like that in C++. No sooner said than done!
(*2)
using namespace kari::underscore;
std::vector<int> v{1,2,3,4,5};
std::accumulate(v.begin(), v.end(), 0, _+_); // result: 15
std::transform(v.begin(), v.end(), v.begin(), _*2); // v = 2, 3, 6, 8, 10
std::transform(v.begin(), v.end(), v.begin(), -_); // v = -2,-3,-6,-8,-10
And of course I wouldn't be a complete wacko if I haven't tried to write a function composition. As the composition operator I chose operator * as the closest (by the look of it) of all symbols available to the composition sign in maths. I used it to apply the resulting function for an argument, too. So, that's what I got:
operator *
using namespace kari::underscore;
// 1
std::cout << (_*2) * (_+2) * 4 << std::endl; // output: 12
// 2
std::cout << 4 * (_*2) * (_+2) << std::endl; // output: 10
(+2)
4
(4 + 2) * 2 = 12
(4 * 2 + 2) = 10
The same way you can build quite complex compositions in pointfree style, but bear in mind only Haskell programmers will understand these :)
// (. (+2)) (*2) $ 10 == 24 // haskell analog
std::cout << (_*(_+2))(_*2) * 10 << std::endl; // output: 24
// ((+2) .) (*2) $ 10 == 22 // haskell analog
std::cout << ((_+2)*_)(_*2) * 10 << std::endl; // output: 22
I think it was pretty clear before that there's no need to use these techniques in real projects. But still, I must mention that. After all, my goal was to prove myself and check new C++ standard. Would I be able to do this? And would C++? Well, I guess, you just saw like we both have kind of done that. And I'm really grateful to all guys who read the whole. | https://www.codeproject.com/Articles/1274678/Currying-and-partial-application-in-Cplusplus14?msg=5588058 | CC-MAIN-2019-18 | refinedweb | 2,487 | 52.09 |
DESCRIPTION
To properly handle syntax highlighting, vi and viw use syntax configuration files that describe how the syntax for a given programming, scripting, or mark-up language should be highlighted. While several syntax configuration files are included with MKS Toolkit, you can also create new configuration files to handle additional languages.
These configuration files must have a .viw extension. When the vi option variable syntaxlanguage is set to DETECT, vi searches for the appropriate syntax configuration file to use. This file will be of the form ext.viw where ext is the file extension of the file being edited. vi first looks for this file in the $HOME/syntax directory and, if not found, in the $ROOTDIR/etc/syntax directory.
When you install MKS Toolkit, a number of syntax configuration files are installed in $ROOTDIR/etc/syntax. To determine which syntax configuration file should be used to highlight which file name. vi use syntax map files as described in the Syntax Map Files section.
General Structure
Syntax configuration files are flat text files. They contain five types of lines:
Lines that start with the # character.
Blank lines.
Lines that start with the syntaxGroup statement.
Lines that start with the hilightGroup statement.
Lines the specify the value of a boolean flag.
A line beginning with # is a comment lines and is ignored by vi. Blank lines are also ignored.
A line beginning with syntaxGroup defines a syntax group and specifies which commands, key words, strings, and blocks are assigned to that group. For instance, in a syntax configuration file for the C programming language, the key words if and while might be assigned to a syntax group named cConditional while the keywords int and char might be assigned to one named cDatatype. Similarly, a string beginning with // might be assigned to lineComment, a block that starts with /* and ends with */ might be assigned to blockComment, and some strings beginning with # (such as #include) might be assigned to cPreProcessor.
A line beginning with hilightGroup defines a mapping of syntax groups to a highlight group. The highlight group defines color is used to displayed members of the mapped syntax group. Continuing with the C language example, the cConditional, cDatatype, and cPreprocessor syntax groups might be mapped to the Keyword highlight group, while the lineComment and blockComment syntax groups might be mapped to the Comment highlight group.
Lines that specify the value of a boolean flag can change the behavior of the pattern matching used by the syntaxGroup statements.
syntaxGroup Statement
A syntaxGroup statement has one of the following formats:
syntaxGroup syntax_group_name keyword_list syntaxGroup syntax_group_name startStr="start_string" endStr="end_string" syntaxGroup syntax_group_name startStr="start_string" endStr="EOLPAT" syntaxGroup syntax_group_name startStr="start_string" keyword_list
The individual elements of these formats are defined as follows:
syntax_group_name is an alphanumeric string that describes the syntax group. This string can be a maximum of 31 characters in length.
- Note:
For the purposes of this reference page, an alphanumeric string must begin with a letter and can only contain letters, digits, and the underscore character (_).
keyword_list is a list of one or more alphanumeric language keywords separated by spaces. Each keyword will be highlighted with the same color as determined by an appropriate hilightGroup statement. keyword_list can be a maximum of 4097 characters in length. It is not necessary for keyword_list to contain all keywords that you want to assign to a given syntax group. You can specify additional keywords by using another syntaxGroup statement with the same syntax_group_name.
startStr="start_string" and endStr="end_string" specify the start and end of a block of characters, The block begins with start_string and ends with end_string and will be highlighted with the color determined by the appropriate hilightGroup statement. start_string and end_string each have a maximum length of 31 characters.
When endStr="EOLPAT", the block of characters ends when end-of-line (EOL) is encountered.
startStr="start_string" in conjunction with keyword_list defines a list of keywords that have special significance when preceded by start_string. All keywords starting with the same start_string must be specified with a single statement of this type. start_string and keyword_list can be a maximum of 31 characters and 4097 characters, respectively.
hilightGroup Statement
The hilightGroup statement has the following format:
hilightGroup highlight_group_name syntax_group_name_list
The individual elements formats are defined as follows:
highlight_group_name is one of the pre-determined list of highlight groups supported by vi:
Conditional or Cond Keyword or Key PreProcessor or Preproc Comment Datatype or Data Operator or Oper Constant or Const Function or Func Structure or Struct Expression or Expr
This name is case-insensitive. By default, each highlight group is displayed by vi using a particular color. The color used to display a particular group may be changed by using the appropriate vi option variable. See the Set Option Variables section of the vi reference page for more details.
syntax_group_name_list is a list of one or more syntax_group_names, as specified in a previous syntaxGroup statement, and separated by spaces.
Boolean Flags
The format for setting a boolean flag is:
boolean_flag=value
where boolean_flag is the name of the flag to be set and value is either 0 or 1.
The following boolean flags are currently supported:
- match_case
When set to 1, syntax patterns are case sensitive. When set to 0, they are case insensitive. By default, syntax patterns are case insensitive.
- highlight_inside_quotes
When set to 1, syntax highlighting occurs inside of double quotes. When set to 0, double quotes do not allow highlighting inside of them. By default, syntax highlighting does not occur within double quotes.
- backslash_continues_strings
When set to 1, syntax highlighting works like the C language where multiline string constants must be continued by appending a \ at the end of the line. When set to 0, it works like shell scripts where strings continue without \. For example:
echo "starting and continuing"
By default, syntax highlighting works like C.
Example
The following is an excerpt from the c.viw provided with MKS Toolkit:
# Comments syntaxGroup cComment1 startStr="/*" endStr="*/" syntaxGroup cComment2 startStr="//" endStr="EOLPAT" # Preprocessor keywords start with # syntaxGroup cPreProc1 startStr="#" if ifdef endif else elif define undef ifndef # Keywords used in conditional or iterative statements syntaxGroup cCond break case continue do else if switch while # Keywords for datatypes syntaxGroup cType1 bool char class double enum float int long short syntaxGroup cType2 signed struct typedef union unsigned void wchar_t # Known Constants syntaxGroup cConst NULL TRUE FALSE # Keywords or strings used for operators. syntaxGroup cplusOper1 and and_eq bitand bitor const_cast dynamic_cast syntaxGroup cplusOper2 not not_eq operator or or_eq xor xor_eq syntaxGroup cplusOper3 sizeof static_cast reinterpret_cast syntaxGroup cOtherKey1 asm auto catch delete explicit syntaxGroup cOtherKey1 export extern false friend goto inline mutable syntaxGroup cOtherKey2 namespace new private protected public pure syntaxGroup cOtherKey2 register return static template syntaxGroup cOtherKey3 this throw true try typeid typename using syntaxGroup cOtherKey3 virtual volatile const # Map syntax groups to hilight groups. hilightGroup Conditional cCond hilightGroup Keyword cOtherKey1 cOtherKey2 cOtherKey3 hilightGroup PreProc cPreProc1 cPreProc2 hilightGroup Comment cComment1 cComment2 hilightGroup Type cType1 cType2 hilightGroup Operator cplusOper1 cplusOper2 cplusOper3 hilightGroup Const cConst
Syntax Map Files
As mentioned earlier, vi uses syntax map files to associate extensions and file names with syntax configuration files. The provided $ROOTDIR/etc/syntax/syntax.map file includes mappings for several common extensions and file names:
File or Extension File .c, .h, .cc, .cpp, .hpp c.viw .i asm.viw .bat, .cmd bat.viw .jav, .java java.viw .htm, .html, .sgm, .sgml, .xml html.viw .jj, .jjt javacc.viw .csh csh.viw .sh, .ksh sh.viw .pl perl.viw .php php.viw .mk make.viw makefile make.viw .profile sh.viw
If you change or replace any of the listed files or place a file of the same name in your $HOME/syntax directory, that file is used instead.
You can override the associations given in the $ROOTDIR/etc/syntax/syntax.map file by creating a $HOME/syntax/syntax.map file. This file consists of a list of regular expressions and associated syntax configuration files. Each entry consists of a regular expression followed by white space and the name of the associated syntax configuration file. For example, a $HOME/syntax/syntax.map map containing:
.*[.]cpp cpp.viw .*[.]tst test.viw
indicates that syntax highlighting for files with a .cpp extension should use cpp.viw instead of the normal c.viw. Similarly, it adds a new association for files with a .tst extension. These files will use the test.viw syntax file to determine syntax highlighting.. | https://www.mkssoftware.com/docs/man4/vi.4.asp | CC-MAIN-2018-13 | refinedweb | 1,403 | 52.7 |
Implementation status: implemented
Synopsis
#include <stdlib.h>
void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int (*compar)(const void *, const void *));
Description
The function searches an ascending order array (with binary search) for an element with specified value.
Arguments:
key - a value to be found,
base - a pointer to the beginning of array area to be searched,
nitems - the number of array elements,
size - the number of bytes taken by each element,
compar - the comparison function.
Function searches an array of nitems objects, the initial member of which is pointed to by base, for a member that matches the object pointed to by key. The size (in bytes). It should return an integer which is less than, equal to, or greater than zero if the key object is found, respectively, to be less than, to match, or be greater than the array member.
Return value
The function returns a pointer to a matching member of the array, or a null pointer if no match is found.
If two members compare as equal, which member is matched is unspecified.
Errors
No errors are defined. | https://phoenix-rtos.com/documentation/libphoenix/posix/bsearch | CC-MAIN-2020-29 | refinedweb | 187 | 59.23 |
On Wed, 2008-04-30 at 13:36 +0100, David Woodhouse wrote: > Smells like libtinfo isn't built with -fPIC? Hm, don't think it's that. But 'stdscr' is a variable, and the configure test seems to be attempting to call it as if it's a function. This is probably not a good thing to be doing. This is a quick hack to fix it, but you should probably be including ncurses.h to pick up the appropriate declaration of stdscr -- it's different according to how ncurses was built. --- clex-3.18/configure~ 2008-04-01 14:06:50.000000000 +0100 +++ clex-3.18/configure 2008-04-30 14:11:02.000000000 +0100 @@ -3339,11 +3339,11 @@ cat >>conftest.$ac_ext <<_ACEOF #ifdef __cplusplus extern "C" #endif -char stdscr (); +extern int stdscr; int main () { -return stdscr (); +return stdscr; ; return 0; } -- dwmw2 | http://www.redhat.com/archives/fedora-devel-list/2008-April/msg02390.html | CC-MAIN-2014-42 | refinedweb | 143 | 69.28 |
getsockname - get socket name
#include <sys/socket.h>
int getsockname(int s , struct sockaddr * name , socklen_t * namelen )
Getsockname returns the current name for the specified socket. The
namelen parameter should be initialized to indicate the amount of space
pointed to by name. On return it contains the actual size of the name
returned (in bytes).
On success, zero is returned. On error, -1 is returned, and errno is
set appropriately.
EBADF The argument s is not a valid descriptor.
ENOTSOCK [Toc] [Back]
The argument s is a file, not a socket.
ENOBUFS [Toc] [Back]
Insufficient resources were available in the system to perform
the operation.
EFAULT The name parameter points to memory not in a valid part of the
process address space.
SVr4, 4.4BSD (the getsockname function call appeared in 4.2BSD). SVr4
documents additional ENOMEM and ENOSR error codes.
The).
bind(2), socket(2)
BSD Man Page 1993-07-24 GETSOCKNAME(2) | https://nixdoc.net/man-pages/Linux/man2/getsockname.2.html | CC-MAIN-2020-29 | refinedweb | 154 | 60.21 |
The Maybe data type
There are only two hard things in Computer Science:
null and
undefined.
Well, Phil Karlton didn’t say exactly those words, but we can all agree that dealing with
null,
undefined, and the concept of emptiness in general is hard, right?
The absence of a value
Every time we annotate a variable with a Type, that variable can hold either a value of the annotated Type,
null, or
undefined (and sometimes even
NaN!).
That means, to avoid errors like
Cannot read property 'XYZ' of undefined, we must remember to consistently apply defensive programming techniques every time we use it.
Another tricky aspect of the above fact is that semantically, it’s very confusing what
null and
undefined should be used for. They can mean different things for different people. APIs also use them inconsistently.
What can go wrong?
Even if you apply defensive programming techniques, things can go wrong. There are all sort of ways in which you could end up with false negatives.
In this example, the number
0 will never be found because
0 is falsy, like
undefined. The
Array.find() result when the find operation doesn’t match anything.
const numToFind = 0; const theNum = [0, 1, 2, 3].find(n => n === numToFind); if (theNum) { console.log(`${theNum} was found`); } else { console.log(`${theNum} was not found`); }
Sadly, defensive programming (aka
undefined /
null checks behind
if statements) are also a common source of bugs.
Maybe to the rescue
Wouldn’t it be nice if we could consistently handle emptiness, with the help of the compiler and without false negatives?
There’s already something that does all that: it’s the
Maybe data type (also known as
Option).
Maybe encapsulates the idea of a value that might not be there.
A
Maybe value can either be
Just some value or
Nothing.
type Maybe<T> = Just<T> | Nothing;
We often talk about this kind of Types as Container Types, because their only purpose is to give semantic meaning to the value they hold and to allow you to perform specific operations on it in a safe way.
We are going to use the ts.data.maybe Library. Let’s get familiar with its API.
Our app has a
User Type:
interface User { id: number; nickname: string; email: string; bio: string; dob: string; }
We also make a
/users request to our REST API, which returns the following payload:
[ (...) { "id": 1234, "nickname": "picklerick", "email": "[email protected]", "bio": null } (...) ]
At this point, if we annotate this payload with
User[], lots of bad things can happen in our codebase because
User is lying. We are expecting
bio and
dob to always be a
string, but in this case, one is
null and the other is
undefined.
There’s a potential for runtime errors.
Type annotations with
Maybe
Let’s fix this with
Maybe.
import { Maybe } from "ts.data.maybe"; interface User { id: number; nickname: string; email: string; bio: Maybe<string>; dob: Maybe<Date>; }
Once you add
Maybe to the equation, nothing is implicit anymore. There’s no way to get around that Type declaration — the compiler will always force you to treat
bio and
dob as
Maybe.
Creating
Maybe instances
Ok, but how do we use this?
Let’s create a
User parser for our API result.
For this, we’ll create a
UserJson Type, used only by the parser, that represents what we are getting from the server and another
User Type that represents our domain model. We’ll use this Type throughout the application.
import { Maybe, just, nothing } from 'ts.data.maybe'; interface User { id: number; nickname: string; email: string; bio: Maybe<string>; dob: Maybe<Date>; } interface UserJson { id: number; nickname: string; email: string; bio?: string | null; dob?: string | null; } const userParser = (json: UserJson): User => ({ id: json.id, nickname: json.nickname, email: json.email, bio: json.bio === null || json.bio === undefined ? nothing() : just(json.bio), dob: json.dob === null || json.dob === undefined || json.dob === '' ? nothing() : just(new Date(json.dob)) });
As you can see, to create a
Maybe instance, you have to use one of the available constructor functions:
–
just<T>(value: T): Maybe<T>
–
nothing<T>(): Maybe<T>
Notice how we’ve decided to define emptiness differently for
bio and
dob (date of birth).
We can represent
bio with an empty string — there’s nothing wrong with that.
However, we cannot represent a
Date with an empty string. That’s why the parser treats them differently, even though the data that comes from the server is a
string for both.
Extracting values from
Maybe
Now that we’ve managed to declare and create
Maybe instances, let’s see how we can use them in our logic.
We plan to create an html representation of the list of users that we are getting from the server, and we are going to represent them with cards.
This is the function that we’ll use to generate the Html markup for the card:
const userCard = (user: User) => `<div class="card"> <h2>${user.nickname}</h2> <p>${userBio(user.bio)}</p> <ul> <li>${user.email}</li> <li>${userDob(user.dob)}</li> </ul> </div>`;
Nothing special so far, but let’s see what those two functions that extract the values from
Maybe look like:
userBio()
const userBio = (maybeBio: Maybe<string>) => withDefault(maybeBio, '404 bio not found');
Here, we have introduced a new
Maybe API: the
withDefault() function (also known as
getOrElse() in other
Maybe implementations).
withDefault<A>(value: Maybe<A>, defaultValue: A): A
This function is used to extract the value from a
Maybe instance.
If the
Maybe instance is
Nothing, then the default value will be returned — in this case,
404 bio not found. If the instance is a
Just, it will unwrap and return the string value it contains.
i.e.
withDefault(just(5), 0) would return
5.
withDefault(nothing(), 'This is empty') would return
This is empty.
userDob()
const userDob = (maybeDate: Maybe<Date>) => caseOf( { Nothing: () => 'Date not provided', Just: date => date.toLocaleDateString() }, maybeDate );
Here, we are introducing another new
MaybeAPI: the
caseOf() function.
caseOf<A, B>(caseof: {Just: (v: A) => B; Nothing: () => B;}, value: Maybe<A>): B
In the
userDob function, we don’t want to use
withDefault because we need to perform some logic with the extracted value before returning it, and that’s precisely what the
caseOf() function is useful for.
This function gives you an opportunity to make computations before returning the value.
Maybe-fying existing APIs
There’s one last thing that needs to be done to complete our application: we need to render our user cards.
The rendering logic involves dealing with DOM APIs, we need to get a reference to the
div element where we want to insert our Html markup, and we’ll use the
getElementById(elementId: string): null | HTMLElement function.
In our newly acquired obsession to avoid
null and
undefined, we’ve decided to create a Maybefied version of this function to avoid dealing with
null.
const maybeGetElementById = (id: string): Maybe<HTMLElement> => { const elem = document.getElementById(id); return elem === null ? nothing() : just(elem); };
Now the compiler won’t let us treat the result like it’s an
HTMLElement, when in reality it could entirely be
null if the
div we are looking for is not in our page.
Maybe has us covered.
Let’s use this function and render those user cards:
const maybeAppDiv: Maybe<HTMLElement> = maybeGetElementById('app'); caseOf( { Just: appDiv => { appDiv.innerHTML = '<h1>Users</h1>' + usersJson .map(userJson => userCard(userParser(userJson))) .join('<br>'); return; }, Nothing: () => { document.body.innerHTML = 'App div not found'; return; } }, maybeAppDiv );
You can play with the code of this example here.
We’ve seen just a few of the available
Maybe APIs. You can do much more with this data type.
Go check the ts.data.maybe docs page to find out more.
The
Either data type
Errors are an essential part of software development, ignore them and your program will fail to meet the user’s expectations.
Defining failure
As always, semantics are fundamental, and defining failure consistently is vital to making our programs easier to reason about.
So, what exactly defines failure? Let’s see some examples of the kind of errors you can find around:
- An operation that throws a runtime exception.
- An operation that returns an
Errorinstance.
- An operation that returns
null.
- An operation that returns an object with
{error: true}in it.
- When we reach the
catch()clause in a
Promise
Most of the time, you’ll handle errors by branching your logic with
if and
try catch statements.
The resulting code can get messy quite rapidly because of the depth of nesting and intermediate variables that need to be defined to transport the final result from one point of your code to another.
Either to the rescue
Wouldn’t it be nice if we could abstract all those
if and
try catch statements and reduce the number of intermediate variables that need to be defined?
There’s already something that does all that: it’s the
Either data Type (also known as
Result).
Either encapsulates the idea of a computation that may fail.
An
Either value can either be
Right of some value or
Left of some error.
type Either<T> = Right<T> | Left;
Looks familiar, right? It’s very similar to the
Maybe type signature, although you’ll see how they differ in a moment.
We are going to use the ts.data.either Library. Let’s get familiar with its API.
The
Either candidates
This time we are going to create a
getUserById service that searches a user by id from a json file.
The service does the following:
1. Validates that the Json file name is valid.
2. Reads the Json file.
3. Parses the Json into an object Graph.
4. Finds the user in the array.
5. Returns.
As you can see, every step has the potential for failure. That’s fine because we are going to use
Either to keep errors under control.
Some utils for our example
Let’s create a few things our example relies on to work.
First, we are going to reuse the
UserJson Type from the previous example:
export interface UserJson { id: number; nickname: string; email: string; bio?: string | null; dob?: string | null; }
We also need a (virtual) file system.
const fileSystem: { [key: string]: string } = { "something.json": ` [ { "id": 1, "nickname": "rick", "email": "[email protected]", "bio": "Rick Sanchez of Earth Dimension C-137", "dob": "3139-03-04T23:00:00.000Z" }, { "id": 2, "nickname": "morty", "email": "[email protected]", "bio": null, "dob": "2005-04-08T22:00:00.000Z" } ]` };
We need a
readFile(filename: string): string; function for our virtual file system that returns the file contents as a string if the file is found or throws an exception otherwise.
const readFile = (filename: string): string => { const fileContents = fileSystem[filename]; if (fileContents === undefined) { throw new Error(`${filename} does not exists.`); } return fileContents; };
Finally, a (quick and dirty)
pipeline function implementation, which will allow us to make our function calls flow similar to how fluent APIs do:
There are some libraries out there that do the same in a Typesafe way, but I didn’t want to include yet another dependency.
And there’s already a native JavaScript pipeline API implementation in the works!
export const pipeline = (initialValue: any, ...fns: Function[]) => fns.reduce((acc, fn) => fn(acc), initialValue);
So, instead of calling multiple functions like this:
add1( add1( add1( 5 ) ) ); // 8
We can make it like this:
pipeline( 5, n => add1(n), // we could go point-free and just use `add1` n => add1(n), n => add1(n) ); // 8
Either composition
Our
getUserById function is, in fact, a sequence of actions where the next depends on the outcome of the previous.
Each step does something that may fail and passes the result to the next one, and because of that, the best way to represent each of these steps is with functions returning
Either.
1. Validating the Json filename
const validateJsonFilename = (filename: string): Either<string> => filename.endsWith(".json") ? right(filename) : left(new Error(`${filename} is not a valid json file.`));
Here we introduce the
Left and
Right constructor functions:
left(error: Error): Either;
right(value: T): Either;
The logic is quite straightforward (and naive): If the file doesn’t have
.json extension, we return a
Left, which means there was an error, otherwise a
Right with the filename.
2. Reading the Json file
const readFileContent = (filename: string): Either<string> => tryCatch(() => readFile(filename), err => err);
As we saw previously, the
readFile function throws an exception if the file is not found.
To control runtime errors
Either has the
tryCatch function:
tryCatch<A>(f: () => A, onError: (e: Error) => Error): Either<A>
This function wraps logic that may throw and returns an
Either instance.
tryCatch accepts two function parameters, one that is executed on success and another on failure.
On success, the result is returned wrapped in a
Right, on failure the error generated from the source function is passed to the error handler and the result is returned wrapped in a
Left.
3. Parsing Json
const parseJson = (json: string): Either<UserJson[]> => tryCatch( () => JSON.parse(json), err => new Error(`There was an error parsing this Json.`) );
Nothing new here, we use
tryCatch because
JSON.parse throws on failure.
4. Finding the user in the array
After all this error juggling it is time to search for the user, but let’s think about it, what happens if the provided
id doesn’t match any user, should we return
null,
undefined or maybe
Left? Oh! Remember
Maybe? Let’s use it here too!
const findUserById = (users: UserJson[]): Either<Maybe<UserJson>> => { return pipeline( users.find(user => user.id === id), (user: UserJson) => user === undefined ? nothing<UserJson>() : just(user), (user: Maybe<UserJson>) => right(user) ); };
Wow, look at that return.
Type signature Either<Maybe<UserJson>>
There’s so much stuff packed in so few characters… let’s recap:
–
Either -> contains a value or an error.
–
Maybe -> contains something or nothing.
–
UserJson -> contains a
UserJson.
So, just by reading the signature
findUserById(users: UserJson[]): Either<Maybe<UserJson>>;, you know for sure that
findUserById is part of an operation that might have failed (
Either) and returns a
UserJson that can be empty (
Nothing). Not a small feat!
5. Returning a value
At this point, we have all the ingredients needed to declare our
getUserById service. Let’s put it all together.
const getUserById = (filename: string, id: number): Either<Maybe<UserJson>> => { const validateJsonFilename = (filename: string): Either<string> => filename.endsWith(".json") ? right(filename) : left(new Error(`${filename} is not a valid json file.`)); const readFileContent = (filename: string): Either<string> => tryCatch(() => readFile(filename), err => err); const parseJson = (json: string): Either<UserJson[]> => tryCatch( () => JSON.parse(json), err => new Error(`There was an error parsing this Json.`) ); const findUserById = (users: UserJson[]): Either<Maybe<UserJson>> => { return pipeline( users.find(user => user.id === id), (user: UserJson) => user === undefined ? nothing<UserJson>() : just(user), (user: Maybe<UserJson>) => right(user) ); }; return pipeline( filename, (fname: string) => validateJsonFilename(fname), (fname: Either<string>) => andThen(readFileContent, fname), (json: Either<string>) => andThen(parseJson, json), (users: Either<UserJson[]>) => andThen(findUserById, users) ); };
The only thing this function adds to what we’ve done in the four previous steps is compose them all in a pipeline, where each operation feeds its resulting
Either to the next one thanks to this new
Either Api we just introduced, the
andThen function:
andThen<A, B>(f: (a: A) => Either<B>, value: Either<A>): Either<B>
This function basically says:
— Give me an
Either and I’ll return you another
Either using this function that returns
Either that you have to provide as well.
The way this function
pipeline flows is as follows:
1. Provide an initial value.
2. Execute this function, if it fails, return the error in a
Left, otherwise return the resulting value in a
Right.
3. If we got a
Left from the previous function return that
Left, otherwise execute this function, if it fails, return the error in a
Left, otherwise, return the resulting value in a
Right.
4. If we got a
Left from the previous function return that
Left, otherwise execute this function, if it fails, return the error in a
Left, otherwise, return the resulting value in a
Right.
5. If we got a
Left from the previous function return that
Left, otherwise execute this function, if it fails, return the error in a
Left, otherwise, return the resulting value in a
Right.
Did you notice that steps 3, 4 and 5 are the same? And that would be true for all intermediate operations that this pipeline might have. Once you get the idea, everything flows.
Using our
getUserById service
Our service returns a
UserJson buried two levels deep, one is an
Either and the other is a
Maybe. Let’s extract this valuable information from our container types.
The
printUser function extracts the
UserJson from the
Maybe.
const printUser = (maybeUser: Maybe<UserJson>) => maybeCaseOf( { Nothing: () => "User not found", Just: user => `${user.nickname}<${user.email}>` }, maybeUser );
Here,
maybeCaseOfis an alias becasue both
Eitherand
Maybehave a function called
caseOfthat we use in the same source file.
You can create an alias importing the function like this:
import { caseOf as maybeCaseOf } from "ts.data.maybe";
And finally! Let’s tie everything together:
console.log( caseOf( { Right: user => printUser(user), Left: err => `Error: ${err.message}` }, getUserById("something.json", 1) ) ); // rick<[email protected]> console.log( caseOf( { Right: user => printUser(user), Left: err => `Error: ${err.message}` }, getUserById("something.json", 444) ) ); // User not found console.log( caseOf( { Right: user => printUser(user), Left: err => `Error: ${err.message}` }, getUserById("nothing.json", 2) ) ); // Error: nothing.json does not exists. console.log( caseOf( { Right: user => printUser(user), Left: err => `Error: ${err.message}` }, getUserById("noExtension", 2) ) ); // Error: noExtension is not a valid json file.
You can play with the code of this example here.
We’ve seen just a few of the available
Either APIs, and you can do much more with this data type.
Go check the ts.data.either docs page to find out more.
Conclusion
We’ve learned that container Types are wrappers for values that provide APIs so we can safely operate with them.
The
Maybe container Type makes explicit the concept of emptiness, instead of relying on the inferior semantic and error-prone alternatives
null and
undefined we have this wrapper at our disposal that has a clearly defined API and semantic meaning.
The
Either container Type encapsulates the concept of failure and offers an alternative to the verbosity of branching our code in
if and
try catch statements.
The clearly-defined composable APIs exposed by this type infect our programs, making them more functional, clean and more comfortable to read and reason about. “Safer code with container types (Either and Maybe)”
hi, nice libs. however the map functions of Maybe doesn’t handle the case when the mapper returns null or undefined. so the safety is broken… am I wrong?
Hi Mark,
`null` and `undefined` are treated as `Nothing` values at run-time. At compile-time you’ll still get all the strict type checking though.
This decision was made because of the way JavaScript works. The other option was throwing a run-time exception, which was not ideal..
Take a look at this example:
Cheers! | https://blog.logrocket.com/safer-code-with-container-types-either-and-maybe/ | CC-MAIN-2022-21 | refinedweb | 3,187 | 56.25 |
Created on 2019-08-07 20:36 by Alexander.Pyhalov, last changed 2019-09-09 07:26 by vstinner.
We've moved illumos-gate wsdiff python tool from Python 2 to Python 3.
The tool does the following - for each file from old and new proto area compares file attributes to find differences in binary otput (spawning elfdump, dump and other utilities).
Performance has degraded in two times when commands.getstatusoutput() was replaced by subprocess.getstatusoutput().
os.popen() now is Popen() wrapper, so it also has poor performance.
Even naive popen() implementation using os.system() and os.mkstemp() behaved much more efficiently (about two times faster e.g. 20 minuts vs 40 minutes for single tool pass).
Have you tried switching to using Popen itself (or run, which keeps it to one layer of convenience wrapping)?
subprocess.getstatusoutput is three layers of wrapping (it calls check_output, which in turn calls run, which in turn calls Popen), and (unlike Python 2) has to decode all the output. run would avoid two layers of wrapping, can optionally receive the raw bytes instead of decoding to str, and avoids needing to wrap the whole thing in a shell (which system, older popen, and getstatusoutput all do).
Beyond that, it looks like when 3.8 releases, Popen should get *much* faster if the call meets certain conditions, see for details. If you can make your use cases conform to those requirements (e.g. by using shutil.which to determine the absolute paths to your utilities instead of relying on PATH lookup), the speed up should eliminate (or more than eliminate) the performance regression you're seeing (per #35537, on macOS, which got the least benefit, it was still a 1.7x improvement; on other OSes, the multiplier hits 61x or 106x).
I've tried to rewrite subporcess.getstatusoutput() usage with subprocess.Popen() and switch to shell=False, it didn't help, so I doubti it getstatusoutput() overhead, it's Popen() issue.
Can you post a simple script showcasing the performance degradation?
I couldn't reproduce entire test, as wsdiff script is rather large, but here's the simplified version. If Popen is used more often, difference is much more significant.
# Using workaround
$ python3.5 ~/tmp/1.py 1
10.780487537384033
# Without workaround
$ python3.5 ~/tmp/1.py
13.347045660018921
# Using python2.7
$ python2.7 ~/tmp/1.py
9.83385586739
Even if I use
import subprocess
process = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
universal_newlines=True)
return process.stdout.read()
difference in times are the same.
I don't seen any significant difference here (Ubuntu 18.04):
$ time python2 sp.py
10.3433089256
real 0m10,362s
user 0m6,565s
sys 0m4,372s
$ time python3 sp.py
11.746907234191895
real 0m11,781s
user 0m7,356s
sys 0m5,239s
This issue lacks a lot of information:
* What is your operating system (name and version)? On Linux, what is your Linux kernel version?
* Which Python version did you try?
* Which command are you running?
* Do you use a shell?
* Do you use bytes (default) or Unicode (universal_newlines=True or text=True)?
* Can you provide a minimum reproducer? I don't know how to use msg349894: cmd is not defined.
Attached 1.py uses 2 commands, appararently both use a shell:
* "find /usr/bin -type f 2>/dev/null"
* "objdump '%s'"
"objdump '%s'" is unsafe and can lead to shell injection: try to avoid the usage of a shell. Use subprocess.Popen directly, or an helper which doesn't use shell=True.
We have recently bumped into a similar problem. Using FreeBSD, subprocess calls were taking more than 10 times the usual time to execute after migrating to python3.6. After some digging, the default for 'close_fds' was changed to 'True'. On linux, this actually made things faster, but for unix, much slower. Passing 'close_fds=False' solved this for us.
I create bpo-38061 "FreeBSD: Optimize subprocess.Popen(close_fds=True) using closefrom()". | https://bugs.python.org/issue37790 | CC-MAIN-2019-47 | refinedweb | 657 | 68.87 |
Here’s something I had to get my head wrapped around when I started building Jamstack sites. There are these different stages your site goes through where you can put logic.
Let’s look at a special example so you can see what I mean. Say you’re making a website for a music venue. The most important part of the site is a list of events, some in the past and some upcoming. You want to make sure to label them as such or design that to be very clear. That is date-based logic. How do you do that? Where does that logic live?
There are at least four places to consider when it comes to Jamstack.
Option 1: Write it into the HTML ourselvesOption 1: Write it into the HTML ourselves
Literally sit down and write an HTML file that represents all of the events. We’d look at the date of the event, decide whether it’s in the past or the future, and write different content for either case. Commit and deploy that file.
<h1>Upcoming Event: Bill's Banjo Night</h1> <h1>Past Event: 70s Classics with Jill</h1>
This would totally work! But the downside is that weu’d have to update that HTML file all the time — once Bill’s Banjo Night is over, we have to open your code editor, change “Upcoming” to “Past” and re-upload the file.
Option 2: Write structured data and do logic at build timeOption 2: Write structured data and do logic at build time
Instead of writing all the HTML by hand, we create a Markdown file to represent each event. Important information like the date and title is in there as structured data. That’s just one option. The point is we have access to this data directly. It could be a headless CMS or something like that as well.
Then we set up a static site generator, like Eleventy, that reads all the Markdown files (or pulls the information down from your CMS) and builds them into HTML files. The neat thing is thatwe can run any logic we want during the build process. Do fancy math, hit APIs, run a spell-check… the sky is the limit.
For our music venue site, we might represent events as Markdown files like this:
--- title: Bill's Banjo Night date: 2020-09-02 --- The event description goes here!
Then, we run a little bit of logic during the build process by writing a template like this:
{% if event.date > now %} <h1>Upcoming Event: {{event.title}}</h1> {% else %} <h1>Past Event: {{event.title}}</h1> {% endif %}
Now, each time the build process runs, it looks at the date of the event, decides if it’s in the past or the future and produces different HTML based on that information. No more changing HTML by hand!
The problem with this approach is that the date comparison only happens one time, during the build process. The
now variable in the example above is going to refer to the date and time the build happens to run. And once we’ve uploaded the HTML files that build produced, those won’t change until we run the build again. This means that once an event at our music venue is over, we’d have to re-run the build to make sure the website reflects that.
Now, we could automate the rebuild so it happens once a day, or heck, even once an hour. That’s literally what the CSS-Tricks conferences site does via Zapier.
But this could rack up build minutes if you’re using a service like Netlify, and there might still be edge cases where someone gets an outdated version of the site.
Option 3: Do logic at the edgeOption 3: Do logic at the edge
Edge workers are a way of running code at the CDN level whenever a request comes in. They’re not widely available at the time of this writing but, once they are, we could write our date comparison like this:
// THIS DOES NOT WORK import eventsList from "./eventsList.json" function onRequest(request) { const now = new Date(); eventList.forEach(event => { if (event.date > now) { event.upcoming = true; } }) const props = { events: events, } request.respondWith(200, render(props), {}) }
The
render() function would take our processed list of events and turn it into HTML, perhaps by injecting it into a pre-rendered template. The big promise of edge workers is that they’re extremely fast, so we could run this logic server-side while still enjoying the performance benefits of a CDN.
And because the edge worker runs every time someone requests the website, we can be sure that they’re going to get an up-to-date version of it.
Option 4: Do logic at run timeOption 4: Do logic at run time
Finally, we could pass our structured data to the front end directly, for example, in the form of data attributes. Then we write JavaScript that’s going to do whatever logic we need on the user’s device and manipulates the DOM on the fly.
For our music venue site, we might write a template like this:
<h1 data-{{event.title}}</h1>
Then, we do our date comparison in JavaScript after the page is loaded:
function processEvents(){ const now = new Date() events.forEach(event => { const eventDate = new Date(event.getAttribute('data-date')) if (eventDate > now){ event.classList.add('upcoming') } else { event.classList.add('past') } }) }
The
now variable reflects the time on the user’s device, so we can be pretty sure the list of events will be up-to-date. Because we’re running this code on the user’s device, we could even get fancy and do things like adjust the way the date is displayed based on the user’s language or timezone.
And unlike the previous points in the lifecycle, run time lasts as long as the user has our website open. So, if we wanted to, we could run
processEvents() every few seconds and our list would stay perfectly up-to-date without having to refresh the page. This would probably be unnecessary for our music venue’s website, but if we wanted to display the events on a billboard outside the building, it might just come in handy.
Where will you put the logic?Where will you put the logic?
Although one of the core concepts of Jamstack is that we do as much work as we can at build time and serve static HTML, we still get to decide where to put logic.
Where will you put it?
It really depends on what you’re trying to do. Parts of your site that hardly ever change are totally fine to complete at edit time. When you find yourself changing a piece of information again and again, it’s probably a good time to move that into a CMS and pull it in at build time. Features that are time-sensitive (like the event examples we used here), or that rely on information about the user, probably need to happen further down the lifecycle at the edge or even at runtime.
You forgot the A in JAM. Your API endoint should be doing your logic. You Markup should load the app frame then the JavaScript should request upcoming and past events from the API, and the API should do the logic of determining what is past and what is upcoming and respond accordingly.
Touché
Option 4 is clean and hassle free but there is one problem with it.
It is timezone. Event might be happened already, but user sees it as it is about to happen.
Maybe there is a way to convert user and event time to utc or any standard, and then compare it for status.
You can deal with UTC dates and format that to local time zone after computation for display only. | https://css-tricks.com/where-does-logic-go-on-jamstack-sites/ | CC-MAIN-2022-05 | refinedweb | 1,320 | 79.6 |
Directory Listing.
error check for 3d support
added resuse so use can specify wether or not to use the current meshfile or to over write it the surface tagging was providing some issues commented out for now
Do not ignore gmshGeo2Msh return value
Make tests write to the correct directories
Fixing some unit test failures on osx
Fixing more tests to check for the optional natgrid package
Try a version number debtools accept. Updated subst files. Still missing trusty
Bump version to allow experiments to not clash
First steps towards python3 packages. Problems still to be resolved: doesn't remove cleanly (esys/__init__.pyc is created) Need to test interactions between the new packages and the old
template is not executable......
fixed error which I did not know about
replacing a sleep with an MPIbarrier because it's much, much faster in block testing
added a flush and delay to fix race conditions hiding testing summaries from rank zero
Doesn't work yet but getting some subworld changes in.
adding.
python 3 print
non exponential mapping
adding options to record time and cycle number in silo and VTK files.
well, this was embarrassing...
Tweaks to the forward model tests and finally silenced all but rank 0 for unit test output. I don't think this will hide useful info as all ranks should output the same thing by the TextTestRunner...
commented out prints
added changes for polepole models
array of mu's should be float even if someone does [1,2]..
minor comment fix for ripley
Adding speckley (high-order) domain family, doesn't yet support MPI, Reduced functionspaces, or PDEs using A, B and/or C..
We were setting --cpus-per-rank without a --bind... option under OpenMPI but the latter is required according to doco. This, in combination with setting OMP_PROC_BIND=true, caused all ranks to run on the same core when running without hostfile (e.g. on guineapig) so the runtimes exploded. Added --bind-to-core to fix that issue.
Fixed another race with file deletion.
minor revisions
Fix recent mpi test failures by giving ranks>0 some time to check their output before deleting test files..
Making == and != on Data objects throw exceptions to warn people that they probably don't do what they might think they do. Credit to Jaco and Cihan.
remember the good ol' days where no newline at end of files were frowned upon? Thanks to crayc++ they're back.
scons ends if tests fail again...
close the file after finishing reading to avoid segfault on centos.
Modify unit tests to read their classes from esys.escriptcore.utestselect Change the line in that file to switch between unittest and unittest2
gcc 4.9: error: type qualifiers ignored on function return type [-Werror=ignored-qualifiers]
Wait a bit after running the mpi-enabled gmsh version to increase probability of success (yes it's a hack).
Fixes for Python3
This commit is brought to you by the number 4934 and the tool "meld". Merge of partially complete split world code from branch.
this is a fix for older versions of numpy where passing in an a list of ints causes the inver code to break.
a few constness fixes in abstract and pasowrap SystemMatrix.
a few non-invasive const fixes in AbstractSystemMatrix.
fixed a very bad doc string in abstract class.
Removed the remaining (2) bashism's in run-escript so bash is no longer required.
trying to make centos happy.
Fixes #253 (unused var in weipa)
instructions for FreeBSD 10.0
export LD_PRELOAD for tests. added freebsd 10.0 options file.
updating deb changelog
Fixes for macports
removing spare 'as'
Reorder homebrew install
update to comments and fixing of docstring
fix unused var
fix docstring error
Fixed Wunused-functions picked up by g++ 4.9
removing runmodel from /bin given it doesn't have x-permissions
fix docstring indentation isssue for accousticwaveform
restoring lost changes
updated install doc
removing test print
updates for centos 6.5 install instructions
add centos 6.5 scons option file.
Updated info about macos commandline tools to note existance of xcodebuild command.
update sympy version check
sympy version check
sympy version check
sympy version check
Added missing backslash Corrected spelling mistake
affected tests now skipped if pyproj not installed
adding options for fedora 20, only changes boost_python-mt for now
typo
scaled down grav_netcdf test...
some changes to user guide.
added suggestion to copy options file from os directory.
Updated warning message when no options file is provided
Removing manual pagebreaks
Minor updates
rewording and checking
Small changes
this file is added so that we can import Symbolic by doing: import esys.escript.symbolic as symb instead of import esys.escriptcore.symbolic as symb the one line containined in the file is on line five for reasons prettiness
Updated changes list and sorted dev lists
fixing small errors
grammar, spelling and formating changes.
added sympy to bib and making small grammar, spelling and style changes.
symbolic part of user guide nearly complete
adding figures for symbolic part of user guide.
new intel cc,mkl & mpi on savanna.
fixing package requirements for ubuntu trusty packages
Updated changelog
fixed ripley dirac test for multiple ranks and added protections against MPI causing problems due to premature exits by some ranks
whitespace only changes.
adding dirac point interpolation tests for ripley, all ranks will be used in subdividing each axis in turn
changed symconsts to symconsts to fit the rest of escript
Q: ...so what does this papi flag do? A: darn, you got me. [now it prints errors with the papi version shipped with debian, hooray]
all of paso now lives in its own namespace.
don't report an error when there isn't one.....
paso: starting to polish
Remove reference to epydoc documentation from doxygen (since our debian doc package uses sphinx).
bringing doxygen reported version number up to date
fixing mkl build.
cleansing
removing leftover debug prints
added exception for domain sizes that cause integer overflows
wrapping resize exceptions for overly large domains (previous message to user was: 'RuntimeError: vector::_M_fill_insert')
Avoid division by zero
skipping multirank segywriter tests now that multirank writes throw exceptions
modified atoms code that when type is set to escript.Symbol, sympy.symbol get added to the type list. This is because escript.symbols are represented by sympy symbols in the _arr list
some mopping in paso
removing leftover python solveroptions
FWI is running
Added import division and changed a few / to //
paso util sweep
added exceptions to ripley for more informative deaths to negative element counts
adding exception for multi-rank segy write instead of failing to write correctly and reporting success
More vacuuming.
lots of future print_function
fixed awkard integer division in LinearMapping (py3 unaffected)
paso::Options.
I fink I broke it - now I thixed it.
Removing MPIInfo from pythonMPI
checkpointing paso::Preconditioner.
Removing variational problem as it will not be part of the release
keeping older compilers happy
scons options for trusty
Adding initial support for ubuntu trusty
Fixing non-mpi build.
added test for evalf
"Some" SystemMatrix clean up.....
removing unused MIS
Added Jaco
Adding missing names.
some incredibly long lines are now much, much nicer to read/wrap
fixing MKL compile.
Removed obsolete file, reverted verbosity of test and a bit more cleanup.
checkpointing some SparseMatrix cleanup.
fixed sillyness with serial builds reporting as MPI
SolverBuddy documentation changes from old python docstrings to doxygen format
now with all required files at no extra cost
allowing for larger amounts of variable tracking with debug=true (mostly for escriptcpp.cpp)
Pattern shared ptrs
SystemMatrixPattern shptr
Coupler/Connector shared ptrs.
paso::SharedComponents now header-only and shared ptr managed.
replacing awful config file debugthing
paso::Distribution instances are now managed by a boost::shared_ptr, methods are all inline.
moving away from shared pointers in domain components
Removed some obsolete checkPtr's. More to come...
Removed code duplication and moved IndexList to esysUtils header only. Renamed AML.cpp which is old,unused code.
added missing const.
put SparseMatrix into paso namespace, accompanied by minor code cleanup.
code cleanup of paso::SparseMatrix_MatrixVector and variants. Mostly a no-op.
adding symbolic to user guide, work in progress
changed 'dict_keys' object to list so that it can be indexed
make escriptcore/ visible
changed has_key to in for python 3
changing more awkward logic into more obvious (and correct, though i doubt a negative length ever happens) logic
fixed a broken numerical comparison
changed header guard definition to match header guard check
fixed silly naming issue
refactored linearPDE tests (removing repetition)
cleaned up and simplified run_seismic tests, including specific checking for obspy not being installed
added test for preservation of data substitutions
fixing a race condition in file tests
Temporarily adjusting magic numbers
python3ified tests using deprecated test methods ( #89 and #106 ), added run_seismic into downunder tests (with skips if obspy/segywriters fail to write)
replacing xrange with range for python3 compatibility, refs #106
Removed commented for loops
Major issues with subs and data objects have been rectified. subs was also not working properly for symbol to symbol substitutions this has been rectified.
allowed custom assemblers a value tolerance in tests (for case of 0 to 1 in objects, tolerance of 1e-8)
added ripley rectangle reading from compressed files, added unit tests for binaryGrid reads and writes (only single ranks for compressed thus far) (#104)
mapping test fixed
making inversioncostfunctions python3 compatible
adjusted InversionCostFunction tests to run on arbitrary numbers of ranks
first version of a FWI
mapping for FWI added
updated setitem and getitem to preserve data substitutions
Fix scoping because my compiler complained. g++4.8 thing?
exporting compression support to buildvars
fixing test file filename mismatch
adding support for reading binary grids from gzip compressed binary files, ripley brick only so far
missing file
fixing/completing 2D lame assembler
added a check to only get data substitutions on symbols
a more general for of the inversioncostfunction has required for waveform inversin
renamed
added an optional evalf input to the evaluator, without this constants such as pi etc wont get evaluated. and renamed constants symconstants
Added a success/fail line below config in build process ( redmine #26 )
fixed presenservation of data objects(data substitutions) when subs is called on a symbol
Modify run_forward test to account for small negative results.
Added a missed include guard
Fix copy error from 3d down to 2d.
Fixed some bad indenting. Skip non-linear tests if sympy is not available.
Fixing print statement
made non-linearPDE tests on ripley work with any number of ranks
Added a temporay fix to get some of the unit tests passing again. This mechanism will be removed before the release so don't get used to it.
adding skeleton of fast Lame assemblers adjusted automatic ripley domain subdivision ( should solve issue #94 ) more tab->space conversions
Another try at this test.
Fixing not enough elements for small numbers of ranks in test
Failed to take ripley padding into account when constructing tests.
Removed rotation from ydirection test
Modified domain in tests
Some additional cleanup I missed
Set the randomfill back to generating randoms and updated doco to tell people how to use it.
added modification double *F_p=NULL; if(!p.F.isEmpty()) { p.F.requireWrite(); F_p=p.F.getSampleDataRW(0); } to all files such they will not operate on an empty F.
This version has been tested in some detail. It does not actually do randoms though (since that wrecks the testing). In will do a commit soon which puts the randomness back
updated test_yDirection fixed a couple of small bugs
Put in a check to make sure F is not used when empty. This prevents an exception.
some more work toward seismic data
Added test when adding incorrect Dim And Shape, for tryin to set Unknown Perameter and a test to make sure the definition of y is correct
data sources support tags now
data sources support tags now
Correcting python libname for sage. Fixing bug where the number of values in the shape was not considered for buffer and message size.
added warning output when saving as silo but not built with silo support (redmine #87 )
fixed __getitem__ such that the symbol it return will have the same dimentionality as its parent symbol
adding HTI support to 3D wave assembler
fixed duplication for 2D constant data in wave assembler
added support for HTI waves to the fast wave assembler
adjusting porcupine config to use MPI by default
Give the unit test enough room
acoustic forward problem + testing add.
modified nonlinearPDE to be compatible with python 3.
Replaced python dictionary iteritems with item for python 3.0 compatibility
Removing Finley mesh import which was copied from run_linearPdeOnFinley... as it is not used.
adding nonlinearpde test for ripley.
changed name
Changed name
adding ripley test for nlpde
adding nlpde tests
Unit test for nonlinear pde. test that it can generate a solution without error and that the appropriate coefficients are generated when setValue is called.
expanded tab chars for consistentcy and removed trailing whitespace
Not using GNU only getopt arguments
Ammended install doco for OSX
compacted older style C comparison structure
Fixed another comparator which wasn't strict
Correcting comparator function so it acts as < rather than <=
Replacing .eps figures in user guide with their pdf versions. If you are creating new figures, then please don't use .eps
Improvements but still needs more validation
adjusted launcher to run efficiently/properly on raijin
check in util no longer necassary due to wrappings in contants.py
This should help running on raijin without damaging anything.
Trying to make the shell on osx happy.
Adding wrapper for Symbolic constants such as pi usage: symconsts.pi ---> gives escript Symbol(sympy.pi)
Cater for changed interface in sympy 0.7.2. Also silenced a harmless warning.
more informative exception for unsupported error message
fixed dirac point->node mapping issues in ripley when using mpi
New solution to cos(sympy.pi). This solution help to keep sympy optional in escript and provides the desired functionality..
removed unwanted table
some extensions to synthetic_sonicHTI.py
further optimisation of wave assemblers, added support for constant data
fixed indent errors in coalgas, added future print import to seismic_wave, since it was using py3 style prints
fixed some error message formatting interpreting tuples badly
Renamed the default options file to make it clear that it was used for g++. There is now no default mole options file. This is deliberate. You need to configure your environment based on the compiler you wish to use. (See scripts in /usr/local/env). If you are doing a lot of building, symlink your chosen file to scons/mole_options.py. DO NOT COMMIT it though.
line 966 "if not args.has_key(n): args[n]=Data()" was changed to "if not args.has_key(n) and not constants.has_key(n): args[n]=Data()". also added: args=dict(args.items()+constants.items()) to merge the two dictionaries.
Ensure that DYLD_LIBRARY_PATH is passed into scons. Update mole_options to work with g++ (To get this to work, you will need to set up your env vars).
They should be equivalent but just in case ! == is treated differently to !=
Fixes necessary to get a clang/macports build working on 10.9
TTI fixes
fixed more whitespace issues
fixed mixed tabs/spaces for python 3 compatibility
Fixes to keep clang happy
Fixed failure for lazy data when interpolating.
missing file
Modifying nonlinearPDE.py comments to make the meaning clearer
fixing error in comment
Eliminated all const_cast<Data*> hacks in ripley and finley now that Data.getSampleDataRO returns a const pointer.
getSampleDataRO is now const
py3 RuntimeError does not have 'message' member.
updated gp py3 options.
Implemented reverse reading of grid data from netcdf files. Fixes #44.
new name for boost library on guineapig
-.
Corrected a faulty test.
Addresses #43 - altitude is now scaled according to reference system height unit. Also separated out UTM zone determination from the actual projection code to silence bogus output.
modifications to sonic seismic
scaling corrected
exposed createAbsorbtionLayerFunction
fix to deal with empty right hand side vector F.
tiny grammar fix in user guide
include cmath in all cases rather than math.h - the mathinf for intel on windows is still there (in part because we have no way to test if it is still relevant)
Updating run_models to not call the old DarcyFlow methods
Mantis issue #675 said Cihan: while merging symbolic into trunk I noticed that most dudley tests are disabled. This happened in revision 3261 where you wrote: "Disable some unit tests for dudley until I can fix MPI failures" Is that fixed? === I'm renabling most of the test (which pass without difficulty). But one of them appears to be out of date or something. More investigation required.
fixed tabs/space mix for python3
Added boost::noncopyable to remaining abstract base classes in the module file. ie escriptcpp.cpp Note I have not altered the c++ inheritance (this just just for the boost::python import)
Fixed missing \
downunder: self-demagnetization added as forward model.
Using section: science in debian/control instead of main. This new value for section has the virtue of actually existing
merged 3.4.1 release changes into trunk
Minor change to figure. Replaced .pdf with .png
fixed doc building relying on potentially missing python package installs (bug #739)
adding porcupine's scons options file
fixed gmsh Design deconstructor attempting to access non-existing members or files that were never created also fixed a loose (non-)integer division for python3
Undoing unintended commit of omp wrapper removal
python3ified things, replaced mixed whitespace and xrange calls
Some more work on this
some corrections
HTI added
Some work on rectangle random MPI
replaced a deliberate NULL dereference with abort() to satisfy lion-clang
strain convention corrected.
some update
Package building files for saucy
Options file for ubuntu 13.10
fixed Dudley saveVTK crash on world size > 6 (mantis bug #738)
and another typo fixed.
VTI wave added
typo fixed
VTI wave added
Removed spurious print and some minor changes in inversion example.
Options file for ferret
renamed design.Design to design.AbstractDesign as a more explicit/descriptive name, this will break any existing custom implementation until changed to match updated gmsh.Design docstring to match that of the code
Moving MeshAdapter constructor call out of smartptr constructor. I think a throw in there would lead to undefined behaviour
Fixed boost/intel issue in dudley and synced options file with module on savanna.
fixed mixed tabs/spaces and py2 prints breaking the python3 compiler
updated doc install instructions to match that required
documentation spelling and whitespace corrections, added some Design.setOptions params that were missing from the userguide
clarification on receiver array
Replaced non-visible (when built) unicode endash with single dash in user guide source
Fixed missing install keyword in instructions
some modifications
argument for lumping added.
renamed file
Added msec unit
sonic wave propagation added
wave simulator base added
wave simulator base added
missing retirn statement added
Moving to new icc and associated modules..
Ok, the python wrappers do use esysUtils for the exception translator. Anything else?
Windoze: Fixed warning and linker error Don't look for non-existing pasowrap tests.
Reordered and removed superfluous libraries from link lines. Hope W32 likes that.!
initial value changed
initial value changed
initial value changed
Fixed MSVC90 file as per Gordon's report..
. | https://svn.geocomp.uq.edu.au/escript/trunk/?view=log&sortby=log&pathrev=5722 | CC-MAIN-2019-18 | refinedweb | 3,227 | 54.73 |
29 July 2011 10:53 [Source: ICIS news]
SINGAPORE (ICIS)--?xml:namespace>
Sales, meanwhile, grew 20% year on year to W17,178bn in the April-June period but while operating profit declined by 32% to W451.3bn, SK Innovation said in a report posted on its website.
SK Innovation‘s earnings before interest, tax, depreciation and amortisation (EBITDA) also fell 27% year on year to W583.4bn in the second quarter, the company said.
Compared to the first quarter, SK Innovation’s pre-tax profit slumped 66% in the three months ending June because of weaker margins and sales volume of petrochemical products.
Operating profit declined 62% quarter on quarter, while EBITDA plunged 56%, it said.
Product spreads at SK Global Chemicals - SK Innovation’s petrochemicals division - fell during the second quarter of this year on the back of higher feedstock costs.
The polyethylene (PE)-naphtha spread was 15% lower quarter-on-quarter at $359/tonne (€251/tonne), while the paraxylene (PX)-naphtha spread slumped 28% over the same period to $516/tonne.
Paraxylene spreads were bearish in the second quarter owing to the normalisation of quake-hit facilities in
In its outlook, the company said that it expects olefin spreads to improve in the third quarter of 2011 on the back of turnarounds at regional crackers.
Increased utilisation rates at its downstream facilities on easing power shortages in
($1 = W1,0 | http://www.icis.com/Articles/2011/07/29/9480896/s-koreas-sk-innovation-pre-tax-profit-falls-12-sales-up-20.html | CC-MAIN-2015-22 | refinedweb | 232 | 51.89 |
Library tutorials & articles
Custom Email Control in ASP.NET
Custom Email Control in ASP.NET.
Sending email from a Web page is the most common functionalities used in web development. A common use of sending email is to send a static pre defined mail message to a designated email address from administrator menu. The .NET Framework makes the task of sending email from a Web page relatively simple. In order to send an email from ASP.NET Web page you need to use the Smtp Mail class found in System.Web.Mail namespace, which contains a static method Send.
System.Web.Mail namespace needs to be improrted to send an email. We use the SmtpMail and MailMessage classes of this namespace for this purpose. The MailMessage class provides properties and methods for constructing an email message.
To create email user control, we need to add a user-control file to a project. First, create a new ASP.NET Web application. Right click on the project in the Project Explorer and click Add - Add New Item and select a Web User Control item. This adds a file with the extension .ascx to the project. This is the file that the user control will use to expose its interface. basic HTML of emailStatic.aspx looks like this
<%@ Control Language="VB" EnableViewState="False" Debug="true" Strict="false" %>
<%@ Import Namespace="System.Web.Mail" %>
<SCRIPT language="VB" runat="server">
Sub Page_load(Sender as Object, E as EventArgs)
If request.form("EmailAddress") = "" Then
dim strResponse as string = "<h2>Send Email formatted in HTML</h2>"
lblMessage.Text = strResponse
Else
dim strResponse as string = "You just sent an email message formatted in HTML to:<h2>" & request("EmailAddress") & "</h2>"
lblMessage.Text = strResponse
End If
End Sub
Sub btn_Click(sender as Object, e as System.EventArgs)
If request.form("EmailAddress") <> ""
Dim mail As New MailMessage
mail.From = "salman.zafar@xyz.com"
mail.To = request.form("EmailAddress")
mail.Subject = "asp.net user controls"
mail.Body = "mail sent using asp.net user controls"
mail.BodyFormat = MailFormat.Html
' Mail Server Internet Address
mail.Fields.Add("","mail.xyz.com")
'
mail.Fields.Add("", "25")
' There are two levels of Send Usage
' cdoSendUsingPickup = 1 "Send message using the local SMTP service pickup directory."
' cdoSendUsingPort = 2 "Send the message using the network (SMTP over the network)."
mail.Fields.Add("", "1")
' There are three levels of SMTP Authentication
' cdoAnonymous = 0 "Do not authenticate"
' cdoBasic = 1 "Use basic (clear-text) authentication."
' cdoNTLM = 2 "Use NTLM authentication"
mail.Fields.Add("", "1")
' User account and password to authenticate to the server defined above
mail.Fields.Add("", "YourUserName")
mail.Fields.Add("", "YourPassword")
SmtpMail.SmtpServer = "mail.xyz.com"
SmtpMail.Send(mail)
End If
End Sub
</SCRIPT>
<asp:Label</asp:Label>
<FORM name="form1" method="post" runat="server" ID="Form1">
<INPUT id="btnSubmit" type="submit" value="Sending Email " name="b1" runat="server" OnServerClick="btn_Click">
</FORM>
Drag above control in any aspx file and start using emailing with predefined text in ascx file.
The HTML code for emailStaticTest.aspx looks like this
<%@ Register TagPrefix="uc1" TagName="emailStatic" Src="emailStatic.ascx" %>
<%@ Page language="c#" Codebehind="emailStaticTest.aspx.cs" AutoEventWireup="false" Inherits="CustomControls.emailStatic.emailStaticTest" %>
<uc1:emailStatic</uc1:emailStatic>
While this control is also quite simple, it lays the foundation for much more complex and innovative user controls. User controls can be very useful for breaking down a large application into smaller, more manageable chunks. Custom Email Control in ASP.NET. | http://www.developerfusion.com/article/6310/custom-email-control-in-aspnet/ | crawl-002 | refinedweb | 564 | 52.46 |
Member Since 6 Months Ago
3,250.
Commented on Practical Component Exercise #3: Tabs
Late, but I can provide you my code if you still want it. It's working for me.
Started a new Conversation Dear Jeffery , Please Make The Ottomatik Ad Below The Video Open In New Tab.
Sometimes, I click it by mistake.
Replied to Option To Save Video Quality Setting.
Same case, but opposite for me. My wifi is a bit slow, so the videos automatically start at 720p. But I can't watch it under 1080p, I just don't see the codes clearly unless its at 1080p, so I am willing to let it buffer a bit before watching.
Replied to AJAX For Laravel
I already know the basics of vanilla JS, so if Vue tutorials include Ajax, I can just skip dedicated AJAX tutorials?
Btw, do you have any other JS suggestions before Vue? I have some videos on ES6, Async (callbacks and promises), Fetch API) on my 'Learn JS' playlist. Which ones do you think I should learn before Vue and which ones can I skip because learning Vue will teach them anyway?
It's just that I'm planning to get the basics of Vue down this weekend, and I don't want to repeat lessons.
Started a new Conversation AJAX For Laravel
I'm planning to learn Vue JS, but I thought it'd be better if I learnt some basics first, like AJAX, jQuery, etc.
What's the best way to learn AJAX for Laravel? The tutorial I'm watching right now is using Vanilla ES5 JS for Ajax, but he mentions that it can be used with jQuery, Axios, etc.
I believe Laravel already has Axios out of the box? If so, Should I learn Axios, then AJAX with Axios or stick with Ajax with Vanilla JS?
Or should I skip AJAX altogether if I'm going to learn Vue later anyway?
Replied to Can Post Requests Set In Route Be Sent From A Different Website?
Sounds good. Thanks for the input!
Replied to Can Post Requests Set In Route Be Sent From A Different Website?
What if I don't need to use auth?
For ex. lets say a "Contact Us" form in a website. User doesn't need to register or login to send us a basic query, just put their contact info and message and send it.
I've noticed other tutorials do something like this instead (as opposed to Laracasts) :
<form method="POST" action="[email protected]"> . . </form>
without having it in the routes file.
Is this the safer/preferred method?
Started a new Conversation Can Post Requests Set In Route Be Sent From A Different Website?
If I have a form that sends a POST request to mywebsite.com/formsubmit and my route file has
Route::post('formsubmit', [email protected]);
Can a different website (say yourwebsite.com) have something like
<form method='POST' action='mywebsite.com/formsubmit'> ... ... </form>
store data into mywebsite.com's database?
Does csrf prevent these?
Replied to How To Redirect To An Anchor When Using Back() ?
This worked, kinda.
It does scroll down, but not fully to the error section. It just stops midway.
However, I have a link in the page that links to the error too (for testing), and that fully scrolls down to the error section.
Started a new Conversation How To Redirect To An Anchor When Using Back() ?
I have a page where if there is an error on form submission, it redirects to the same page using
return back()->with('message', 'Some Error');
However, the error message is at the bottom of the form, so I want it to auto scroll to the div with #message. How do I pass #message on back()?
Replied to Looking For A Good Tutorial On Implementing Recaptcha V3 On Laravel 6
Edit: I got the response token too, turns out you have to put the same thing in the 'action' in the script as the form.
Replied to Looking For A Good Tutorial On Implementing Recaptcha V3 On Laravel 6
I did check the first link before, and the backend part was really confusing.
The second one is even more confusing for me.
Anyway, I followed the first link and added this in my controller
$url = ''; $data = [ 'secret' => config('app.secret'), 'response' => request('recaptcha') ]; ddd($data);
This is the output:
array:2 [▼ "secret" => "6LeNr8*******" "response" => null ]
As you can see, the secret key is received correctly, but the response is null, which I'm guessing shouldn't be the case? Can you help me figure this out?
Started a new Conversation Looking For A Good Tutorial On Implementing Recaptcha V3 On Laravel 6
I've been looking for a good tutorial on the topic, but I haven't found any that is beginner'friendly.
I'm looking for one that teaches how to install and implement Google Recaptcha using this package:
Most tutorials are just blocks of code saying - copy this into that, but I don't know what they do at all.
What I've done:
Generated the site and secret keys and put them in my env file.
This is in my header:
<script src="{{ env('CAPTCHA_SITE_KEY') }}"></script>
This is in footer:
<script> grecaptcha.ready(function() { grecaptcha.execute('{{ env('CAPTCHA_SITE_KEY') }}', {action: 'contact-us'}).then(function(token) { if(token){ document.getElementById('recaptcha').value = token; } }); }); </script>
And this is the field in contact form:
<input type="hidden" name="recaptcha" id="recaptcha">
After this, I'm completely lost.
Replied to Class 'App\Http\Controllers\Contact' Not Found
Could you explain it a bit?
I renamed the Mail/Contact.php to Mail/Contact_email.php and made the necesssary changes inside that, and it's working now. Should I still use
use App\Mail\Contact as Contact_email;
?
What does it actually do? I'm a beginner so I don't really understand.
Replied to Class 'App\Http\Controllers\Contact' Not Found
@tisuchi This worked with a small tweak, since I had two contact.php, I changed the one under mail directory to Contact_email.php, and added
use App\Mail\Contact_email;
If I don't include the line above, I get this:
Class 'App\Http\Controllers\Contact_email' not found
I still don't understand why I have to use that model manually, but in the videos it works just by using the Mail facade. Shouldn't the mail facade automatically look in the mail directory?
Here's the video:
Started a new Conversation Class 'App\Http\Controllers\Contact' Not Found
I'm trying to send email following the latest Laravel 6 videos, but I'm getting this:
Class 'App\Http\Controllers\Contact' not found
Here's my ContactController.php:
<?php namespace App\Http\Controllers; use App\Contact; use Illuminate\Http\Request; use Illuminate\Support\Facades\Mail; class ContactController extends Controller { /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // request()->validate([ 'fullname' => 'required:max:50', 'email' => 'required|email', 'subject'=>'required|max:100', 'message'=>'required|max:500' ]); Mail::to(request('email')) ->send(new Contact()); } /** * Display the specified resource. * * @param \App\Contact $contact * @return \Illuminate\Http\Response */ public function show(Contact $contact) { // return view('pages.contact'); } }
I already have a 'Contact.php' in Mail folder, generated through
php artisan make:mail Contact
that looks like this:
<?php namespace App\Mail; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; class Contact extends Mailable { use Queueable, SerializesModels; /** * Create a new message instance. * * @return void */ public function __construct() { // } /** * Build the message. * * @return $this */ public function build() { return $this->view('email.contact'); } }
The only different thing I did from the tutorial was make a Contact model too like this:
php artisan make:model -mcr
Because I want to store it in the database too.
How do I solve this error? It looks like its looking for a Contact.php in the 'App\Http\Controllers\ directory instead of the 'App\Mail' directory
Replied to Any Way To Download A Complete Laracasts Series?
Replied to Any Way To Download A Complete Laracasts Series?
OK,
Final Question (questions) I promise.
Is the 15$ Subscription one time, monthly, yearly? And can I pay with PayPal?
I don't have a credit card but I could manage Paypal.
Sorry for these small queries, and thanks a lot for your time and responses.
Replied to Any Way To Download A Complete Laracasts Series?
Oh ok,
Last question. There seems to be a bug in the notification times, I started this topic 20mins ago and notifications say 11 hrs ago.
Any way to report this?
Replied to Any Way To Download A Complete Laracasts Series?
Alright.
Also, is there a way to know if a course is premium only before starting it? I don't see any indication at all a this page:
Started a new Conversation Any Way To Download A Complete Laracasts Series?
My connection at home is not so great, and it's difficult to read what Jeff is writing at anything lower than 1080p.
Is there a way to download all videos in a series?
Replied to Routes Not Working In Hosted App
Huh, for some reason, when uploading the files on the server, the .htaccess file was not uploaded at all (along with other hidden files like .env). I re-uploaded them, and it's working now, thanks for the help!
Started a new Conversation Routes Not Working In Hosted App
Hello,
My routes work fine on my local machine, but once I upload them in the hosting server, they don't work at all. Only the homepage works.
How can I fix this?
Here's my web.php file:
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', '[email protected]')->name('home'); Route::get('/about', '[email protected]')->name('about'); Route::get('/services', '[email protected]')->name('services'); Route::resource('/posts', 'PostsController'); Route::resource('/comments', 'CommentsController'); Route::resource('/category', 'CategoryController'); Auth::routes(); Route::get('/dashboard', '[email protected]'); Route::get('posts/{id}/duplicate', '[email protected]'); Route::get('/logout', '\App\Http\Controllers\Auth\[email protected]'); Route::get('/dashboard/category/create', '[email protected]'); Route::get('/dashboard/category', '[email protected]_category'); Route::get('/dashboard/posts', '[email protected]_posts');
And here's a link to my hosted app: lekham.ushostserver.com
Replied to Why Does {{ Auth::user() }} Work Anywhere But Other Models Don't?
Replied to Why Does {{ Auth::user() }} Work Anywhere But Other Models Don't?
So I have to pass the Category model in all my controllers, then pass the $categories variable in each and every controller function?
I know that works, I tried it before. But its so much repetition.
Is there a way to define something like '$sidebar_categories' that pulls name of all categories from the Category model and can be used globally? I just need to load it into my 'sidebar.blade.php' file, which is loaded in all other views.
Maybe I can define it in the Controller.php itself, since all controllers extends it. But I'm not sure how to make that work.
Started a new Conversation Why Does {{ Auth::user() }} Work Anywhere But Other Models Don't?
How come {{ Auth::user() }} works anywhere but any other model I need to import with the 'use' command?
I want to display a list of categories in all my pages, but I keep getting 'Class 'Category' not found'. I'm trying this right now:
@foreach (Category::orderBy('name', 'asc') as $category ) <li><a href="#">{{ $category->name }}</a></li> @endforeach
Can I make Categories model universally accessible like Auth? Or this there a better way to do this?
Replied to App URL Not Working Properly?
Thanks a lot!
As i said, if i use slash, i get localhost/storage/... Instead of localhost/lsapp/public/storage/... Even though my app url is localhost/lsapp/public. How can I solve this issue?
I'm fairly new, so I have no idea how to use those helpers you mentioned.
Btw, can (or should) I define my directories in env file and use it instead?
Started a new Conversation App URL Not Working Properly?
Hello,
I started learning Laravel from Traversy Media's tutorial, so like he taught, I used virtual hosts in XAMPP to point my app public folder "localhost/lsapp/public" to lsapp.com. After the course, I removed the virtual host codes because I needed to work on some other work related projects too.
Now, I'm trying to access the website directly from localhost/lsapp/public, and the website loads, but all the links that I put manually in the views and routes are using just localhost. I have also changed the APP URL in the .env file, and using the URL function returns "localhost/lsapp/public/", the login and register URLS are pointed correctly too, but everything else is broken. I have also cleared the config cache.
Here's what happens:
If I put something like <img src="/storage/images/image1.jpg">, it points to "localhost/storage/images/image1.jpg" instead of "localhost/lsapp/public/storage/images/image1.jpg".
EDIT:
Just as I was writing this post, I tried using <img src="storage/images/image1.jpg"> instead of <img src="/storage/images/image1.jpg"> (removed the first slash in src) and now its working.
It was working properly even with the slash before, when it was working through lsapp.com, could someone tell me the difference between putting the slash and not putting it?
Also, I'm gonna post this and keep it up, in case someone else has the same issue in the future.
Replied to Cannot Get ANSI Colors To Work In VS Code Git Bash Integrated Terminal
@untymage As I mentioned, I don't want to enter --no-ansi everytime (a permanent solution for this would be nice) and the other answer seems only for external git bash, not for VS Code integrated git bash. I even tried changing the path of git bash from bin/bash.exe to git-bash.exe, it opens it externally that way.
Started a new Conversation Cannot Get ANSI Colors To Work In VS Code Git Bash Integrated Terminal
I spent around 2-3 hours yesterday searching for a solution, but I haven't found any.
I know this isn't strictly Laravel related, but Laravel is the first thing I'm learning other than basics, so I don't know where else to ask. I'm only using git bash for Laravel as of now.
I'm using Git Bash as the integrated terminal in VS Code. However, ANSI colors are not working and instead I'm getting the codes to replace them.
Here's a screenshot: I followed both the answers in this post:
The first answer got rid of the color codes but did not display colors, only in the external terminal. No change in integrated terminal, even after putting the aliases.
The second answer also kinda worked, it got me the colors. Everything is repeated twice, so it's difficult. Here's an example: Please help me get the colors working, or maybe just get rid of ansi overall in php artisan commands, without having to put --no-ansi in every command. | https://laracasts.com/@mrkarma4ya | CC-MAIN-2020-05 | refinedweb | 2,562 | 65.42 |
See also: IRC log
<briansuda> Zakin, [IPcaller] is briansuda
<DanC> "Wednesday, October 11, 2006 at 15:00:00 Wed 11:00 AM * Wed 4:00 PM *"
<DanC> that's UTC / Boston / London
<HarryH> Sorry running late...
<DanC> unknown: Rachel Yager, Chimezie Ogbuji, Danny Ayers
<HarryH> +??P is HarryH
Minutes from last meeting to be sent out again for review
Murray: sent out introduction work, waiting for comments
iand: haven't had time to read it thoroughly
FabienGandon: what's process on editing?
HarryH: editors version can be changed whenever
danc: intro feels a bit long
<scribe> ACTION: iand to review Murray's suggested intro [recorded in]
danc: hello world example needs thought
<HarryH>
murray: needs rdf description of the stand in resource description section
HarryH: might be nice to have same examples everywhere
danc: readers may skip to examples
HarryH: do we lose the point if we don't elaborate the examples?
murray: if we put in 2 bits of
code, e.g. 5-6 lines of markup making assertions about authors
in fragments of different languages
... docbook, link rel="author" etc
danc: pick examples from real languages
HarryH: what about linking to the examples in the primer?
murray: not in intro - it should be self-contained
danc: dave booth asking for full xml example, we'll get to it
danc, is that ok?
<DanC> yes
<scribe> ACTION: Danc to flesh out ways to express author information in different markup languages [recorded in]
<DanC> MM: 1.103 is current
<DanC> (I think the 2 actions in the agenda are done.)
HarryH: chimezie expressed some
concerns that 2 example were not flowing well enough
... should we use real data or not?
danc: there might be real hreview
data, but they're usually not xhtml and don't have grddl
markup
... which means we have to copy, asking permission
... is it fair to copy yahoo data but not other W3C members'?
... would prefer to use real data
Murray: shouldn't tidy up existing data
HarryH: should we go back to reviews with manufactured data?
murray: what about getting w3c staff to write reviews of restaurants in cambridge and get them posted?
danc: i have hotel reviews
HarryH: we need more than one reviewer for example to make sense
danc: one hotel review is in edinburgh
<HarryH> we could try to make reviews
<HarryH> of hotels.
danc: want to talk about
xbrl
... xbrl uses xml schema and taxonomies which are like rdf schemas
... how much do we specify and how much do we evangelise?
murray: are we a bit early? do you want to work on a transformation and put in primer?
danc: yes I want to and we could
be early
... linkedin use hresume
... might be easier than xbrl
murray: i think dan ought to spend more time on section 4 of draft, less mathematics
danc: danny was going to look at test cases, ian too?
iand: would like to be involved
danc: don't close formats issue yet - ben adida and brian mcbride have some comments
scribe notes some discussion on local policy vs intention of author
HarryH: when should we ship spec? wait for tests?
danc: ready to go now
<HarryH> Brian's question about conneg and GRDDL
<HarryH>
murray: example of language
conneg. without accept header the server sends english version,
but my browser asks for spanish version
... grddl transformation will fetch from server and possibly get different language version
... how to fix this for the non technical user?
<HarryH> harry: GRDDL processors SHOULD support XSLT 1.0 and MAY support other
<HarryH> transformation languages."
<HarryH> GRDDL-aware agents SHOULD support XSLT 1.0 and MAY support other transformation languages
murray: believe dan's position is that "processor" shouldn't be mentioned but that the document shoud simply define the grddl terms
harry: what about putting this kind of language in primer?
we already have the following in primer: "Generally, if the transformation can be fully expressed in XSLT 1.0 then it is preferable to use that format since all GRDDL processors should be capable of interpreting an XSLT 1.0 document."
HarryH: add a test case too
<HarryH> add another use-case that adds XMLProc?
<DanC> spec says . "
<HarryH> Xlinclude case
<HarryH> Content negotation case
<HarryH> IanD: interested in content negotiation test case
<scribe> ACTION: iand to construct a content negotiation test case [recorded in]
scribe notes some discussion on grddl mechanism of passing document or infoset to transformation
danc: let's work through comments
<HarryH>
<HarryH> ACTION: iand to address comments on primer [recorded in]
<HarryH> ACTION DanC to handle Michael Hausenblas comments
<HarryH> ACTION: Murray (namespaces) to go over Section 4 of GRDDL Spec [recorded in]
harry: what the critical path now on the spec?
<HarryH> Murray: Example in introduction and Namespaces Section in Critical Path
<HarryH> Meeting adjourned!
I wrote this last year:
"Web 2.0 isnt the Semantic Web. Some might say its the semantic web (lower case) or that its a stepping stone to the Semantic Web. I dont hold either of those views. I believe that the Semantic Web is actually a part of Web 2.0 which is to say not only that Web 2.0 is more important than the Semantic Web but that Web 2.0 requires the Semantic Web"
harryh, can you generate minutes?
This is scribe.perl Revision: 1.127 of Date: 2005/08/16 15:12:03 Check for newer version at Guessing input format: RRSAgent_Text_Format (score 1.00) No ScribeNick specified. Guessing ScribeNick: iand Inferring Scribes: iand WARNING: No "Present: ... " found! Possibly Present: FabienGandon HarryH IPcaller MM Murray Murray_Maloney P5 briansuda danc harry iand inserted unknown You can indicate people for the Present list like this: <dbooth> Present: dbooth jonathan mary <dbooth> Present+ amy Regrets: Ben_Adida 2006 Guessing minutes URL: People with action items: danc iand murray namespaces WARNING: Input appears to use implicit continuation lines. You may need the "-implicitContinuations" option.[End of scribe.perl diagnostic output] | http://www.w3.org/2006/10/11-grddl-wg-minutes.html | CC-MAIN-2015-40 | refinedweb | 994 | 63.59 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.