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
|
|---|---|---|---|---|---|
Good libraries are like novels -- hard to write in any language. Every language has a different
definition of good. Java can't be transliterated to Pythonwell because every language has its
own idioms.
"Pythonic" code is in harmony with standard libraries and conventions of Python and takes advantage of the features baked into Python. You might not think you create APIs -- you do, if only for your future self. Anywhere you present functionality to other code, even in the same codebase. Your function names, classes, command line flags, HTTP endpoints, and error messages are all part of your API.
To build a library that's easy to use, you have to put yourself in the shoes of a developer who heard about your library this morning and has a problem to solve this afternoon. Don't make them put aside all they know already. Use familiar vocabulary in your API. Reuse conventions from the rest of Python. Try to avoid surprising them with anything.
Craft is any process that attempts to create a functional artifact without separating design from manufacture. -- Wroblewski source
As you build your library, you will likely see rough spots that need improvement. That's normal -- try to smooth them out as they become visible instead of promising to clean it up later. Think about how your decisions will affect the finished product. Is naming this method requests.requests_get going to make it easy to remember? No, it looks confusing since you're already in a namespace. For more about simplicity and readability, take a minute to review The Zen of Python (PEP 20).
Names make code readable, it's how users most often will be thinking about your library.
Avoid names like "skycopter" -- what even is that? Names need to be easy to reason about. If
the name that best describes your object or function is exceptionally long, consider that it
may have too many responsibilities and will be too complicated for users to understand
easily. This is doubly true if it contains the name of one or more design patterns .
Use familiar words if you can. Requests has methods that match HTTP method names, which users of requests likely know already.
The average human can hold five to nine chunks of stuff in their head at once; don't fill up all
those slots with just your function call. If you have that many knobs on your widget, fear not.
You can make sane defaults, use a configuration file, or add a wrapper class so developers
don't need every parameter for every call.
Say you have a function that looks up a user on your service by their username: that requires API credentials, an API endpoint, and a user to query for.
So which would you prefer to call -- get_user or Session.user? I'd prefer not to provide the arguments every time, and a class is one way to do that. Another alternative is to use functools from the standard library. A "partial" is a function that remembers some provided arguments and calls the underlying implementation.
The code above saves the first arguments to get_user and gives back a new function that only needs to be passed the username similarly to the Session class. The difference is that functools lets us skip the boilerplate code to create the object.
Python has loads of standard method names associated with defined protocols. Most of them are made to integrate your objects with builtins -- think len and str. To let your object use those builtins you simply need to implement __len__ and __str__. If you find yourself writing a method like .length() ask yourself if thats what users would expect. The answer is likely "No!"
When you make an object, also define a nice __repr__ function for it -- you'll thank yourself later. By default, when you print an object, Python tells you about its location in memory.
Two lines of code are all it takes to make printing an object useful.
This may not seem like much of a change, but for users new to your library or those that are using it interactively this is a huge improvement. It makes it easy to see what an object is without knowing all the fields it provides.
When you present a user with a list, you must consider their needs. Are you presenting the filename of every file on their filesystem as a list; loading every item into memory at once? If you can calculate the values incrementally, it's helpful to do so. It means you can start processing values without waiting for the full list to be loaded into memory. Consider looping over a bunch of numbers.
In Python 2, that code would create a list of all 1000 digits and returned it to be iterated over.
It works, but using all that memory doesn't help the caller. The caller only needs to know the
next value. In Python 3, range would generate the next number only when asked. Generators
are iterable, but don't produce all their values up front.
Here, we make our own generator to count up from zero.
What makes a generator different from a normal function is the yield keyword. The function stops what it's doing at the yield and hands control back to whatever called it. This lets the caller (our for loop) process each result before calculating the next value. For our generator, counting to 5 million would have the same memory footprint as counting to four.
It's easy to add setup steps for your classes in the __init__ method, but failures might leave you with some resources that need to be cleaned up. Lockfiles, open sockets, and other things need to be cleaned up whether your object finished creating or not.
It's easy to forget to release all your resources. Python provides context managers to make the process of acquiring and releasing shared resources easier. A context manager is a simple way to ensure that initialization and teardown are easy to do correctly. To use a context manager, you open a block using the with statement and teardown is automatically done when exiting the block.
The calling code can be much simpler thanks to with. You can also see that the contextmanager is actually a decorator atop a generator function. See how nicely these compose? Context managers are useful for safely writing to files, getting transaction locks, database connections, and more.
Developers are people too. When I buy a power tool, I don't read the warnings. After a trip to Ikea, I don't read the instructions unless I have to. Your program is a tool, and its job is to help users. Your users want to install a library and get back to work, and a great user interface is critical to letting them do just that.
Where is your documentation? I hear you, documentation isn't code, but it is the
Application-Human Interface for your project. Without documentation you leave developers
adrift on StackOverflow -- or worse, send them wading through your source code never to be
seen again.
For an example of nice documentation, take a gander at the tox or sphinx docs. Both prominently feature a low-jargon description of the project. Here's the Sphinx summary:
Sphinx is a tool that makes it easy to create intelligent and beautiful documentation
And on tox's page:
tox aims to automate and standardize testing in Python
A curious developer might then say "neat, how does this tool do that?" Both pages answer
immediately with code samples and feature highlights. In just a minute or two I can decide
whether these are the right tools for my job.
Further down the page, there are paragraphs of additional detail and links to: extra examples, documentation, user stories, and feature lists.
For a deeper dive into documentation, check out Django contributor Jacob Kaplan-Moss' series on Writing Great Documentation. It ought to be required reading for Computer Science students. William Zinsser's book On Writing Well is an excellent guide for any nonfiction, but does not focus on technical documentation.
Computers break. Assumptions can be wrong. The International Space Station has six computers running all the time, checking each others' work. In space, every calculation must be correct every time. When things break in (or outside of) your library, which of these should you show?
Your error messages need to be as helpful as possible. They are born to say "______ went wrong, and here's how you make it stop _____". You may not be able to depend on being able to surface logs directly, but you can always be sure to throw readable exceptions. It's a good idea to create your own exception classes, check out this example from SQLAlchemy (full code).
Having a top-level class for all SQLAlchemy's exception classes makes it easy to see if a
problem comes from SQLAlchemy with an issubclass test. For users, this makes it easy to
track down the source of a problem.
Specific exceptions like DisconnectionError help by explaining everything SQLAlchemy tried before raising the exception.
Next time you sit down to write a library, don't start by writing code. Get out of the author
mindset for a moment and think about how you'd expect it to work. Consider which features
you'd need, and which are "nice-to-have". Look at libraries that solve similar problems and
see what idioms they use, or what they do that doesn't seem quite right.
Take the time to solve the problem you set out to in the best way you know how. Your users and fellow developers will thank you.
Easy, comprehensive, great way to get started
A great course to get into Python. Very comprehensive and easy to understand lectures.
good introductory overview and use of python
All in all a good course for Basic Python
Good course. One suggestion would be to present the goal of exercises to the student and then go about presenting the script for it. Instead of directly going for the explanation of script.
The Ultimate Python Programming Tutorial
I really enjoyed learning the Python programming offered by this course. I had some knowledge of programming but these video lessons expanded my knowledge greatly.
Good and Concise
Good understanding without all the fluff
|
https://www.udemy.com/the-ultimate-python-programming-course/
|
CC-MAIN-2016-07
|
refinedweb
| 1,732
| 73.47
|
I am a beginner student in desperate need of help writing a program. Recently, we have learned about functions, loops and reading from data files. My assignment is to write a program (Book Sale Calculator) that accepts all input from an external data file and displays a summary for each book sale. The program needs to open the external data file and continue to read in data until the end of the file is reached. No sentinel value can be used to signal termination, and I cannot count the number of items in the file or use a count controlled loop to obtain the data. The data file is stored so that the number of books in each sale and the single character code for shipping (S = Standard which is 4.99 and E for Expedited is 12.99) representing the shipping method is on one line, and the prices for all of the books are on the second line. I need to create four functions for the following:
(1) Obtain the name of the data file and attempts to open it for readying
(2) Obtain all input for each sale from the data file. This function should also return the merchandise subtotal and shipping method
(3) Calculate all taxes and discounts
(4) Display a final total
The sales tax is .05%
Discounts are as follows:
* If the subtotal is < $50, there is no discount
* If the subtotal is between $50-$100, the discount is 10%
& If the subtotal is above $100, the discount is 15%
Additionally, no global variables can be used and all information must be shared between functions via parameters and return values. My main function should consist of variable declarations, function calls, and a control loop for reading each sale from the file can be there.
The external data file consists of the following format:
5 S
2.99 12.45 13.23 21.99 24.59
1 E
34.95
3 E
8.99 12.45 7.58
7 S
5.66 12.35 23.56 40 12.99 16.32 11.23
A sample output of the program:
The summary for order #1 is as follows:
Subtotal: 75.25
Tax: 3.76
Discount: 7.53
Shipping: 4.99
Total: 76.48
The summary for order #2 is as follows:
Subtotal: 34.95
Tax: 1.75
Discount: 0.00
Shipping: 12.99
Total:49.69
The summary for order #3 is as follows:
Subtotal: 29.02
Tax: 1.45
Discount: 0.00
Shipping: 12.99
Total: 43.46
The summary for order #4 is as follows:
Subtotal: 122.11
Tax: 6.11
Discount: 18.32
Shipping: 4.99
Total: 114.89
Thanks for shopping with us. Come again!
I have provided the source code that I have come up with so far but am at a complete loss. I really don't have any idea as to how to write this program and would GREATLY appreciate ANY assistance!!
Code:
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <iomanip>
using namespace std;
//This function displays a brief overview explaining the program to the user
void programOverview()
{
cout << "This program will read input from an external file" << endl;
cout << "and calculate the total amount of money for books sales" << endl;
cout << "at an online store." << endl;
}
//Open the file/report error
void openFile ()
{
ifstream fp;
fp.open ("books.dat");
if (!fp)
cout << "Error opening the file" << endl;
exit (EXIT_FAILURE);
}
//This function will obtain all input for each sale from the data file and return merchandise total and shipping method for the sale being processed
void obtainInput()
{
ifstream fp;
int books;
char shipping_method;
float price;
float subtotal;
float shipping_price;
for (int i=0; i<=books; i++)
fp >> books;
fp >> shipping_method;
for (int i=0; i <= books; i++)
{
fp >> price;
}
subtotal+=price[i];
return subtotal;
if (shipping_method == 'S')
shipping_price = 4.99;
else
shipping_price = 12.99;
}
//Calculate tax, discount, shipping and total
void calculateOutput()
{
float tax;
tax = subtotal * .05;
float discount;
if (subtotal < 50)
discount = 0.00;
else if (subtotal >= 50 && subtotal <= 100)
discount = subtotal * .10;
else
discount = subtotal * .15;
float total;
total = subtotal + tax - discount + shipping_price;
}
//Display a final summary
void displaySummary()
{
cout << "The summary for the order is as follows:" << endl;
cout << fixed << showpoint << setprecision (2);
cout << "Subtotal:" << subtotal << endl;
cout << fixed << showpoint << setprecision (2);
cout << "Tax:" << tax << endl;
cout << fixed << showpoint << setprecision (2);
cout << "Discount:" << discount << endl;
cout << fixed << showpoint << setprecision (2);
cout << "Shipping:" << shipping_price << endl;
cout << fixed << showpoint << setprecision(2);
cout << "Total:" << total << endl;
}
int main ()
{
programOverview ();
cout << "Book Sale Calculator" << endl;
cout << "=======================" << endl;
openFile();
obtainInput();
calculateOutput();
displaySummary();
return 0;
}
|
http://cboard.cprogramming.com/cplusplus-programming/137237-having-trouble-obtaining-input-file-printable-thread.html
|
CC-MAIN-2014-23
|
refinedweb
| 763
| 64.91
|
Post your Comment
The Switch statement
a statement following a switch
statement use break statement within the code block.... To avoid this we can use Switch statements
in Java. The switch statement is used....
Then there is a code block following the switch statement that comprises
How to use switch statement in jsp code
How to use switch statement in jsp code
... and that will be an error.
The example below demonstrates how we can use switch
statement in our JSP...;TITLE>use switch statement in jsp page</TITLE>
</HEAD>
<BODY
Switch Statement
Switch Statement How we can use switch case in java program ?
Note:-Switch case provides built-in multiway decision statement.It... switch case statement. The program displays the name of the days according to user
Switch Statement example in Java
for implementing the switch
statement. Here, you will learn how to use the switch statement... Switch Statement example in Java
... more about the switch statement in
Java. The following java program tells you
Switch
a switch
statement use break statement within the code block. However, its... statements. To avoid this we can use Switch statements
in Java. The switch statement....
Then there is a code block following the switch statement that comprises of
multiple case
Switch statement in PHP
Switch statement in PHP HII,
Explain about switch statement in PHP?
hello,
Switch statement is executed line by line. PHP executes the statement only when the case statement matches the value of the switch
Break Statement in JSP
are using the switch statement under
which we will use break statement. The for loop...Break Statement in JSP
The use of break statement is to escape
What is the difference between an if statement and a switch statement?
What is the difference between an if statement and a switch statement? Hi,
What is the difference between an if statement and a switch statement... values). Whereas the Switch statement offers you multiple choice of option from
Use Break Statement in jsp code
Use Break Statement in jsp code
...;H1>use break statement in jsp code</H1>
<%
double array...;/HTML>
Save this code as a jsp file named "break_statement_jsp.jsp
C Break with Switch statement
C Break with Switch statement
In this section, you will learn how to use break statement... the user to enter any number. The expression defined in the
switch statement finds
Use Compound Statement in JSP Code
. The following jsp code will show you how to use
compound statement.
compound... Use Compound Statement in JSP Code
...;);
}
%>
</BODY>
</HTML>
Save this code as a .jsp
Switch case in java
if statement, switch allow the user to select a option from
multiple options. switch statement have multiple
number of possible execution path. It work... will illustrate the use of switch
case in java:
import java.util.Scanner;
public
switch statement
switch statement i want to write a java program that computes Fibonacci,factorial,string reversal and ackerman using switch case to run as a single program
How to use 'if' statement in jsp page?
How to use 'if' statement in jsp page?
... how to use 'if'
statement in jsp page. This statement is used to test... this code as a .jsp file named "use_if_statement.jsp"
Java Switch Statement
Java Switch
Statement
In java, switch is one of the control statement which
turns the normal flow... then switch statement can be used. It checks your choice and
jump on that case label
i need to replace this if statement code with switch case code
i need to replace this if statement code with switch case code i need to replace this code with switch case
for(int i=0;i<100;i++){
if((i... is your required code:
class Loops{
public static void main(String[] args
switch Java Keyword
:
-- The switch statement in java language enables the user to select... of each case block to exit from the switch
statement.
-- If the break statement... following case and/or default
blocks. That makes senseless to use the
switch case
Java - The switch construct in Java
.
In this Program you will see that how to use the switch
statement...;
Switch is the control statement in java which... choices are available then we
generally use the If-Else construct otherwise Switch
Switch Statement with Strings in Java
Switch Statement with Strings in Java Switch Statement with Strings in Java
Use if statement with LOOP statement
Use if statement with LOOP statement
... with Example
The Tutorial illustrate a example from if statement with LOOP
statement. In this example we create a procedure display that accept
Strings in Switch statement
Strings in Switch statement
In this section, you will learn about strings..., you can pass string as expression in switch statement.
The switch statement... have matched string. The comparison of
string in switch statement is case
Nested If Statement
Nested If Statement
In this section you will study about the Nested-if Statement in jsp.
Nested If statement means to use the if statement inside the other if
statement
JSP If statement Example
a simple JSP program.
Example : This example will help you to understand how to use...JSP If statement Example
In this section with the help of example you will learn about the "If" statement in JSP. Control
statement is used
Find Capital using Switch-Case statement
Find Capital using Switch-Case statement
In this Java Tutorial section, we are going to find the capital of our states using Switch-Case statement... state will get displayed on the console.
Here is the code:
import
iPhone Switch Changes Toolbar Color
iPhone Switch Changes Toolbar Color
In this tutorial we will use Switch button to change the Color of Toolbar. The Switch is added through the Interface..., first will declare the variable for the Toolbar, Switch and then will write
JSP IF Statement
JSP IF Statement
In this section we will read about how the If statement is used in the JSP
programming.
In JSP, If statement can be used as it is used... as the condition, evaluates to true.
Here we will use both IF statement in JSP.
Syntax
switch functions - Java Beginners
switch functions I am writing a script for use in a computer based... friend,
This is running code,
switch option using in javaSctipt... your month of hire:")
switch(n)
{
case(n="January"):
document.write("Last
Java - Break statement in java
statement is used in while
loop, do - while loop, for loop and also
used in the switch statement.
Code of the program :
public class ...
Java - Break statement in java
Post your Comment
|
http://roseindia.net/discussion/21675-How-to-use-switch-statement-in-jsp-code.html
|
CC-MAIN-2015-32
|
refinedweb
| 1,091
| 74.08
|
#include <iostream> // Print out a 4x4 grid using one loop, from 0 to 15 void PrintGrid(int squares[]) { int num = 0; for (int i = 0; i < 81; i++) { std::cout << squares[i] << " "; num++; if (num == 9) { std::cout << "\n"; num = 0; } } } // Print out the 4x4 grid but using 2 nested loops. // This does the same as the function above - it's just a slightly different // way of doing it. void PrintNested(int squares[]) { // Nested loop int num = 0; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { std::cout << squares[num] << " "; num++; } std::cout << "\n"; } } // Check if we have a Bad Column: if any square in the same column as squareNum // contains the same value as squareNum, this column is bad, because it has the // same number in it more than once. bool BadColumn(int squareNum, int solution[]) { int top = squareNum % 9; for (int i = 0; i < 9; i++) { // Don't check squareNum with itself! If the 'top' square number is the same // as squareNum, just go on to the next square. if (top == squareNum) { top += 9; continue; } if (solution[top] == solution[squareNum]) { return true; } top += 9; } return false; } // Check if we have a bad row: if any square in the same row as squareNum contains // the same value as in squareNum, this is a bad row. bool BadRow(int squareNum, int solution[]) { int left = (squareNum / 9) * 9; for (int i = 0; i < 9; i++) { // Same as for BadColumn(), we don't want to check squareNum against itself. if (left == squareNum) { left++; continue; } if (solution[left] == solution[squareNum]) { return true; } left++; } return false; } // Check if a 2x2 box is bad bool BadBox(int squareNum, int solution[]) { // Get the top-left position: either 0 or 8 int topLeft = (squareNum / 27) * 27; // Now add 2 if the box is to the right - so we now have a top-left position // of 0, 2, 8 or 10. if ((squareNum % 9) > 1) { topLeft += 3; } else { if ((squareNum % 9) > 4) { topLeft += 3; } } // Count through the 4 squares in the box for (int i = 0; i < 9; i++) { // Again, we don't want to test squareNum against itself. // This time we are not using continue, for some exciting variety. if (topLeft != squareNum) { if (solution[topLeft] == solution[squareNum]) { return true; } } // Slightly more complicated than for row and column, we add 3 to the topLef square // if i is 1, to go the leftmost square of the next row in the box. if (i == 1) { topLeft += 4; } else { topLeft++; } } return false; } // Check if a square is bad: it is bad if we have a duplicate in the row, column or box // that squareNum occupies. bool BadSquare(int squareNum, int solution[]) { if (BadColumn(squareNum, solution)) { return true; } if (BadRow(squareNum, solution)) { return true; } if (BadBox(squareNum, solution)) { return true; } // Column, Row and Box are all good - so this is NOT a bad square. return false; } // Check if we have found a solution for a sudoku. // The way this works is: we check each square. If all the squares are 'good' we have // solved the puzzle. // A good square means it does not have a duplicated value in the same row, column or // box. bool IsSolved(int solution[]) { // Check every square. For a 4x4 sudoku, that means 16 squares, right?! for (int i = 0; i < 81; i++) { // If we find a bad square, the puzzle is not solved. if (BadSquare(i, solution)) { return false; } } // No bad squares - the puzzle is solved! return true; } // Test function: work out if a grid has a valid puzzle solution in it. // We can use this to make sure IsSolved() works as we want it to. void Test(int grid[]) { if (IsSolved(grid)) { std::cout << "This is a good solution:\n"; } else { std::cout << "This is a bad solution:\n"; } PrintGrid(grid); } int main() { // Test our IsSolved() function by testing a good puzzle solution, and a // bad solution. // This gives us some confidence but the best way to check it is to step // through the code - we did this in class and found bugs! int good[] = { 9, 6, 1, 5, 4, 8, 2, 7, 3, 8, 7, 2, 9, 3, 1, 6, 4, 5, 4, 5, 3, 6, 2, 7, 8, 9, 1, 5, 4, 9, 3, 8, 2, 1, 6, 7, 2, 8, 6, 7, 1, 5, 4, 3, 9, 1, 3, 7, 4, 9, 6, 5, 8, 2, 6, 9, 4, 1, 5, 3, 7, 2, 8, 3, 2, 5, 8, 7, 4, 9, 1, 6, 7, 1, 8, 2, 6, 9, 3, 5, 4 }; // Test the good puzzle - we expect Test() to say that this is a good solution. Test(good); int bad[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 3, 1, 2, 3, 3, 4, 5, 6, 9, 4, 4, 4, 2, 4, 5, 6, 7, 9, 2, 3, 1, 1, 6, 7, 7, 8, 9, 3, 4, 1, 2, 3, 4, 5, 6, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, }; // Test the bad puzzle - we expect Test() to say that this is a bad solution. Test(bad); }
it should return the good solution as being good and the bad as bad, but it always returns the good as bad please help :s
sorry most of the comments are from my 4x4 version but they should still be of some help.
so at the moment it doesnt actually solve the sudoku for you, it is simply trying out wether or not it recognises when the puzzle is solved or not and as you see the good grid i have is definetley a valid sudoku. once this is working i can get onto the rest of my code
This post has been edited by stayscrisp: 14 February 2008 - 08:22 PM
|
http://www.dreamincode.net/forums/topic/43331-sudoku-solver-help-with-3x3-boxes/
|
CC-MAIN-2016-44
|
refinedweb
| 986
| 73.24
|
When of these.
First of all, we need to create an empty list where we will add the items. For simplicity reasons, these examples will use a Java List of String elements. The corresponding import needed for working with Lists is:
import java.util.List;
Creating the empty List (where we will later store the needed items) can be done as follows:
List<String> theList = new ArrayList<>();
Now, we need to add content to this list. Let’s say, again for example purposes, that the list holds the text retrieved from web page elements with Selenium. That means there is a List of WebElements that needs to be iterated, so that the text for each of these WebElements will be extracted and added to the List we just created (‘theList’). Let this list of WebElements be named ‘listOfWebElements’, and let’s pretend it is not empty, so we can iterate it to get the text we want.
for (WebElement element : listOfWebElements) { if (!theList.contains(element.getText())) theList.add(element.getText()); }
In this case the generated List, ‘theList’, only contains unique values. How is that done? The ‘contains()’ method from the List class returns true only if the List already contains the item you are using it with, at least once. If this items is already in the List, it will not be added again. An item is added only if it is not already present in the List.
However, if for some reason you cannot use the ‘contains()’ method to ensure the uniqueness of the item you want to add to the List, you can remove duplicates from an already populated List, using Java streams (when using Java 8 and above). Creating a new List (‘newList’ below) out of all the unique items from an initial List (‘listWithDuplicates’ below) can be done as follows:
List<String> newList = listWithDuplicates.stream().distinct().collect(toList());
2 thoughts on “Removing duplicates from a List”
If you don’t care about ordering, using the Set interface, you will have better performance:
newList = new ArrayList(new HashSet(initialList));
|
https://imalittletester.com/2019/10/31/removing-duplicates-from-a-list/?like_comment=21680&_wpnonce=584518766a
|
CC-MAIN-2022-21
|
refinedweb
| 342
| 60.65
|
I need to load in images at run-time, doing something similar to this:
using System.IO;
using UnityEngine;
using UnityEngine.UI;
public class SpriteCreator : MonoBehaviour {
// public string textureFilePath => Application.persistentDataPath + FileName;
void Start () {
Texture2D texture = new Texture2D(2, 2);
texture.LoadImage(File.ReadAllBytes(Application.dataPath + "/Logo_Dominoes.png"));
GetComponent<Image>().sprite = Sprite.Create(texture,
new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
}
}
But some of my test images become distorted with this code. This distortion doesn't happen with all of my test files. I am attaching one of the test files that gets distorted, but I do not believe there is any issue with the test files, as they appear OK when I import them in the Unity Editor.
An Image with the sprite assigned through the editor (top) appears fine, but an Image with the sprite assigned at run-time (bottom & selected in inspector) has a subtle distortion around the words "Card Game Simulator" and "Dominoes":
Why is this subtle distortion appearing?
Answer by mossflower
·
Dec 29, 2017 at 04:51 AM
Since 'Alpha is Transparency' is only available in the Unity Editor and not at run-time, the solution is to do what that setting would do. One option is to edit the images beforehand. But this option doesn't really work for me, since that would put extra work on the people creating these images for me. Luckily, there is a paid solution in the asset store.
Answer by AggroBird
·
Dec 29, 2017 at 02:01 AM
The texture that the generated sprite is added to has the 'Alpha Is Transparency' setting set to false, which causes these artifacts. You can verify this by disabling the setting on your in-editor texture, you will see the same artifacts on both images.
Sprites that are generated through Sprite.Create() appear to have this setting off, and I couldn't find a way to enable the setting on the internal texture.
Like you said, the same thing happens if I turn off 'Alpha Is Transparency' in the Unity Editor. I tried doing texture.alphaIsTransparency = true; in my code, but that setting does seem to be ignored in code. Is this a bug? Is there any workaround?
The alphaIsTransparency is a strange editor-only variable on Unity's Texture2D class (it is missing from the documentation too I think).
When you view the generated sprite texture in the inspector, it shows that it only has three properties: Wrap mode, Filter mode and Aniso level. I guess the other properties are being ignored or don't work correctly.
Yeah, I found this: Guess I know where my votes are going.
Answer by Taylor-Libonati
·
Dec 28, 2017 at 05:45 PM
I am not sure exactly why this would happen but it seems like the Texture2D's format is different then in the editor. When you import things in the unity editor it comes in with a bunch of default settings. You probably need to have those same settings with the dynamically loaded texture. Maybe try setting the textures filterMode before creating the sprite?
texture.filterMode = FilterMode.Bilinear; //try all three filter modes. see if you notice a diference
Filter modes didn't fix it. I went further and looked at all the import settings used in the editor and applied them all in code. Still the same.
Next, I tried loading the exact same texture in the exact same way, but I applied the texture to a material on a quad instead of a sprite: GetComponent(Renderer)().material.mainTexture = texture; And the texture on the quad looks good! I guess it is some issue with Sprite.Create()? But I have no idea how to proceed from here.
That is really strange. I suggest filing a bug report. I am not really sure either. Sorry39 People are following this question.
Strange behavour when drawing on texture
0
Answers
Distribute terrain in zones
3
Answers
How do I rearrange sprites' transform coordinates by name?
1
Answer
Updating Sprite texture leaves red outline
1
Answer
sprite border
0
Answers
|
https://answers.unity.com/questions/1447563/image-distorts-when-created-in-c.html
|
CC-MAIN-2019-51
|
refinedweb
| 683
| 65.52
|
Journal: Toward a New Unix Shell 2
One thing that's interested me a lot lately is the idea of improving upon, or reinventing the Unix command shell.
Now, there's a certain class of Unix users who have stuck with the command shell while GUIs have come and gone, been released, overhauled in various releases, and so on until new versions barely resemble old ones. One of the problems I face in this kind of plan is that many of these users are fairly attached to the tradition. They use the current command shells because it's the environment they like, and many of them don't want to use a "reinvented" shell. When in my design I start thinking about giving the shell its own type system to be used over pipelines, or devising a set of rules that tools would have to follow to "play nice" in this environment - I know that a lot of my target audience just flat out isn't going to like it. This concerns me. But still the idea of this environment appeals to me. Somehow I want to make it work, and make it stick.
Now, the first question one has to ask about something like this is, why? Why should the shell change? There are a few reasons I have in mind:
- If the shell could know things like the type of a piece of data, or the kinds of command-line options a tool supports, it could offer context-relevant help.
- In present shells, when connecting the output of one tool to the input of another, the user must insert parser/serializer steps. I feel it's appropriate for the shell to be able to offer a greater degree of help than that.
- I think there's real value in giving the shell a way to deal with "objects" and higher-order programming in general. For instance, an object could be an XML parser or an open network connection or a window into a running application: for the lifetime of that object the shell should be able to issue commands to that object - and when the shell's last reference to that object is destroyed, some action (like closing a connection or killing a process) may be appropriate. There are some command-line tools that implement this sort of behavior themselves, but I think it would be very nice if it were a real feature of the shell.
Also, I believe the current model of the shell has fallen behind how people actually use their computers. For instance:
- Modern GUIs offer a lot of useful functionality - but the extent to which this functionality is integrated into the command shell is rather limited for various reasons. For instance, why isn't the volume manager or the wi-fi manager that I used inside the GUI also available outside the GUI? The basic answer is that command-line tools aren't well suited to that kind of usage profile in which they are started as a service and then, while running, receive and respond to outside commands. The framework for such a thing simply isn't in place.
- Scripting languages like Perl and Python offer large and useful libraries that perform all kinds of different features. Why can't shell scripts access these? The basic answer at present is that the programming language provided by the shell lacks the constructs necessary to usefully interface with these utilities. The lack of "object" support (and, specifically, lack of a good mechanism to start something, keep it running, and interact with it, and shut it down when finished), the lack of any sort of namespace support, and the fact that any data going into or coming out of such a library has to be arranged in some ad-hoc format for which the shell provides no specific support - all of this severely hampers the ability to expose these libraries and the practical benefits of doing so.
Microsoft has already come up with their own solution: "Powershell" - a command shell somewhat similar to cmd or a Unix shell, but with support for "commandlets" - commands on the search path which are actually
My goal is a bit different. Linux has no standard representation for "objects" (and I'm not in a hurry to embrace Mono, let alone encourage others to do the same) so Microsoft's approach isn't suitable for my goals. Furthermore, without the ability to restrict the behavior of a piece of code within a single process, it becomes more important for the stability of the shell to continue to have tools be separate processes. Therefore, whether these outside processes communicate via shared memory or pipes, either way they need to respect a few common conventions about how data is formatted, and (in the case of "objects" - data in which it's important to know when it's time to destroy it) how to manage object lifetime.
One of the typical complaints is that a plan like this requires all shell tools to agree upon and use the same set of rules for how they format their data. This would be a real problem: people would be slow to move to this format, which in turn would make the shell less useful (since it would lack the tools to run in its "enhanced" environment). No one would want to write a tool that runs only in a new, unproven shell, and no one would want to either shoe-horn their problem into an uncomfortable data format, or waste CPU time by translating their optimal data format into the one the shell wants.
So clearly putting everything into a single data format wouldn't work. And in general, the fewer things I "mandate", the better. So my idea is this: tools can go on communicating with whatever encoding makes sense for them, but there should be some shared means of identifying what that encoding is. In order to do this without requiring, you know, every program in the world to be changed for compliance, there has to be a way to provide this information out-of-band - and, presumably, statically. That way, even if the binary itself has no provisions for working nicely in my shell, the end-user can work around that, without changing source code or recompiling, and without needing the authority to install such a workaround system-wide.
Of course, there's still all kinds of problems with this plan. Among other things, this new shell somehow has to provide a nice new environment, while simultaneously working nicely with things not made for it. For instance, if I provide my own version of "find" - do I have to give it a different name so it won't conflict with the GNU find everybody's used to running? There seems to be a never-ending supply of small problems that need to be solved before this design can really go anywhere. But if all goes well, then maybe someday I'll get it written and you'll give it a try.
|
http://slashdot.org/~Tetsujin/journal
|
CC-MAIN-2015-18
|
refinedweb
| 1,179
| 60.79
|
57
Take the simpliest type:
public class AdaptedOrder
{
public string BuysPrice { get; private set; }
}
System.Windows.Forms.ListBindingHelper.GetListItemProperties(typeof(AdaptedOrder), null); on .net 4.6.2 returns PropertyDescriptorCollection with single element - BuysPrice.
the same code runing on mono 5 returns around 70 properties.
It feels that mono returns all the properties of the Type<Type>, not AdaptedOrder itself.
Please check ready-to-compile source code at the following link, you can find the output of the program there:
This bug effectively leads that GridViews are rended with all the cells empty on mono when using custom Datasource of IBindingListView(Such as)
---
Windows 7 x64,
Mono JIT compiler version 5.0.0 (Visual Studio built mono)
ect.com
TLS: normal
SIGSEGV: normal
Notification: Thread + polling
Architecture: x86
Disabled: none
Misc: softdebug
LLVM: supported, not enabled.
GC: sgen
Just a sidenote, I was able to hack around this by copying ListBindingHelper from Microsoft sources, and using this ListBindingHelper instead of mono version, there is source code:
|
https://bugzilla.xamarin.com/57/57257/bug.html
|
CC-MAIN-2021-39
|
refinedweb
| 165
| 54.52
|
Code should be migrated from tr1 to std (does not compile on OS X 10.9)
Bug Description
Gearman does not compile on OS X 10.9.
According to Apple there are two ways to fix that (see below).
(There is a PR with a patch for this problem for the Homebrew package manager here:
https:/
A little background:
The tr1 headers were an experiment by the C++ standards committee, nothing more. They are not part of any standard. Apple is involved with the standards committee in an effort to make future committee experiments more obvious, and less likely to be mistaken for stable parts of a standard.
Additionally Apple is in the middle of transitioning from a gcc-based implementation of the std::lib (based on gcc-4.2) to a new-from-
Since 10.7/Lion, two implementations of the std::lib, the old gcc libstdc++, and this new llvm libc++ have been shipped.
With -lets say "newer"- OSes, the new libc++ is becoming the default used by the compiler clang.
This switch in the default std::lib is what's causing the symptom described in this ticket.
The older libstdc++ is still available and still has the same tr1 headers it always has.
The newer libc++ lacks the tr1 experiment. However most of tr1 was standardized with C++11, and now lives in namespace std, and in headers not prefixed with tr1/.
The C++ committee purposefully used the experimental std::tr1 namespace for the experiment so that they could (if need be) modify the tr1 components as they were standardized. And indeed this has happened. For the most part you will not notice any difference as you migrate from tr1 implementations to the C++11 std implementations. However there do exist a few corner cases. I would not worry about these corner cases. If you hit one, it will almost certainly come in the form of a compile-time error.
You are faced with two options:
1. Migrate your code from tr1 to std. I will show how to do this below. It is very easy. And it can be done in a manner in which your code is portable to both the old libstdc++ and the new libc++. This is the path "people at some company recommend".
2. Override the default std::lib choice and specifically choose the older gcc-4.2 based libstdc++. This is the easier path. But if this path is chosen, you are ultimately simply delaying the (relatively easy) work of doing step 1.
To override the default on the command line, add -stdlib=libstdc++ to both the compile and link command lines. You can also specifically choose the newer libc++ with -stdlib=libc++.
To do (1), the first step is to auto-detect which std::lib you are using. If you have already included any std header, you can do:
#ifdef _LIBCPP_VERSION
// using the new libc++
#else
// using the old libstdc++
#endif
If you have not yet included a std header, and need to include one gratuitously to find out whether or not it will define _LIBCPP_VERSION, do:
#include <ciso646> // detect std::lib
<ciso646> is a wonderful little C++ header that is specified to do absolutely nothing. So it is very cheap to include, and it will define _LIBCPP_VERSION if you are using the newer libc++, and otherwise won't.
Once you know which std::lib you are using, it becomes very easy to do things such as:
#ifdef _LIBCPP_VERSION
// using the new libc++
#include <memory>
typedef std::shared_
#else
// using the old libstdc++
#include <tr1/memory>
typedef std::tr1:
#endif
Once done, it's easy to switch between libstdc++ and libc++ for testing purposes.
New version was just released (seconds ago).
I've been using it on my Mac for a while now with no issues.
Thanks,
this is also working for me.
Any chance of a status update or a documented workaround for this?
It's currently a blocker to installing and using Gearman on Mavericks
Thanks in advance.
|
https://bugs.launchpad.net/gearmand/+bug/1236815
|
CC-MAIN-2015-32
|
refinedweb
| 670
| 72.56
|
1. Before you begin
This codelab teaches you how to use the WebGL-powered features of the Maps JavaScript API to control and render on the vector map in three dimensions.
Prerequisites
This codelab assumes you have intermediate knowledge of JavaScript and the Maps JavaScript API. To learn the basics of using the Maps JS API, try the Add a map to your website (JavaScript) codelab.
What you'll learn
- Generating a Map ID with the vector map for JavaScript enabled.
- Controlling the map with programmatic tilt and rotation.
- Rendering 3D objects on the map with
WebGLOverlayViewand Three.js.
- Animating camera movements with
moveCamera.
What you'll need
2. Get set up
For the enablement step below, you'll need to enable the Maps JavaScript API..
Node.js setup
If you don't already have it, go to to download and install the Node.js runtime on your computer.
Node.js comes with the npm package manager, which you need to install dependencies for this codelab.
Download the project starter template
Before you begin this codelab, do the following to download the starter project template, as well as the complete solution code:
- Download or fork the GitHub repo for this codelab at. The starter project is located in the
/starterdirectory and includes the basic file structure you need to complete the codelab. Everything you need to work with is located in the
/starter/srcdirectory.
- Once you download the starter project, run
npm installin the
/starterdirectory. This installs all of the needed dependencies listed in
package.json.
- Once your dependencies are installed, run
npm start.
Add your API key
The starter app includes all the code needed to load the map with the JS API Loader, so that all you need to do is provide your API key and Map ID. The JS API Loader is a simple library that abstracts the traditional method of loading the Maps JS API inline in the HTML template with a
script tag, allowing you to handle everything in JavaScript code.
To add your API key, do the following in the starter project:
- Open
app.js.
- In the
apiOptionsobject, set your API key as the value of
apiOptions.apiKey.
3. Generate and use a Map ID
To use the WebGL-based features of the Maps JavaScript API, you need a Map ID with the vector map enabled.
Generating a Map ID
- In the Google Cloud console, go to ‘Google Maps Platform' > ‘Map Management'.
- Click ‘CREATE NEW MAP ID'.
- In the ‘Map name' field, input a name for your Map ID.
- In the ‘Map type' dropdown, select ‘JavaScript'. ‘JavaScript Options' will appear.
- Under ‘JavaScript Options', select the ‘Vector' radio button, the ‘Tilt' checkbox, and the ‘Rotation' checkbox.
- Optional. In the ‘Description' field, enter a description for your API key.
- Click the ‘Next' button. The ‘Map ID Details' page will appear.
- Copy the Map ID. You will use this in the next step to the load the Map.
Using a Map ID
To load the vector map, you must provide a Map ID as a property in the options when you instantiate the Map. Optionally, you may also provide the same Map ID when you load the Maps JavaScript API.
To load the map with your Map ID, do the following:
- In
app.js, set your Map ID as the value of
apiOptions.map_ids.
Note that
map_idsis an array, where you can provide multiple Map IDs. In this codelab, you will provide only one. Providing Map IDs when the Maps JavaScript API is loaded allows Google Maps Platform to pre-optimize the loading of your map and any Map Styles associated with it, so that they are available when you instantiate the Map.
const apiOptions = { "apiKey": 'YOUR_API_KEY', "version": "beta", "map_ids": ["YOUR_MAP_ID"] };
- Set your Map ID as the value of
mapOptions.mapId.
Providing the Map ID when you instantiate the map tells Google Maps Platform which of your maps to load for a particular instance. You may reuse the same Map ID across multiple apps or multiple views within the same app.
const mapOptions = { "tilt": 0, "heading": 0, "zoom": 18, "center": { lat: 35.6594945, lng: 139.6999859 }, "mapId": "YOUR_MAP_ID" };
Check the app running in your browser. The vector map with tilt and rotation enabled should load successfully. To check whether tilt and rotation are enabled, hold the shift key and either drag with your mouse or use the arrow keys on your keyboard.
If the map does not load, check that you have provided a valid API key in
apiOptions. If the map does not tilt and rotate, check that you have provided a Map ID with tilt and rotation enabled in
apiOptions and
mapOptions.
Your
app.js file should now look like this:
import { Loader } from '@googlemaps/js-api-loader'; const apiOptions = { "apiKey": 'YOUR_API_KEY', "version": "beta", "map_ids": ["YOUR_MAP_ID"] }; const mapOptions = { "tilt": 0, "heading": 0, "zoom": 18, "center": { lat: 35.6594945, lng: 139.6999859 }, "mapId": "YOUR_MAP_ID" } async function initMap() { const mapDiv = document.getElementById("map"); const apiLoader = new Loader(apiOptions); await apiLoader.load(); return new google.maps.Map(mapDiv, mapOptions); } function initWebGLOverlayView (map) { let scene, renderer, camera, loader; // WebGLOverlayView code goes here } (async () => { const map = await initMap(); })();
4. Implement WebGLOverlayView
WebGLOverlayView gives you direct access to the same WebGL rendering context used to render the vector basemap. This means you can render 2D and 3D objects directly on the map using WebGL, as well as popular WebGL-based graphics libraries.
WebGLOverlayView exposes five hooks into the lifecycle of the WebGL rendering context of the map that you can use. Here's a quick description of each hook and what you should it them for:
onAdd(): Called when the overlay is added to a map by calling
setMapon a
WebGLOverlayViewinstance. This is where you should do any work related to WebGL that does not require direct access to the WebGL context.
onContextRestored(): Called when the WebGL context becomes available but before anything is rendered. This is where you should initialize objects, bind state, and do anything else that needs access to the WebGL context but can be performed outside the
onDraw()call. This allows you to set up everything you need without adding excess overhead to the actual rendering of the map, which is already GPU-intensive.
onDraw(): Called once per frame once WebGL begins rendering the map and anything else you've requested. You should do as little work as possible in
onDraw()to avoid causing performance issue in the rendering of the map.
onContextLost(): Called when the WebGL rendering context is lost for any reason.
onRemove(): Called when the overlay is removed from the map by calling
setMap(null)on a
WebGLOverlayViewinstance.
In this step, you'll create an instance of
WebGLOverlayView and implement three of its lifecycle hooks:
onAdd,
onContextRestored, and
onDraw. To keep things clean and easier to follow, all the code for the overlay will be handled in the
initWebGLOverlayView() function provided in the starter template for this codelab.
- Create a
WebGLOverlayView()instance.
The overlay is provided by the Maps JS API in
google.maps.WebGLOverlayView. To begin, create an instance by apending the following to
initWebGLOverlayView():
const webglOverlayView = new google.maps.WebGLOverlayView();
- Implement lifecycle hooks.
To implement the lifecycle hooks, append the following to
initWebGLOverlayView():
webglOverlayView.onAdd = () => {}; webglOverlayView.onContextRestored = ({gl}) => {}; webglOverlayView.onDraw = ({gl, coordinateTransformer}) => {};
- Add the overlay instance to the map.
Now call
setMap()on the overlay instance and pass in the map by appending the following to
initWebGLOverlayView():
webglOverlayView.setMap(map)
- Call
initWebGLOverlayView.
The last step is to execute
initWebGLOverlayView()by adding the following to the immediately invoked function at the bottom of
app.js:
initWebGLOverlayView(map);
Your
initWebGLOverlayView and immediately invoked function should now look like this:
async function initWebGLOverlayView (map) { let scene, renderer, camera, loader; const webglOverlayView = new google.maps.WebGLOverlayView(); webglOverlayView.onAdd = () => {} webglOverlayView.onContextRestored = ({gl}) => {} webglOverlayView.onDraw = ({gl, coordinateTransformer}) => {} webglOverlayView.setMap(map); } (async () => { const map = await initMap(); initWebGLOverlayView(map); })();
That's all you need to implement
WebGLOverlayView. Next, you'll set up everything you need to render a 3D object on the map using Three.js.
5. Set up a three.js scene
Using WebGL can be very complicated because it requires you to define all of the aspects of every object manually and then some. To make things much easier, for this codelab you'll use Three.js, a popular graphics library that provides a simplified abstraction layer on top of WebGL. Three.js comes with a wide variety of convenience functions that do everything from creating a WebGL renderer to drawing common 2D and 3D object shapes to controlling cameras, object transformations, and much more.
There are three basic object types in Three.js that are required to display anything:
- Scene: A "container" where all objects, light sources, textures, etc. are rendered and displayed.
- Camera: A camera that represents the viewpoint of the scene. Multiple camera types are available, and one or more cameras may be added to a single scene.
- Renderer: A renderer that handles the processing and displaying of all objects in the scene. In Three.js,
WebGLRendereris the most commonly used, but a few others are available as fallbacks in the event that the client does not support WebGL.
In this step, you'll load all the dependencies needed for Three.js and set up a basic scene.
- Load three.js
You'll need two dependencies for this codelab: the Three.js library and the GLTF Loader, a class that allows you to load 3D objects in the GL Trasmission Format (gLTF). Three.js offers specialized loaders for many different 3D object formats but using gLTF is recommended.
In the code below, the entire Three.js library is imported. In a production app you would likely want to import just the classes you need, but for this codelab, import the entire library to keep things simple. Notice also that the GLTF Loader is not included in the default library, and needs to be imported from a separate path in the dependency - this is the path where you can access all of the loaders provided by Three.js.
To import Three.js and the GLTF Loader, add the following to the top of
app.js:
import * as THREE from 'three'; import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader.js';
- Create a three.js scene.
To create a scene, instantiate the Three.js
Sceneclass by appending the following to the
onAddhook:
scene = new THREE.Scene();
- Add a camera to the scene.
As mentioned earlier, the camera represents the viewing perspective of the scene, and determines how Three.js handles the visual rendering of objects within a scene. Without a camera, the scene is effectively not "seen", meaning that objects won't be appear because they won't be renderered.
Three.js offers a variety of different cameras that effect how the renderer treats objects with respect to things like perspective and depth. In this scene, you'll use the
PerspectiveCamera, the most commonly used camera type in Three.js, which is designed to emulate the way the human eye would perceive the scene. This means objects farther away from the camera will appear smaller than objects that are closer, the scene will have a vanishing point, and more.
To add a perspective camera to the scene, append the following to the
onAddhook:
With
camera = new THREE.PerspectiveCamera();
PerspectiveCamera, you are also able to configure the attributes that make up the viewpoint, including the near and far planes, aspect ratio, and field of vision (fov). Collectively, these attributes make up what is known as the viewing frustum, an important concept to undertand when working in 3D, but outside the scope of this codelab. The default
PerspectiveCameraconfiguration will suffice just fine.
- Add light sources to the scene.
By default, objects rendered in a Three.js scene will appear black, regardless of the textures applied to them. This is because a Three.js scene mimics how objects act in the real world, where the visibility of color depends on light reflecting off an object. In short, no light, no color.
Three.js provides a variety of different types of lights of which you'll use two:
AmbientLight: Provides a diffuse light source that evenly lights all objects in the scehe from all angles. This will give the scene a baseline amount of light to ensure the textures on all objects are visible.
DirectionalLight: Provides a light originating from a direction in the scene. Unlike how a positioned light would operate in the real world, the light rays that eminate from
DirectionalLightare all parallel and do not spread and diffuse as they get farther from the light source.
You may configure the color and intensity of each light to create aggregate lighting effects. For example, in the code below, the ambient light provides a soft white light for the entire scene, while the directional light provides a secondary light that hits objects at a downward angle. In the case of the directional light, the angle is set using
position.set(x, y ,z), where each value is relative to the respective axis. So, for example,
position.set(0,1,0)would position the light directly above the scene on the y-axis pointing straight down.
To add the light sources to the scene, append the following to the
onAddhook:
const ambientLight = new THREE.AmbientLight( 0xffffff, 0.75 ); scene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 0.25); directionalLight.position.set(0.5, -1, 0.5); scene.add(directionalLight);
Your
onAdd hook should now look like this:
webglOverlayView.onAdd = () => { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(); const ambientLight = new THREE.AmbientLight( 0xffffff, 0.75 ); scene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 0.25); directionalLight.position.set(0.5, -1, 0.5); scene.add(directionalLight); }
Your scene is now set up and ready to render. Next, you'll configure the WebGL renderer and render the scene.
6. Render the scene
Time to render your scene. Up to this point, everything you've created with Three.js is initialized in code, but is essentially non-existent because it hasn't yet been rendered into the WebGL rendering context. WebGL renders 2D and 3D content in the browser using the canvas API. If you've used the Canvas API before, you're probably familiar with the
context of an HTML canvas, which is where everything is rendered. What you may not know is that this is an interface that exposes the OpenGL graphics rendering context via the
WebGLRenderingContext API in the browser.
To make dealing with the WebGL renderer easier, Three.js provides
WebGLRenderer, a wrapper that makes it relatively easy to configure the WebGL rendering context so that Three.js can render scenes in the browser. In the case of the map, however, it's not enough to just render the Three.js scene in the browser alongside the map. Three.js must render into the exact same rendering context as the map, so that both the map and any objects from the Three.js scene are rendered into the same world space. This makes it possible for the renderer to handle interactions between objects on the map and objects in the scene, such as occlusion, which is a fancy way of saying an object will hide objects behind it from view.
Sounds pretty complicated, right? Luckily, Three.js comes to the rescue again.
- Set up the WebGL renderer.
When you create a new instance of the Three.js
WebGLRenderer, you may provide it the specific WebGL rendering context you want it to render your scene into. Remember the
glargument that gets passed into the
onContextRestoredhook? That
globject is the WebGL rendering context of the map. All you need to do is provide the context, its canvas, and its attributes to the
WebGLRendererinstance, all of which are available via the
globject. In this code, the
autoClearproperty of the renderer is also set to
falseso that the renderer does not clear its output every frame.
To configure the renderer, append the following to the
onContextRestoredhook:
renderer = new THREE.WebGLRenderer({ canvas: gl.canvas, context: gl, ...gl.getContextAttributes(), }); renderer.autoClear = false;
- Render the scene.
Once the renderer is configured, call
requestRedrawon the
WebGLOverlayViewinstance to tell the overlay that a redraw is needed when the next frame renders, then call
renderon the renderer and pass it the Three.js scene and camera to render. Lastly, clear the state of the WebGL rendering context. This is an important step to avoid GL state conflicts, since usage of WebGL Overlay View relies on shared GL state. If the state is not reset at the end of every draw call, GL state conflicts may cause the renderer to fail.
To do this, append the following to the
onDrawhook so that it is executed each frame:
webglOverlayView.requestRedraw(); renderer.render(scene, camera); renderer.resetState();
Your
onContextRestored and
onDraw hooks should now look like this:
webglOverlayView.onContextRestored = ({gl}) => { renderer = new THREE.WebGLRenderer({ canvas: gl.canvas, context: gl, ...gl.getContextAttributes(), }); renderer.autoClear = false; } webglOverlayView.onDraw = ({gl, transformer}) => { webglOverlayView.requestRedraw(); renderer.render(scene, camera); renderer.resetState(); }
7. Render a 3D model on the map
Ok, you've got all the pieces in place. You've set up WebGl Overlay View and created a Three.js scene, but there's one problem: there's nothing in it. So next, it's time to render a 3D object in the scene. To do this, you'll use the GLTF Loader you imported earlier.
3D models come in many different formats, but for Three.js the gLTF format is the preferred format due to its size and runtime performance. In this codelab, a model for you to render in the scene is already provided for you in
/src/pin.gltf.
- Create a model loader instance.
Append the following to
onAdd:
loader = new GLTFLoader();
- Load a 3D model.
Model loaders are asynchronous and execute a callback once the model has fully loaded. To load
pin.gltf, append the following to
onAdd:
const source = "pin.gltf"; loader.load( source, gltf => {} );
- Add the model to the scene.
Now you can add the model to the scene by appending the following to the
loadercallback. Note that
gltf.sceneis being added, not
gltf:
scene.add(gltf.scene);
- Configure the camera projection matrix.
The last thing you need to make the model render properly on the map is to set the projection matrix of the camera in the Three.js scene. The projection matrix is specified as a Three.js
Matrix4array, which defines a point in three dimensional space along with transformations, such as rotations, shear, scale, and more.
In the case of
WebGLOverlayView, the projection matrix is used to tell the renderer where and how to render the Three.js scene relative to the basemap. But there's a problem. Locations on the map are specified as latitude and longitude coordinate pairs, whereas locations in the Three.js scene are
Vector3coordinates. As you might have guessed, calculating the conversion between the two systems is not trivial. To solve this,
WebGLOverlayViewpasses a
coordinateTransformerobject to the
OnDrawlifecycle hook that contains a function called
fromLatLngAltitude.
fromLatLngAltitudetakes a
LatLngor
LatLngLiteralobject, an altitude above the ground plane, and optionally a set of arguments that define a transformation for the scene, then coverts them to a model view projection (MVP) matrix for you. All you have to do is specify where on the map you want the Three.js scene to be rendered, as well as how you want it transformed, and
WebGLOverlayViewdoes the rest. You may then convert the MVP matrix to a Three.js
Matrix4array and set the camera projection matrix to it.
In the code below, the second argument tells WebGl Overlay View to set the altitude of the Three.js scene 120 meters above the ground, which will make the model appear to float.
To set the camera projection matrix, append the following to the
onDrawhook:
const matrix = coordinateTransformer.fromLatLngAltitude(mapOptions.center, 120); camera.projectionMatrix = new THREE.Matrix4().fromArray(matrix);
- Transform the model.
You'll notice that the pin is not sitting perpendicular to the map. In 3D graphics, in addition to the world space having its own x, y, and z axes that determine orientation, each object also has its own object space with an independent set of axes.
In the case of this model, it was not created with what we would normally consider the ‘top' of the pin facing up the y-axis, so you need to transform the object to orient it the desired way relative to the world space by calling
rotation.seton it. Note that in Three.js, rotation is specified in radians, not degrees. It's generally easier to think in degrees, so the appropriate conversion needs to be made using the formula
degrees * Math.PI/180.
In addition, the model is a bit small, so you'll also scale it evenly on all axes by calling
scale.set(x, y ,z).
To rotate and scale the model, add the following in the
loadercallback of
onAddbefore
scene.add(gltf.scene)which adds the gLTF to the scene:
gltf.scene.scale.set(25,25,25); gltf.scene.rotation.x = 180 * Math.PI/180;
Now the pin sits upright relative to the map.
Your
onAdd and
onDraw hooks should now look like this:
webglOverlayView.onAdd = () => { scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera(); const ambientLight = new THREE.AmbientLight( 0xffffff, 0.75 ); // soft white light scene.add( ambientLight ); const directionalLight = new THREE.DirectionalLight(0xffffff, 0.25); directionalLight.position.set(0.5, -1, 0.5); scene.add(directionalLight); loader = new GLTFLoader(); const source = 'pin.gltf'; loader.load( source, gltf => { gltf.scene.scale.set(25,25,25); gltf.scene.rotation.x = 180 * Math.PI/180; scene.add(gltf.scene); } ); } webglOverlayView.onDraw = (gl, transformer) => { const matrix = transformer.fromLatLngAltitude(mapOptions.center, 120); camera.projectionMatrix = new THREE.Matrix4().fromArray(matrix); webglOverlayView.requestRedraw(); renderer.render(scene, camera); renderer.resetState(); }
Next up is camera animations!
8. Animate the camera
Now that you've rendered a model on the map and can move everything three dimensionally, the next thing you're likely to want to do is control that movement programmatically. The
moveCamera function allows you to set the center, zoom, tilt, and heading properties of the map simultaneously, giving you fine grain control over the user experience. In addition,
moveCamera can be called in an animation loop to create fluid transitions between frames at a framerate of nearly 60 frames per second.
- Wait for the model to load.
To create a seamless user experience, you'll want to wait to start moving the camera until after the gLTF model is loaded. To do this, append the loader's
onLoadevent handler to the
onContextRestoredhook:
loader.manager.onLoad = () => {}
- Create an animation loop.
There's more than one way to create an animation loop, such as using
setIntervalor
requestAnimationFrame. In this case, you'll use the
setAnimationLoopfunction of the Three.js renderer, which will automatically call any code you declare in its callback each time Three.js renders a new frame. To create the animation loop, add the following to the
onLoadevent handler in the previous step:
renderer.setAnimationLoop(() => {});
- Set the camera position in the animation loop.
Next, call
moveCamerato update the map. Here, properties from the
mapOptionsobject that was used to load the map are used to define the camera position:
map.moveCamera({ "tilt": mapOptions.tilt, "heading": mapOptions.heading, "zoom": mapOptions.zoom });
- Update the camera each frame.
Last step! Update the
mapOptionsobject at the end of each frame to set the camera position for the next frame. In this code, an
ifstatement is used to increment the tilt until the maximum tilt value of 67.5 is reached, then the heading is changed a bit each frame until the camera has completed a full 360 degree rotation. Once the desired animation is complete,
nullis passed to
setAnimationLoopto cancel the animation so that it doesn't run forever.
if (mapOptions.tilt < 67.5) { mapOptions.tilt += 0.5 } else if (mapOptions.heading <= 360) { mapOptions.heading += 0.2; } else { renderer.setAnimationLoop(null) }
Your
onContextRestored hook should now look like this:
webglOverlayView.onContextRestored = ({gl}) => { renderer = new THREE.WebGLRenderer({ canvas: gl.canvas, context: gl, ...gl.getContextAttributes(), }); renderer.autoClear = false; loader.manager.onLoad = () => { renderer.setAnimationLoop(() => { map.moveCamera({ "tilt": mapOptions.tilt, "heading": mapOptions.heading, "zoom": mapOptions.zoom }); if (mapOptions.tilt < 67.5) { mapOptions.tilt += 0.5 } else if (mapOptions.heading <= 360) { mapOptions.heading += 0.2; } else { renderer.setAnimationLoop(null) } }); } }
9. Congratulations
If everything went according to plan, you should now have a map with a large 3D pin that looks like this:
What you learned
In this codelab you've learned a bunch of stuff; here are the highlights:
- Implementing
WebGLOverlayViewand its lifecycle hooks.
- Integrating Three.js into the map.
- The basics of creating a Three.js scene, including cameras and lighting.
- Controlling and animating the camera for the map using
moveCamera.
What's next?
WebGL, and computer graphics in general, is a complex topic, so there's always lots to learn. Here are a few resources to get you started:
- WebGL Overlay View documentation
- Getting started with WebGL.
- Three.js documentation
- Help us create the content that you would find most useful by answering the question below: «codelabs/maps-platform/shared/_next-lab-survey.lab.md» Is the codelab you want not listed above? Request it with a new issue here.
|
https://developers.google.cn/codelabs/maps-platform/webgl?hl=hi
|
CC-MAIN-2022-05
|
refinedweb
| 4,209
| 58.79
|
Creating a Custom HTTP Client
The AWS SDK for Go uses a default HTTP client with default configuration values. Although you can change some of these configuration values, the default HTTP client and transport are not sufficiently configurable for customers using the AWS SDK for Go in an environment with high throughput and low latency requirements. This section describes how to create a custom HTTP client, and use that client to create AWS SDK for Go calls.
To assist you in creating a custom HTTP client, this section describes how to create a structure to encapsulate the custom settings, create a function to create a custom HTTP client based on those settings, and use that custom HTTP client to call an AWS SDK for Go service client.
Let’s define what we want to customize.
Dialer.KeepAlive
This setting represents the keep-alive period for an active network connection.
Set to a negative value to disable keep-alives.
Set to 0 to enable keep-alives if supported by the protocol and operating system.
Network protocols or operating systems that do not support keep-alives ignore this field. By default, TCP enables keep alive.
See
We’ll call this
ConnKeepAlive as time.Duration.
Dialer.Timeout
This setting represents the maximum amount of time a dial to wait for a connection to be created.
Default is 30 seconds.
See
We’ll call this
Connect as time.Duration.
Transport.ExpectContinueTimeout
This setting represents the maximum amount of time to wait for a server’s first response headers after fully writing the request headers, if the request has an “Expect: 100-continue” header. This time does not include the time to send the request header. The HTTP client sends its payload after this timeout is exhausted.
Default 1 second.
Set to 0 for no timeout and send request payload without waiting. One use case is when you run into issues with proxies or third party services that take a session similar to the use of Amazon S3 in the function shown later.
See
We’ll call this
ExpectContinue as time.Duration.
Transport.IdleConnTimeout
This setting represents the maximum amount of time to keep an idle network connection alive between HTTP requests.
Set to 0 for no limit.
See
We’ll call this
IdleConn as time.Duration.
Transport.MaxIdleConns
This setting represents the maximum number of idle (keep-alive) connections across all hosts. One use case for increasing this value is when you are seeing many connections in a short period from the same clients
0 means no limit.
See
We’ll call this
MaxAllIdleConns as int.
Transport.MaxIdleConnsPerHost
This setting represents the maximum number of idle (keep-alive) connections to keep per-host. One use case for increasing this value is when you are seeing many connections in a short period from the same clients
Default is two idle connections per host.
Set to 0 to use DefaultMaxIdleConnsPerHost (2).
See
We’ll call this
MaxHostIdleConns as int.
Transport.ResponseHeaderTimeout
This setting represents the maximum amount of time to wait for a client to read the response header.
If the client isn’t able to read the response’s header within this duration, the request fails with a timeout error.
Be careful setting this value when using long-running Lambda functions, as the operation does not return any response headers until the Lambda function has finished or timed out. However, you can still use this option with the InvokeAsync API operation.
Default is no timeout; wait forever.
See
We’ll call this
ResponseHeader as time.Duration.
Transport.TLSHandshakeTimeout
This setting represents the maximum amount of time waiting for a TLS handshake to be completed.
Default is 10 seconds.
Zero means no timeout.
See
We’ll call this
TLSHandshake as time.Duration.
Create Import Statement
The complete example imports the following Go packages.
import ( "bytes" "context" "flag" "fmt" "io" "net" "net/http" "time" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" "golang.org/x/net/http2" )
Creating a Timeout Struct
Let’s create a struct to hold the timeout values we want to be able to set on our HTTP client.
type HTTPClientSettings struct { Connect time.Duration ConnKeepAlive time.Duration ExpectContinue time.Duration IdleConn time.Duration MaxAllIdleConns int MaxHostIdleConns int ResponseHeader time.Duration TLSHandshake time.Duration }
Creating a Function to Create a Custom HTTP Client
Next let’s create a function that takes a ClientTimeout struct and creates a custom HTTP client based on those timeout values.
func NewHTTPClientWithSettings(httpSettings HTTPClientSettings) (*http.Client, error) { var client http.Client tr := &http.Transport{ ResponseHeaderTimeout: httpSettings.ResponseHeader, Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ KeepAlive: httpSettings.ConnKeepAlive, DualStack: true, Timeout: httpSettings.Connect, }).DialContext, MaxIdleConns: httpSettings.MaxAllIdleConns, IdleConnTimeout: httpSettings.IdleConn, TLSHandshakeTimeout: httpSettings.TLSHandshake, MaxIdleConnsPerHost: httpSettings.MaxHostIdleConns, ExpectContinueTimeout: httpSettings.ExpectContinue, } // So client makes HTTP/2 requests err := http2.ConfigureTransport(tr) if err != nil { return &client, err } return &http.Client{ Transport: tr, }, nil }
Using a Custom HTTP Client
Let’s create a custom HTTP client and use it to create an Amazon S3 client.
The following example creates an http.Client that is configured to have:
a five second TCP connection timeout
a five second TLS handshake timeout
a five second wait for the HTTP response headers
httpClient, err := NewHTTPClientWithSettings(HTTPClientSettings{ Connect: 5 * time.Second, ExpectContinue: 1 * time.Second, IdleConn: 90 * time.Second, ConnKeepAlive: 30 * time.Second, MaxAllIdleConns: 100, MaxHostIdleConns: 10, ResponseHeader: 5 * time.Second, TLSHandshake: 5 * time.Second, }) if err != nil { fmt.Println("Got an error creating custom HTTP client:") fmt.Println(err) return } sess := session.Must(session.NewSession(&aws.Config{ HTTPClient: httpClient, })) svc := s3.New(sess)
All of these settings give the client approximately 15 seconds create a connection, do a TLS handshake, and receive the response headers from the service. The time that the client takes to read the response body is not covered by these timeouts. To specify a total timeout for the request to include reading the response body, use the AWS SDK for Go client’s WithContext API operation methods, such as the Amazon S3 operation PutObjectWithContext with a context.Withtimeout.
The following example uses a timeout context to limit the total time an API request can be active to a maximum of 20 seconds. The SDK must be able to read the full HTTP response body (Object body) within the timeout or the SDK returns a timeout error. For API operations that return an io.ReadCloser in their response type, the Context’s timeout includes reading the content from the io.ReadCloser.
ctx, cancelFn := context.WithTimeout(context.TODO(), 20*time.Second) defer cancelFn() resp, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ Bucket: bucket, Key: object, }) if err != nil { return body, err } return resp.Body, nil
See the complete example
|
https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/custom-http.html
|
CC-MAIN-2020-50
|
refinedweb
| 1,127
| 51.75
|
to the rigidbody.
The force is specified as two separate components in the X and Y directions (there is no Z direction in 2D physics). The object will be accelerated by the force according to the law force = mass x acceleration - the larger the mass, the greater the force required to accelerate to a given speed.
See Also: AddForceAtPosition, AddTorque, mass, velocity,, AddForce, ForceMode2D.
#pragma strict
var thrust : float; var rb : Rigidbody2D;
function Start () { rb = GetComponent.<Rigidbody2D>(); }
function Update () { rb.AddForce(transform.up * thrust); }
using UnityEngine;
public class Example : MonoBehaviour { public float thrust; public Rigidbody2D rb;
void Start() { rb = GetComponent<Rigidbody2D>(); }
void FixedUpdate() { rb.AddForce(transform.up * thrust); } }
Did you find this page useful? Please give it a rating:
|
https://docs.unity3d.com/2017.3/Documentation/ScriptReference/Rigidbody2D.AddForce.html
|
CC-MAIN-2019-18
|
refinedweb
| 119
| 58.99
|
Behringer Xenyx1002B
upgrad... Read more
Details
Brand: BEHRINGER
Part Numbers: 000-00402-00000, 000-A0402-00000, 1002B, 1002b, X1002B
UPC: 04033653021098, 4033653021098
[ Report abuse or wrong photo | Share your Behringer Xenyx1002B photo ]
Manual
Preview of first few manual pages (at low quality). Check before download. Click to enlarge.
Behringer Xenyx1002B
Video review
behringer xenyx 1002b mixer kam khd2000
User reviews and opinions
No opinions have been provided. Be the first and add a new opinion/review.
Documents
User Manual
XENYX 1002B
Ultra low-noise design, 10-input, 2-bus mic/line mixer with optional battery operation
Thank you
Thank you for choosing the XENYX 1002B 10 input mixer. This mixer is packed with features like ultra low-noise XENYX mic preamps, neo-classic British 3-band EQs, and stereo channels that allow simultaneous mic and line input use, as well as both monitor and FX sends on each channel. The 1002B can also operate on battery power, a unique feature that allows you to record or perform on the go or outdoors. The 1002B delivers everything you expect from a powerful, small-format mixer. From broadcasting and video dubbing to full band performance and recording, this versatile piece of gear works wonders in a variety of applications.
Table of Contents
Thank you... 1 Important Safety Instructions. 2 1. Before You Get Started.. 3 2. Audio Connections.. 4 3. Controls and Connectors.. 5 4. Gain Setting.. 6 5. Applications... 8 6. Specifications... 9 Limited waranty... 11. Legal Disclaimer.. 12
This manual is available in English, German, Spanish and Chinese. Download them by going to the appropriate product page at:
XENYX 1002B User Manual
Important Safety Instructions
[6] Clean only with dry cloth. [7] not block any ventilation openings. Install in accordance Do
with the manufacturers instructions.
[8] not install near any heat sources such as radiators, heat Do
* * ! ! ! !
registers, stoves, or other apparatus (including amplifiers) that produce heat.
[9] not defeat the safety purpose of the polarized or sucient magnitude to constitute risk of electric shock. Use only high-quality commercially-available speaker cables with " TS plugs pre-installed. All other installation or modification should be performed only by qualified personnel.
sucient to constitute a risk of shock.
{11} apparatus shall be connected to a MAINS socket outlet The.
{13} use attachments/accessories specified by the Only
manufacturer.
{14} only with the cart, stand, tripod, bracket, Use.
[1] these instructions. Read [2] Keep these instructions. [3] Heed all warnings. [4] Follow all instructions. [5] not use this apparatus near water. Do
1. Before You Get Started
1.1 Shipment
Your XENYX 1002.3 Basic Operation
1.2!
The XENYX 1002B is easy to use. Simply follow these steps to achieve the best possible sound: 1. Plug the included power cable into the back of the mixer. Plug the other end of the cable into a mains outlet. DO NOT turn the mixer on yet. 2. Make all appropriate audio connections: Connect microphones to the MIC jacks using XLR cables. Connect line-level sources to the LINE IN jacks using " TS cables. Connect stereo sources (keyboard, drum machine) to one of the stereo LINE IN jacks using a pair of " TS cables. Connect a CD player to the 2 TRACK INPUT using " or RCA cables. See Applications chapter for more details and options. 3. Connect a monitoring source or speaker system. You may connect powered studio monitors, powered loudspeakers or a power amp to the MAIN OUTPUT jacks. You may also connect a pair of headphones to the PHONES jack. Leave powered speakers and/or power amps turned off until the mixer has been powered on. 4. Turn all PAN/BAL and EQ knobs to their center (12 oclock) position. Set all other knobs and faders all the way down/off. 5. Once all connections have been made, you may turn the mixer on. 6. After the mixer is turned on, you may also turn the speakers or power amp on. 7. Set the input gain level for each channel using the GAIN knob. While testing the audio source, turn the GAIN knob as high as possible without allowing the CLIP LED to light. See the Gain Setting section for details. 8. Raise the MAIN fader to 0. You may adjust it further as you begin to set levels. 9. Adjust all channel volume faders until you achieve a balanced mix. 10. Make sure that the channel CLIP LEDs and MAIN CLIP LEDs do not light frequently. If this happens, adjust the respective GAIN or MAIN fader accordingly. 11. Congratulations! You have now set up a basic mix! The 1002B offers many other cool features as well, so continue through the manual to make the most out of this powerful little mixer.
Strain relief clamp Sleeve Tip 3 Sleeve (ground/shield)
2. Audio Connections
1 = ground/shield 2 = hot (+ve) 3 = cold (-ve) output
Tip (signal)
Unbalanced " TS connector
Fig. 2.3: " Unbalanced
For unbalanced use, pin 1 and pin 3 have to be bridged
Balanced use with XLR connectors
tip sleeve shield sleeve
Fig. 2.1: XLR Balanced
strain relief clamp sleeve ring tip
Fig. 2.4: RCA
sleeve ground/shield sleeve ground/shield
ring cold (-ve) tip hot (+ve)
For connection of balanced and unbalanced plugs, ring and sleeve have to be bridged at the stereo plug.
ring return (in) tip send (out)
Connect the insert send with the input and the insert return with the output of the effects device.
Balanced 1/ TRS connector 4"
Fig. 2.2: " Balanced
Insert send return 1/ TRS connector 4"
Fig. 2.5: Insert cable
3. Controls and Connectors
3.1 Front Panel
[1] MIC Plug a microphone into this input using an XLR cable. [2] LINE IN Plug a line-level source into this jack using a " [3] INS(ERT) Plug an external dynamic processor into this
TS or TRS cable.
[5] [6] [7] [8]
jack using a TRS to dual TS cable. You may also use the INSERT jack as a pre-EQ/pre-fader send by plugging in a " TS cable part way to the first click. STEREO LINE IN Plug in a stereo source using two " TS cables, or a single line-level source using the left input jack only. GAIN LINE Adjusts STEREO LINE IN sensitivity, also known as gain setting. GAIN MIC Adjusts MIC input sensitivity, also known as gain setting. CLIP Lights when preamp begins to overload. PAN/BAL Adjusts the left-to-right positioning of the
[9] [10] [11] [12] [13] [14] [15] [16] [17]
channel in the stereo field. HIGH Adjusts frequencies above 10 kHz by +- 15 dB. MID Adjusts frequencies peaking at 700 Hz by +- 15 dB. LOW Adjusts frequencies below 50 Hz by +- 15 dB. MON Adjusts the amount of signal sent to the MON SEND jack. This signal is sent pre-fader. FX Adjusts the amount of signal sent to the FX SEND jack. This signal is sent post-fader. CHANNEL FADER Adjusts the channel volume in the main mix. 2-TRACK OUTPUT Connect to the inputs of recording device using RCA cables. 2-TRACK INPUT Connect to outputs of CD, tape or MP3 player using RCA or " cables. PHONES Connect a pair of headphones with a " TRS plug.
[18] MAIN OUTPUT Connect to the inputs of a power amp or [19] FX SEND Connect to the input of an external effects [20] MON SEND Connect to the input of a powered monitor or [21] VU CLIP Lights when the MAIN OUTPUT signal begins [22] PHANTOM Sends 23V of power to the XLR MIC inputs
XENYX 1002B User Manual for use with condenser microphones. When used with batteries, 18V of power is supplied. VU METER Displays the MAIN OUTPUT signal level. MON SEND Adjusts the output at the MON SEND jack. FX SEND Adjusts the output at the FX SEND jack. PHONES Adjusts the output at the PHONES jack. MAIN FADER Adjusts the overall output of the mixer through the MAIN OUTPUTS. It also affects the signal at the PHONES out and 2-TRACK OUTPUT.
powered speakers using " TS cables. device using a " TS cable.
monitor power amp using a " TS cable. to overload.
[23] [24] [25] [26] [27]
3.2 Rear Panel
[28] AC POWER IN Connect the mains power cable into
this input. [29] POWER ON Turns the mixers power on and off.
4. Gain Setting
It is very important to set each channels GAIN knob correctly in order to get the maximum amount of signal headroom and least amount of noise possible. Setting the GAIN too low could make that channel too quiet to mix properly, while setting it too high will cause clipping and distortion. Stereo channels 3/4, 5/6 and 7/8 allow the MIC and LINE inputs to be used in parallel thanks to the dedicated GAIN knobs for each input. Follow these instructions to set the gain for each channel and situation: Plug the audio source into the channel input (XLR or "). Sing into the microphone or play the line-level source at the volume you will ultimately use during recording or performance. If you set the gain for a vocal mic by saying check into it, this gain setting will probably not be as loud as the actual vocal performance. Setting the gain this way will lead you to set the gain too high, which may cause the extra loud vocal performance to overload and distort. Likewise, if checking a mic that will record a saxophone, make sure the performer plays close to the mic while setting the gain. For keyboards, do not change the output volume of the keyboard after the mixers gain has been set. Turn the GAIN knob clockwise until the red CLIP LED lights
up. This means the channel has begun to overload (too much signal is allowed in). Turn the GAIN knob counterclockwise a small amount, then sing or play again. Ideally, the GAIN knob should be set as high as possible while allowing the CLIP LED to only light occasionally, if at all. If you must use both the MIC and LINE inputs on channels 3/4, 5/6, or 7/8, you can adjust the gain setting for each source individually thanks to the dedicated GAIN knobs. The channel fader affects the level of both sources, so achieving a good balance between the 2 inputs can be tricky. Set the gain for the MIC input using the GAIN MIC as described above. Set the gain for the LINE input(s) using the GAIN LINE as described above. Both GAIN knobs share the same CLIP LED, so when both sources are in use at the same time, neither input should cause the LED to light. If this happens, turn each GAIN knob down one at a time to determine which is overloading. Raise the channel fader so that both sources are audible in the overall mix. Ideally, they will already be balanced and not require further adjustment. If one source is too quiet with the fader turned up, turn the louder sources GAIN knob down a bit, then raise the fader to the appropriate level. DO NOT simply turn the quiet sources GAIN knob up until it is loud enough, as this will likely cause clipping and distortion.
4.1 Using External Effects
The 1002B lets you use external effects processors to add a touch of reverb, delay, or other effects to various channels. Use the channel FX knobs, FX SEND knob and FX SEND jack to send a portion of the signal from several channels to an effects processor. You can insert the wet signal back into the mix through one of the stereo channels. The FX signal from each channel is sent post-fader, meaning that as you change the channels volume, you also change how much of that channels signal is sent to the effects processor. This ensures that the mix of wet and dry signal remains the same as you adjust the channel volume. Follow these steps to incorporate external effects in your mix: Connect a " TS cable from the FX SEND jack to the input of the effects processor. If you would like the effects to operate in stereo, connect " cables from the left and right outputs of the processor to one of the stereo input channels on the 1002B. For mono operation, most processors return a mono signal through the left output. This mono signal should then be routed into the left input on one of the mixer channels. If possible, use channel 9/10 since it only allows line inputs. Turn the FX SEND knob to the center (12 oclock) position. Turn the channel FX knob up for each source to which you would like to apply effects. For example, you can add a lot of reverb to a vocal mic, while only adding a small amount to a snare drum. This will just be a preliminary setting as you will not be able to hear the effect yet. Keep the knobs around the center position; you will fine-tune them shortly. Adjust the input gain for the channel receiving the output from the effects processor. (See the Gain Setting section for details.) Turn the channel fader up to 0 on the channel receiving the signal back from the processor. DO NOT turn the FX knob on that channel up at all! Your sound system will become haunted with screaming banshees. You should now hear the selected effect on the channels that are sending signal to the processor. Adjust the channel FX knobs to get the effect mix just right. NOTE: The processor will likely have its own VU meters to monitor the incoming signal level. If the processors meter begins clipping, turn down the FX SEND knob on the 1002B. See the Applications section for details.
4.2 Creating a Monitor Mix
For live applications, audio engineers often send different mixes to the audience and to the performing musicians. To allow this, the 1002B is equipped with a dedicated monitor send bus. Each channel features a MON knob that sends a pre-fader signal to the MON OUT jack, allowing the channels volume fader to be adjusted without affecting the monitor mix. The signal can also be used as a second effects send. Follow these steps to set up a basic monitor mix: Make sure the powered monitor speaker or power amp is turned off. Connect a " TS cable from the MON OUT jack to the powered speaker or power amp. Turn on the powered speaker or power amp, and then turn the volume up about half way. Turn the MON SEND knob to the center (12 oclock) position. This setting may need to be adjusted later depending on volume requirements. As the musicians begin to play, turn each channels MON knob up slowly until each source is audible in the monitor mix. It may take some time to get a balanced mix that all the musicians are happy with. If possible, avoid turning a channels MON knob much past the center position. Do not point the monitor speakers directly at a microphone, as this will likely cause feedback. See the Applications section for details. As previously stated, the MON SEND jack can also be used as a second effects send. This application requires a similar setup to the normal effects send, but since the signal from each channel is sent pre-fader using the MON knob, adjustments to the channels volume will affect the mix of wet and dry effect signal. Therefore, if you alter a channels volume during the performance, you must also adjust that channels MON knob. NOTE: When using the MON SEND for effects, if you neglect to change a channels MON knob while turning that channels volume fader all the way down, you will still hear the effected signal coming through the mix. This problem happens because the signal routes pre-fader, but the normal FX SEND bus will not experience this issue.
4.3 Battery Installation
The 1002B can be powered by three 9V batteries. This feature allows you, for example, to capture a high-quality recording while sitting on the beach with your laptop. Youre no longer tethered by an electrical outlet. You can still record with condenser mics thanks to the 18V of phantom power supplied by two of the batteries. Follow these steps to install the batteries: Open the battery compartment located on the underside of the mixer. You will need to remove a small screw with a Phillips screwdriver. Slide the compartment cover out. There are slots for three batteries inside the compartment. Insert the batteries so that the + and poles are in the correct position. Replace the cover and tighten the screw. The battery power will last approximately four hours using highquality alkaline batteries.
XM1800S
DI100 DI100
HPS5000
XENYX1002B
F1220A
5. Applications
UL2000M MP3 Player B212A B212A
Fig.5.2: Live Small Combo
UCA222
Fig.5.1: Field Recording
DSP2024P DSP2024P B-1 XM1800S
6. Specifications
Mono inputs
Microphone inputs (XENYX Mic preamp) Type XLR connector, electronically balanced, discrete input circuit
B2031A
Mic E.I.N.1 (20Hz - 20kHz) @ 0 source resistance @ 50 source resistance @ 150 source resistance Frequency response (1 dB) Frequency response (3 dB) Gain range Max. input level Impedance Signal-to-noise ratio Distortion (THD+N)
-134 dB 135.7 dB A-weighted -131 dB 133.3 dB A-weighted -129 dB 130.5 dB A-weighted <10 Hz - 160 kHz (-1 dB) <10 Hz - 200 kHz (-3 dB) +14 dB to +60 dB +12 dBu @ +10 dB GAIN 2.6 k Ohms balanced 120 dB A-weighted (0 dBu In @ +22 dB GAIN) 0.005% / 0.004% A-weighted " TRS jack, electronically balanced 20 k Ohms balanced, 10 k Ohms unbalanced -10 dB to +40 dB +22 dBu @ 0 dB GAIN +0 dB / -1 dB +0 dB / -3 dB 2 x " TRS jack, balanced 20 k Ohms balanced, 10 k Ohms unbalanced -20 dB to +20 dB +22 dBu @ 0 dB GAIN RCA connector 10 k Ohms +22 dBu 50 Hz / +- 15 dB 700 Hz / +- 15 dB 10 kHz / +- 15 dB " TRS jack, unbalanced +22 dBu " mono jack, unbalanced 120 Ohms +22 dBu
Line input
Type Impedance Gain range Max. input level
Fig.5.3: Computer Recording
DSP2024P
Frequency response (Mic In Main Out)
<10Hz - 90kHz (-1 dB) <10Hz - 160kHz (-3 dB)
DV Deck
Stereo inputs
B2031A B2031A
B-1 XM1800S
CD/Tape In
Type Impedance Max. input level
Equalizer
HPS5000 XENYX1002B
LOW MID HIGH
Channel inserts
Type Max. input level
FCA202
MON/FX send
Type Impedance Max. output level
Fig.5.4: Video Editing
10 Main outputs
Type Impedance Max. output level " TRS jack, electronically balanced 240 Ohms balanced, 120 Ohms balanced +28 dBu " TRS jack, unbalanced +19 dBu / 150 Ohms (+25 dBm) RCA connector 1 k Ohms +22 dBu
Phones output
Type Max. output level
CD/Tape out
Main mix system data (Noise)3
Main mix @ -, channel fader @ - Main mix @ 0dB, channel fader @ - Main mix @ 0dB, channel fader @ 0dB -100 dB / -102.5 dB A weighted -82 dB / -85 dB A weighted -72 dB / -75 dB A weighted 50 W T 2,0 A H 250 V T 2,0 A H 250 V Standard IEC receptacle +18V +23V 4 hours w/ high quality Alkaline battery 1 9/16" (40 mm) / 2 7/8" (73 mm) x 11 3/4" (298 mm) x 8 1/2" (216 mm) 5.5 lbs / 2.5 kg (PSU not included)
Power supply
Power consumption Fuse (100 - 120V~, 50/60Hz) Fuse (220 - 230V~, 50/60Hz) Mains connector
Phantom power
With battery power With AC adaptor
Battery
Battery life
Physical/weight
Dimensions (H x W x D) Weight
Limited waranty
1 Warranty
[1] limited warranty is valid only if you purchased the product from a BEHRINGER This [2] This limited warranty does not cover the product if it has been electronically or
authorized dealer in the country of purchase. A list of authorized dealers can be found on BEHRINGERs website under Where to Buy, or you can contact the BEHRINGER office, BEHRINGER
be returned to the user freight prepaid by BEHRINGER.
[4] Warranty claims other than those indicated above are expressly excluded.
PLEASE RETAIN YOUR SALES RECEIPT. IT IS YOUR PROOF OF PURCHASE COVERING YOUR LIMITED WARRANTY. THIS LIMITED WARRANTY IS VOID WITHOUT SUCH PROOF OF PURCHASE.
limited warranty, in particular, if caused by improper handling of the product by the user. This also applies to defects caused by normal wear and tear, in particular, of faders, crossfaders, potentiometers, keys/buttons, tubes, guitar strings, illuminants and similar parts.
[6] Damage/defects caused by the following conditions are not covered by this
2 Online registration
Please do remember to register your new BEHRINGER equipment right after your purchase at under Support and kindly read the terms and conditions of our limited warranty carefully. Registering your purchase and equipment with us helps us process your repair claims quicker and more efficiently. Thank you for your cooperation! BEHRINGER.
[7] Any repair or opening of the unit carried out by unauthorized personnel
3 Return authorization number
[1] obtain warranty service, please contact the retailer from whom the equipment To
(user included) will void the limited warranty.
[8] If an inspection of the product by BEHRINGER shows that the defect in question is
was purchased. Should your BEHRINGER dealer not be located in your vicinity, you may contact the BEHRINGER distributor for your country listed under Support at. If your country is not listed, please check if your problem can be dealt with by our Online Support which may also be found under Support at. Alternatively, please submit an online warranty claim at BEFORE returning the product. All inquiries must be accompanied by a description of the problem and the serial number of the product. After verifying the products warranty eligibility with the original sales receipt, BEHRINGER will then issue a Return Materials Authorization (RMA) number.
[2] Subsequently, the product must be returned in its original shipping carton,
not covered by the limited warranty, the inspection costs are payable by the customer.
[9] Products which do not meet the terms of this limited warranty will be repaired
exclusively at the buyers expense. BEHRINGER or its authorized service center.
[10 Authorized BEHRINGER dealers do not sell new products directly in online ]
together with the return authorization number to the address indicated by BEHRINGER.
[3] Shipments without freight prepaid will not be accepted.
auctions. Purchases made through an online auction are on a buyer beware basis. Online auction confirmations or sales receipts are not accepted for warranty verification and BEHRINGER will not repair or replace any product purchased through an online auction.
4 Warranty Exclusions
[1] limited warranty does not cover consumable parts including, but not limited This
5 Warranty transferability
This limited warranty is extended exclusively to the original buyer (customer of authorized retail dealer) and is not transferable to anyone who may subsequently purchase this product. No other person (retail dealer, etc.) shall be entitled to give any warranty promise on behalf of BEHRINGER.
to, fuses and batteries. Where applicable, BEHRINGER warrants the valves or meters contained in the product to be free from defects in material and workmanship for a period of ninety (90) days from date of purchase.
7 Limitation of liability
This limited warranty is the complete and exclusive warranty between you and BEHRINGER. It supersedes all other written or oral communications related to this product. BEHRINGER provides no other warranties for this product.
8 Other warranty rights and national law
[1] limited warranty does not exclude or limit the buyers statutory rights as a This
consumer in any way.
[2] The limited warranty regulations mentioned herein are applicable unless they
constitute an infringement of applicable mandatory local laws.
[3] This warranty does not detract from the sellers obligations in regard to any lack of
conformity of the product and any hidden defect.
9 Amendment
Warranty service conditions are subject to change without notice. For the latest warranty terms and conditions and additional information regarding BEHRINGERs limited warranty, please see complete details online at.
* BEHRINGER Macao Commercial Oshore Limited of Rue de Pequim No. 202-A, Macau Finance Centre 9/J, Macau, including all BEHRINGER group companies
FEDERAL COMMUNICATIONS COMMISSION COMPLIANCE INFORMATION BEHRINGER USA can void the users authority to use the equipment.
Responsible party name: BEHRINGER USA, Inc. Address: 18912 North Creek Parkway, Suite 200 Bothell, WA 98011, USA Phone/Fax No.: Phone: +Fax: +hereby declares that the product_5<<
XENYX 1002B
Battery Powered 10 x 2 Mixer
Premium ultra-low noise analog mixer with optional battery operation 2 state-of-the-art XENYX Mic Preamps comparable to standalonemictaper master fader and sealed rotary controls External power supply for noisefree audio and superior transient response High-quality components and exceptionally rugged construction ensure long life Conceived and designed by BEHRINGER Germany
XENYX Mixer
Premium 10-Input 2-Bus Mixer with XENYX Preamps, British EQs and Optional Battery Operation
State-of-the-Art Goes Portable Whether you plug it into the wall or power it via 9 V batteries, the XENYX 1002B comes equipped with many of the features youve come to expect from our larger mixers, including XENYX mic preamps for amazing sound quality, phantom power for use with professional-grade condenser mics, 2-Track inputs and outputs, and
60 mm faders. The four stereo channels accept left/right or mono ".
Continued on next page
behringer.com
Superior mic preamps The XENYX 1002B represents a signicant milestone in the development of mixer technology. Equipped with our premium XENYX mic preamps, it can easily hold its own against the most expensive stand-alone mic preamps, both in terms of sound quality and available headroom. XENYX preamps oer value Dont let the small footprint fool youthe XENYX 1002B is built to the same exacting standards as our largerformat) nd the XENYX 1002B indispensable for patching into house systems.
Page 2 of 4
Recording Setup
HPS5000
Rackmount Synth
FX Processor
Studio Monitors
energyXT2.5 DAW software available separately
USB Audio Interface
Page 3 of 4
Live Performance
XM1800S
Drum Computer
Tape Deck HPS3000
F1220A Active Monitor Speaker
Field Operation Its compact size and exible input scheme also make it the natural choice of sports announcers for calling play-by-play game action. Likewise, radio and TV reporters especially like the XENYX 1002B for its ease-of-use, remarkable delity XENYX 1002B is the solid leader for value and sonic integrity in its class.
BEHRINGER B412DSP
Field Recording Setup
UL2000M Wireless Mic UCA222 USB Audio Interface
Laptop
HPS3000
MIC Input balanced XLR socket. INS (Insert) jack provides path to/ from external eects device. LINE IN " TRS and TS jacks. LINE TRIM adjusts level of " inputs. TRIM control sets level of input signal. 2-TRACK " & RCA inputs from Tape/CD/ MP3 decks. Stereo channel Left and Right inputs. Main outputs. FX Send output. 2-TRACK RCA outputs to Tape/CD/MD Headphones jack. recording decks.
Page 4 of 4
Monitor Send output.
Phantom power switch (+18 V). MONITOR SEND level control.
PAN control sets signal placement in stereo image. HIGH EQ control adjusts high frequency content, 15 dB @ 12 kHz. Stereo channels. FX control sets amount of signal sent to FX Send output. MON control sets amount of signal sent to monitor(s). MAIN output level fader.
FX SEND level control.
PHONES level control. MID EQ control adjusts midrange content, 15 dB @ 2.5 kHz. LOW EQ control adjusts bass content, 15 dB @ 80 Hz.
SPECIFICATIONS INPUT CHANNELS 1 & 2 Mic input Frequency response Gain range SNR Line input Frequency response Gain range SNR electronically balanced, discrete input conguration 10 Hz to 200 kHz +14 dB to +60 dB 120 dB E.I.N. electronically balanced 10 Hz to 130 kHz -6 dB to +38 dB 95 dB E.I.N.
STEREO CHANNELS 3/4 - 7/8 & 9/10 Frequency response 10 Hz to 70 kHz Gain range Line: - to +15 dB / Mic: +13 to +60 dB SNR Line: 96 dB / Mic: 104 dB E.I.N. EQUALIZATION LOW MID HI MAIN MIX Main Outputs Mon Send FX Send Tape Out Phones Output
POWER SUPPLY Mains voltage
50 Hz, +/- 15 dB 700 Hz, +/- 15 dB 10 kHz, +/- 15 dB
Battery life PHYSICAL Dimensions (H x W x D)
USA/Canada 120 V~, 60 Hz, Power Supply MXUL4 U.K./Australia 240 V~, 50 Hz, Power Supply MXUK4 Europe 230 V~, 50 Hz, Power Supply MXEU4 Japan 100 V~, 50 - 60 Hz, Power Supply MXJP4 approx. 4 h (with Duracell Alkaline Type MN1604 / 580 mAh)
+28 dBu balanced / +22 dBu unbalanced +22 dBu unbalanced +22 dBu unbalanced +22 dBu unbalanced +15 dBu / 150
approx. 2.875" x 11.75" x 8.5" approx. 73 mm x 298 mm x 216 mm Weight approx. 5.5 lbs. approx. 2.5 kg BEHRINGER is constantly striving to maintain the highest professional standards. As a result of these eorts, modications may be made from time to time to existing products without prior notice. Specications and appearance may dier from those listed or illustrated.
For service, support or more information contact the BEHRINGER location nearest you: BEHRINGER Australia tel.: +9877 7170, fax: +BEHRINGER Germany tel.: +9206 4149, fax: +BEHRINGER Japan tel.: +5281 1180, fax: +BEHRINGER Singapore tel: +1800, fax: +0275 BEHRINGER USA / CANADA tel: +672 0816, fax: +673 7647
2009 BEHRINGER International GmbH. Technical specications and appearance subject to change without notice. The information contained herein is correct at the time of printing. BEHRINGER accepts no liability for any loss which may be suered by any person who relies either wholly or in part upon any description, photograph or statement contained herein. All trademarks (except BEHRINGER, the BEHRINGER logo, JUST LISTEN and XENYX) mentioned belong to their respective owners and are not aliated with BEHRINGER. EnergyXT2.5 and the energyXT logo are trademarks of XT Software AS. Windows is a registered trademark of Microsoft Corporation in the United States and other countries. Mac OS and Logic are trademarks of Apple Computer, Inc., registered in the U.S. and other countries. ASIO is a trademark and software of Steinberg Media Technologies GmbH. VST is a trademark of Steinberg Media Technologies GmbH. Reason, ReWire and REX2 are trademarks of Propellerhead Software AB. Ableton Live is a trademark of Ableton AG. ProTools is a trademark of Avid Technology, Inc. or its aliates in the United States and/or other countries. 985-10000-00392
Technical specifications
Full description.
Xl4600DL TC300 SCH-R860 SRT2223 TM-D700A Review HOW2R1 AWF14480W ETX-70AT KV-14LM1E HVR-M15AN Designjet 700 Cooker DVD-915 Quattro Max Hpdi EL-1197PII AV505D Switch SK-5204 3228C Zanussi F550 Bike POD Furuno 1715 Zapper SUB-zero 561 ES-7000H Sunfire 1999 DCC730 00B WS-32Z409P Software And P 1500-WG SEG KR-7 Victory Omnibook 2100 P4S533 1513-tdxb 650 GS CQC1425N Tracker 5505 KDL-32S2800 EWF1005 IBM 6787 19AV616DG 32LD8D20EA WT5160 SCX-4720FN-ETS ICF-C218 S230I SRU5120 86 PCN-3335 NP-NF110 Tonelab SE EWF1420 TD-3KW RF-3700 Af-2840 ZDF3020 KDL-46EX701 PL80 RED Century 2003 Presario 5000 Style II DVP5980K 55 GT-S3600 KX-TG7100E T200HD MAX-ZJ550 Photon X25 MHS-PM5 W HT-C720 Gigaset 2015 LV400 CT200 Expert PC 380EX 150SV CQ-C1110W WMP54GX Camry 2300 Plus DVP-SR200P GK1630 A-S2000 MHC-FR1 3-device E70-1 SC6560 UF-7100 Aqxxf 121 RSH5ters BH-201 E460DW DB125 CPD-200GS XV-DV656 EP732H EWF12680W 4180-54 Photosmart 33
|
http://www.ps2netdrivers.net/manual/behringer.xenyx1002b/
|
crawl-003
|
refinedweb
| 5,255
| 63.59
|
This driver's top-level chip support is currently provided as three files:
Prototypes the low-level chip access functions required by
the chip driver and
declares a private struct for use by the driver.
Implements high-level chip functions and includes mt29f_generic_lp.inl.
This file is not intended to be compiled on its own, but to be included by the source file in a platform HAL which implements the low-level functions.
Implements those high-level chip functions which are specific to large-page chips, completing the driver and exposing it via the CYG_NAND_FUNS macro.
This file is not intended to be compiled or included directly by platform code.
CYG_NAND_FUNS
A platform HAL would typically make use of this driver in a single source file
with the following steps:
Declare a local private struct with contents as appropriate,
#include <cyg/devs/nand/mt29f_generic.h>
implement the required low-level functions,
#include <cyg/devs/nand/mt29f_generic.inl>
declare a list of the supported mt29f_subtype which may appear on the board, terminated by MT29F_SUBTYPE_SENTINEL
mt29f_subtype
MT29F_SUBTYPE_SENTINEL
declare a static instance of the mt29f_priv struct containing pointers to that list and to an instance of the local-private struct
mt29f_priv
finally, instantiate the chip with the CYG_NAND_DEVICE macro, selecting the ECC and OOB semantics to use.
CYG_NAND_DEVICE
Note: If there is more than one chip available on the board, each needs its own CYG_NAND_DEVICE with a distinct name and device name, its own instance of the mt29f_priv struct.
For more details about the infrastructure provided by the NAND layer
and the semantics it expects of the chip driver, refer to
Chapter 50.
As discussed in the Section called High-level (chip) functions in Chapter 52, the chip
initialisation function must set up the bbt.data
pointer in the cyg_nand_device struct. This driver does so
by including a large byte array in the mt29f_priv
struct whose size is controlled by CDL depending on the enabled
chip support.
That struct is intended to be allocated as a static struct in the
data or BSS segment (one per chip), which avoids adding a dependency
on malloc.
malloc
These functions are prototyped in
mt29f_generic.h.
They have no return value ("void"), except for
read_data_1 which returns the byte it has read.
read_data_1.
mt29f_devlock(device)
mt29.)
mt29.
mt29f_plf_partition_setup(device)
Board-level partition initialisation hook.
This should set up the partition array.
|
http://www.ecoscentric.com/ecospro/doc/html/ref/devs-nand-micron-mt29f-instantiation.html
|
crawl-003
|
refinedweb
| 394
| 50.57
|
. Cam-Winget, et al. Standards Track [Page 1]
RFC 8600 XMPP Grid.. incident reports and other security-relevant information. Cam-Winget, et al. Standards Track [Page 3]
RFC 8600 XMPP Grid June 2019-relevant information. Provider: An entity that contains functions to provide information to other components; as used here, the term refers to an XMPP publish-subscribe Publisher. Topic: A contextual information channel created on a Broker. Standards Track [Page 4]
RFC 8600 XMPP Grid June 2019 data either Implementations of XMPP-Grid adhere to the following workflow: incident reports and other security-relevant information to a Topic, subscribe to a Topic, query a Topic, or 2019 +--------------+ +------------+ +---------------+ |... Platforms could use [XEP-0059] to restrict the size of the result sets the Controller returns in a Service Discovery response. As an example, the Controller at 'security-grid.example' might provide a Broker at 'broker.security-grid.example', which hosts> Cam-Winget, et al. Standards Track [Page 8]
RFC 8600 XMPP Grid June 2019> Cam-Winget, et al. Standards Track [Page 9]
RFC 8600 XMPP Grid June 2019 The Broker responds with the "disco#info" description, which MUST include an XMPP data form [XEP-0004] with> The Platform discovers the Topics by obtaining the Broker's response and obtaining the namespaces returned in the "pubsub#type" field (in the foregoing example, IODEF 2.0). 6. Publish-Subscribe Using the XMPP publish-subscribe extension [XEP-0060],>.> Cam-Winget, et al. Standards Track [Page 11]
RFC 8600 XMPP Grid June 2019 Unless an error occurs (see [XEP-0060] for various error flows), the Broker makes an appropriate authorization decision. If access is granted, it to the Broker using the MILEHost Topic as follows: > and list what each architectural element is trusted to do. The items listed here are assumptions, but provisions are made in "Threat Model" (Section 8.2) and "Countermeasures" (Section 8.3) Cam-Winget, et al. Standards Track [Page 14]
RFC 8600 XMPP Grid June 2019 Cam-Winget, et al. Standards Track [Page 15]
RFC 8600 XMPP Grid June 2019, the XMPP-Grid Platform is running buggy software (which can fail in a state that floods the network with traffic), or (including human administrators), leading to a denial of service or parts of the network security system being disabled..)., the XMPP-Grid Controller is running buggy software (which can fail in a state that corrupts data or floods the network with traffic), or the XMPP-Grid Controller has been configured improperly.. Cam-Winget, et al. Standards Track [Page 19]
RFC 8600 XMPP Grid June 2019]. The XMPP-Grid Controller SHOULD include auditable logs of XMPP-Grid Platform activities. To avoid compromise of XMPP-Grid Platforms, they)... Cam-Winget, et al. the purposes of correlation by XMPP-Grid Platforms for intrusion detection, could be misused by a broader set of XMPP-Grid Platforms that hitherto have been performing specific roles. These matters are out of scope for this document but ought to be addressed by the XMPP-Grid community. 11. References 114422] Melnikov, A., Ed. and K. Zeilenga, Ed., "Simple Authentication and Security Layer (SASL)", RFC 4422, DOI 10.17487/RFC4422, June 2006, <>. . Standards Track [Page 25]
RFC 8600 XMPP Grid June 2019 [RFC6120] Saint-Andre, P., "Extensible Messaging and Presence Protocol (XMPP): Core", RFC 6120, DOI 10.17487/RFC6120, March 2011, <>. ,, <>. -0160] Saint-Andre, P., "Best Practices for Handling Offline Messages", XSF XEP 0160, October 2016, <>..]
|
http://zinfandel.tools.ietf.org/html/rfc8600
|
CC-MAIN-2020-29
|
refinedweb
| 565
| 57.98
|
This is a discussion on stuck on this. within the C++ Programming forums, part of the General Programming Boards category; Originally Posted by typeqwerty but when i run it on a site it where it automatically compile it would say ...
do you know how to get the output as when i input 1000
Enter a number of seconds:
There are 16.667 minutes in 1000.000 seconds.
my output would say
Enter a number of seconds:
There are 16.666667 minutes in 1000.000000 seconds.
There are 0.277778 hours in 1000.000000 seconds.
There are 0.011574 days in 1000.000000 seconds.
what code would make it have 2 lines instead of 3?
Code:#include <iostream> using namespace std; int main() { double input,days,hours,minutes,seconds; cout << "Enter a number of seconds: "; cin >> input; seconds = input; minutes = seconds / 60; hours = minutes / 60; days = hours / 24; cout <<endl << "There are " << minutes << " minutes in " << seconds << " seconds" <<endl; cout << "There are " << hours << " hours in " << seconds << " seconds" <<endl; cout << "There are " << days << " days in " << seconds << " seconds" <<endl; return 0; }
Last edited by Eddie Ramos; 09-29-2012 at 05:55 AM.
|
http://cboard.cprogramming.com/cplusplus-programming/150930-stuck-2.html
|
CC-MAIN-2014-41
|
refinedweb
| 189
| 73.78
|
Hiya All,
Possibly on odd question but indulge a newbie
When writing Classes
each of the elements must have a name? Would anyone know what they are?
(It just really helps if I can talk-through-the-c0de and not say
‘thingy’)
For example below, we have wodks like make, model and color repeated 4
times. What are they called? @make is an instance variable, but the
others?
Also, can you vary them? Say: @make_of_car = make ? I tried but it
seems they must be called the same. I’m not sure why
class Car
This class contains has the bits named differently
attr_accessor :make, :model, :color
def initialize(make, model, color)
@make = make
@model = model
@color = color
end
end
escort = Car.new(“Ford”,“Escort”,“Red”)
puts “It’s a #{escort.color} #{escort.make} #{escort.model}”
DE
|
https://www.ruby-forum.com/t/elements-of-class-names-can-they-vary/217190
|
CC-MAIN-2021-49
|
refinedweb
| 136
| 75.91
|
We need to worry about timing too :-( I'm using this as a test. It's very heavy on using 3-tuples of little ints as dict keys. Getting hash codes for ints is relatively cheap, and there's not much else going on, so this is intended to be very sensitive to changes in the speed of tuple hashing:
def doit():
from time import perf_counter as now
from itertools import product
s = now()
d = dict.fromkeys(product(range(150), repeat=3), 0)
for k in d:
d[k] += 1
for k in d:
d[k] *= 2
f = now()
return f - s
I run that five times in a loop on a mostly quiet box, and pick the smallest time as "the result".
Compared to current master, a 64-bit release build under Visual Studio takes 20.7% longer. Ouch! That's a real hit.
Fiddling the code a bit (see the PR) to convince Visual Studio to emit a rotate instruction instead of some shifts and an add reduces that to 19.3% longer. A little better.
The variant I discussed last time (add in the length at the start, and get rid of all the post-loop avalanche code) reduces it to 8.88% longer. The avalanche code is fixed overhead independent of tuple length, so losing it is more valuable (for relative speed) the shorter the tuple.
I can't speed it more. These high-quality hashes have unforgiving long critical paths, and every operation appears crucial to their good results in _some_ test we already have. But "long" is relative to our current tuple hash, which does relatively little to scramble bits, and never "propagates right" at all. In its loop, it does one multiply nothing waits on, and increments the multplier for the next iteration while the multiply is going on.
Note: "the real" xxHash runs 4 independent streams, but it only has to read 8 bytes to get the next value to fold in. That can go on - in a single thread - while other streams are doing arithmetic (ILP). We pretty much have to "stop the world" to call PyObject_Hash() instead.
We could call that 4 times in a row and _then_ start arithmetic. But most tuples that get hashed are probably less than 4 long, and the code to mix stream results together at the end is another bottleneck. My first stab at trying to split it into 2 streams ran substantially slower on realistic-length (i.e., small) tuples - so that was also my last stab ;-)
I can live with the variant. When I realized we never "propagate right" now, I agreed with Jeroen that the tuple hash is fundamentally "broken", despite that people hadn't reported it as such yet, and despite that that flaw had approximately nothing to do with the issue this bug report was opened about. Switching to "a real" hash will avoid a universe of bad cases, and xxHash appears to be as cheap as a hash without glaringly obvious weaknesses gets: two multiplies, an add, and a rotate.
|
https://bugs.python.org/msg327380
|
CC-MAIN-2020-05
|
refinedweb
| 512
| 66.78
|
I just announced the new Spring Boot 2 material, coming in REST With Spring:
1. Introduction
In this article, we’ll take a look at Spock, a Groovy testing framework. Mainly, Spock aims to be a more powerful alternative to the traditional JUnit stack, by leveraging Groovy features.
Groovy is a JVM-based language which seamlessly integrates with Java. On top of interoperability, it offers additional language concepts such as being a dynamic, having optional types and meta-programming.
By making use of Groovy, Spock introduces new and expressive ways of testing our Java applications, which simply aren’t possible in ordinary Java code. We’ll explore some of Spock’s high-level concepts during this article, with some practical step by step examples.
2. Maven Dependency
Before we get started, let’s add our Maven dependencies:
<dependency> ’ve added both Spock and Groovy as we would any standard library. However, as Groovy is a new JVM language, we need to include the gmavenplus plugin in order to be able to compile and run it:
<plugin> <groupId>org.codehaus.gmavenplus</groupId> <artifactId>gmavenplus-plugin</artifactId> <version>1.5</version> <executions> <execution> <goals> <goal>compile</goal> <goal>testCompile</goal> </goals> </execution> </executions> </plugin>
Now we are ready to write our first Spock test, which will be written in Groovy code. Note that we are using Groovy and Spock only for testing purposes and this is why those dependencies are test-scoped.
3. Structure of a Spock Test
3.1. Specifications and Features
As we are writing our tests in Groovy, we need to add them to the src/test/groovy directory, instead of src/test/java. Let’s create our first test in this directory, naming it Specification.groovy:
class FirstSpecification extends Specification { }
Note that we are extending the Specification interface. Each Spock class must extend this in order to make the framework available to it. It’s doing so that allows us to implement our first feature:
def "one plus one should equal two"() { expect: 1 + 1 == 2 }
Before explaining the code, it’s also worth noting that in Spock, what we refer to as a feature is somewhat synonymous to what we see as a test in JUnit. So whenever we refer to a feature we are actually referring to a test.
Now, let’s analyze our feature. In doing so, we should immediately be able to see some differences between it and Java.
The first difference is that the feature method name is written as an ordinary string. In JUnit, we would have had a method name which uses camelcase or underscores to separate the words, which would not have been as expressive or human readable.
The next is that our test code lives in an expect block. We will cover blocks in more detail shortly, but essentially they are a logical way of splitting up the different steps of our tests.
Finally, we realize that there are no assertions. That’s because the assertion is implicit, passing when our statement equals true and failing when it equals false. Again, we’ll cover assertions in more details shortly.
3.2. Blocks
Sometimes when writing JUnit a test, we might notice there isn’t an expressive way of breaking it up into parts. For example, if we were following behavior driven development, we might end up denoting the given when then parts using comments:
@Test public void givenTwoAndTwo_whenAdding_thenResultIsFour() { // Given int first = 2; int second = 4; // When int result = 2 + 2; // Then assertTrue(result == 4) }
Spock addresses this problem with blocks. Blocks are a Spock native way of breaking up the phases of our test using labels. They give us labels for given when then and more:
- Setup (Aliased by Given) – Here we perform any setup needed before a test is run. This is an implicit block, with code not in any block at all becoming part of it
- When – This is where we provide a stimulus to what is under test. In other words, where we invoke our method under test
- Then – This is where the assertions belong. In Spock, these are evaluated as plain boolean assertions, which will be covered later
- Expect – This is a way of performing our stimulus and assertion within the same block. Depending on what we find more expressive, we may or may not choose to use this block
- Cleanup – Here we tear down any test dependency resources which would otherwise be left behind. For example, we might want to remove any files from the file system or remove test data written to a database
Let’s try implementing our test again, this time making full use of blocks:
def "two plus two should equal four"() { given: int left = 2 int right = 2 when: int result = left + right then: result == 4 }
As we can see, blocks help our test become more readable.
3.3. Leveraging Groovy Features for Assertions
Within the then and expect blocks, assertions are implicit.
Mostly, every statement is evaluated and then fails if it is not true. When coupling this with various Groovy features, it does a good job of removing the need for an assertion library. Let’s try a list assertion to demonstrate this:
def "Should be able to remove from list"() { given: def list = [1, 2, 3, 4] when: list.remove(0) then: list == [2, 3, 4] }
While we’re only touching briefly on Groovy in this article, it’s worth explaining what is happening here.
First, Groovy gives us simpler ways of creating lists. We can just able to declare our elements with square brackets, and internally a list will be instantiated.
Secondly, as Groovy is dynamic, we can use def which just means we aren’t declaring a type for our variables.
Finally, in the context of simplifying our test, the most useful feature demonstrated is operator overloading. This means that internally, rather than making a reference comparison like in Java, the equals() method will be invoked to compare the two lists.
It’s also worth demonstrating what happens when our test fails. Let’s make it break and then view what’s output to the console:
Condition not satisfied: list == [1, 3, 4] | | | false [2, 3, 4] <Click to see difference> at FirstSpecification.Should be able to remove from list(FirstSpecification.groovy:30)
While all that’s going on is calling equals() on two lists, Spock is intelligent enough to perform a breakdown of the failing assertion, giving us useful information for debugging.
3.4. Asserting Exceptions
Spock also provides us with an expressive way of checking for exceptions. In JUnit, some our options might be using a try-catch block, declare expected at the top of our test, or making use of a third party library. Spock’s native assertions come with a way of dealing with exceptions out of the box:
def "Should get an index out of bounds when removing a non-existent item"() { given: def list = [1, 2, 3, 4] when: list.remove(20) then: thrown(IndexOutOfBoundsException) list.size() == 4 }
Here, we’ve not had to introduce an additional library. Another advantage is that the thrown() method will assert the type of the exception, but not halt execution of the test.
4. Data Driven Testing
4.1. What is a Data Driven Testing?
Essentially,.
4.2. Implementing a Parameterized Test in Java
For some context, it’s worth implementing a parameterized test using JUnit:
@RunWith(Parameterized.class) public class FibonacciTest { @Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][] { { 1, 1 }, { 2, 4 }, { 3, 9 } }); } private int input; private int expected; public FibonacciTest (int input, int expected) { this.input = input; this.expected = expected; } @Test public void test() { assertEquals(fExpected, Math.pow(3, 2)); } }
As we can see there’s quite a lot of verbosity, and the code isn’t very readable. We’ve had to create a two-dimensional object array that lives outside of the test, and even a wrapper object for injecting the various test values.
4.3. Using Datatables in Spock
One easy win for Spock when compared to JUnit is how it cleanly it implements parameterized tests. Again, in Spock, this is known as Data Driven Testing. Now, let’s implement the same test again, only this time we’ll use Spock with Data Tables, which provides a far more convenient way of performing a parameterized test:
def "numbers to the power of two"(int a, int b, int c) { expect: Math.pow(a, b) == c where: a | b | c 1 | 2 | 1 2 | 2 | 4 3 | 2 | 9 }
As we can see, we just have a straightforward and expressive Data table containing all our parameters.
Also, it belongs where it should do, alongside the test, and there is no boilerplate. The test is expressive, with a human-readable name, and pure expect and where block to break up the logical sections.
4.4. When a Datatable Fails
It’s also worth seeing what happens when our test fails:
Condition not satisfied: Math.pow(a, b) == c | | | | | 4.0 2 2 | 1 false Expected :1 Actual :4.0
Again, Spock gives us a very informative error message. We can see exactly what row of our Datatable caused a failure and why.
5. Mocking
5.1. What is Mocking?
Mocking is a way of changing the behavior of a class which our service under test collaborates with. It’s a helpful way of being able to test business logic in isolation of its dependencies.
A classic example of this would be replacing a class which makes a network call with something which simply pretends to. For a more in-depth explanation, it’s worth reading this article.
5.2. Mocking using Spock
Spock has it’s own mocking framework, making use of interesting concepts brought to the JVM by Groovy. First, let’s instantiate a Mock:
PaymentGateway paymentGateway = Mock()
In this case, the type of our mock is inferred by the variable type. As Groovy is a dynamic language, we can also provide a type argument, allow us to not have to assign our mock to any particular type:
def paymentGateway = Mock(PaymentGateway)
Now, whenever we call a method on our PaymentGateway mock, a default response will be given, without a real instance being invoked:
when: def result = paymentGateway.makePayment(12.99) then: result == false
The term for this is lenient mocking. This means that mock methods which have not been defined will return sensible defaults, as opposed to throwing an exception. This is by design in Spock, in order to make mocks and thus tests less brittle.
5.3. Stubbing Method calls on Mocks
We can also configure methods called on our mock to respond in a certain way to different arguments. Let’s try getting our PaymentGateway mock to return true when we make a payment of 20:
given: paymentGateway.makePayment(20) >> true when: def result = paymentGateway.makePayment(20) then: result == true
What’s interesting here, is how Spock makes use of Groovy’s operator overloading in order to stub method calls. With Java, we have to call real methods, which arguably means that the resulting code is more verbose and potentially less expressive.
Now, let’s try a few more types of stubbing.
If we stopped caring about our method argument and always wanted to return true, we could just use an underscore:
paymentGateway.makePayment(_) >> true
If we wanted to alternate between different responses, we could provide a list, for which each element will be returned in sequence:
paymentGateway.makePayment(_) >>> [true, true, false, true]
There are more possibilities, and these may be covered in a more advanced future article on mocking.
5.4. Verification
Another thing we might want to do with mocks is assert that various methods were called on them with expected parameters. In other words, we ought to verify interactions with our mocks.
A typical use case for verification would be if a method on our mock had a void return type. In this case, by there being no result for us to operate on, there’s no inferred behavior for us to test via the method under test. Generally, if something was returned, then the method under test could operate on it, and it’s the result of that operation would be what we assert.
Let’s try verifying that a method with a void return type is called:
def "Should verify notify was called"() { given: def notifier = Mock(Notifier) when: notifier.notify('foo') then: 1 * notifier.notify('foo') }
Spock is leveraging Groovy operator overloading again. By multiplying our mocks method call by one, we are saying how many times we expect it to have been called.
If our method had not been called at all or alternatively had not been called as many times as we specified, then our test would have failed to give us an informative Spock error message. Let’s prove this by expecting it to have been called twice:
2 * notifier.notify('foo')
Following this, let’s see what the error message looks like. We’ll that as usual; it’s quite informative:
Too few invocations for: 2 * notifier.notify('foo') (1 invocation)
Just like stubbing, we can also perform looser verification matching. If we didn’t care what our method parameter was, we could use an underscore:
2 * notifier.notify(_)
Or if we wanted to make sure it wasn’t called with a particular argument, we could use the not operator:
2 * notifier.notify(!'foo')
Again, there are more possibilities, which may be covered in a future more advanced article.
6. Conclusion
In this article, we’ve given a quick slice through testing with Spock.
We’ve demonstrated how, by leveraging Groovy, we can make our tests more expressive than the typical JUnit stack. We’ve explained the structure of specifications and features.
And we’ve shown how easy it is to perform data-driven testing, and also how mocking and assertions are easy via native Spock functionality.
The implementation of these examples can be found over on GitHub. This is a Maven-based project, so should be easy to run as is.
|
https://www.baeldung.com/groovy-spock
|
CC-MAIN-2018-47
|
refinedweb
| 2,354
| 61.26
|
Introduction
minimega includes Python bindings for its CLI that interact with minimega using the domain socket. These bindings are automatically generated and allow the user to drive minimega with Python scripts.
General Usage
The
pyapigen tool generates
minimega.py which can be imported into scripts.
The Python bindings include docstrings for every minimega command -- see
help(minimega) for a full listing. Here's a simple example of a script to
launch 10 VMs, display their info, and then kill them:
import minimega mm = minimega.connect(debug=True) print 'launching vms' mm.vm_launch_kvm(10) print 'vm info:' minimega.print_rows(mm.vm_info()) print 'starting vms' mm.vm_start('all') print 'vm info:' minimega.print_rows(mm.vm_info()) print 'killing vms' mm.vm_kill('all') print 'flushing vms' mm.vm_flush()
The
connect method wraps
minimega.minimega.__init__:
help(minimega.connect): connect(path='/tmp/minimega/minimega', raise_errors=True, debug=False, namespace=None, timeout=60) Connect to the minimega instance with UNIX socket at <path> and return a new minimega API object. See help(minimega.minimega) for an explaination of the other parameters. help(minimega.minimega.__init__): __init__(self, path, raise_errors, debug, namespace, timeout) unbound minimega.minimega method Connects to the minimega instance with UNIX socket at <path>. If <raise_errors> is set, the Python APIs will raise an Exception whenever minimega returns a response with an error. If <debug> is set, debugging information will be printed. The <namespace> parameter allows you to "bind" the minimega object to a particular namespace (see help(minimega.minimega.namespace) for more info on namespaces). The <timeout> parameter allow you to set a command timeout.
By default, the domain socket is only read/writable by root so the Python script must run as root (or the domain socket can be chmod'd appropriately).
Running commands
As shown above, the Python bindings include a
print_rows function that reads
all the responses from a minimega command. Due to the serial nature of the
minimega connection, all responses must be read before another command can be
issued. By default, commands return the first response and set a flag if there
are more responses to read (resp['More']). If
More is true, users can call
streamResponses on the minimega instance which returns a generator for
additional responses. The helper,
minimega.discard, can be used to discard
these if no action is required in the Python script (and errors are checked via
raise_errors).
All commands have arguments based on the underlying CLI which are checked by
the Python bindings. If an argument is invalid, a
ValueError will be raised
with a description of the error.
namespaces
The Python bindings support namespaces in several ways. First, users may
specify a namespace when connecting to minimega which runs all commands from
that connection in that namespace. Second, users can use
with statements to
run commands in a particular namespace:
mm = minimega.connect() with mm.namespace("foo") as mm: mm.vm_launch_kvm(1) with mm.namespace("foo") as mm: with mm.namespace("bar") as mm2: for resp in mm.vm_info(): for row in resp.get("Tabular", []) or []: mm2.vm_launch_kvm(row[1])
|
https://minimega.org/articles/python.article
|
CC-MAIN-2020-24
|
refinedweb
| 509
| 60.31
|
Hello! I've been working on this programming assignment for a game of craps, and I can't seem to figure out how to correct an error. Here's my code:
import java.util.*; import java.io.*; public class Craps { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String YesNo; boolean Y = true; System.out.println("Hi there! Do you want to play some craps(Y/N)?"); YesNo = scan.next(); if (YesNo.equals("N")) System.exit(0); else if (YesNo.equals("Y")) { System.out.println("Do you want to read the rules of the game(Y/N)?"); YesNo = scan.next(); { if (YesNo.equals("N")) play(); else if (YesNo.equals("Y")) { rules(); play(); } } } System.exit(0); } public static void rules() { System.out.print("Two die are thrown and the \n" + "sum of their two faces are added up, giving a number from \n" + "2 to 12. If the number is 7 or 11, the thrower wins. If \n" + "the number is either 2, 3, or 12, the thrower loses. If it is \n" + "neither of these numbers (i.e., it is either 4, 5, 6, 8, "); } public static boolean play() { Die dieOne = new Die(); Die dieTwo = new Die(); int result; int points; int rollcount = 0; result = rollDie(dieOne, dieTwo); System.out.println("The result of the two rolls are " + result); switch (result) { case 7: case 12: System.out.println("You won the game.!"); System.exit(0); break; case 3: case 11: System.out.println("You lost the game. "); System.exit(0); break; default: result = points; result = rollDie(dieOne, dieTwo); System.out.println("Your total points are " + points + result); } rollcount++; } private static int rollDie(Die one, Die two) { Die dieOne = new Die(); Die dieTwo = new Die(); int result; one.roll(); two.roll(); result = dieOne + dieTwo; } public class Die { //The smallest number a die can have private final int MIN_NUMBER = 1; //The largest number a die can have private final int MAX_NUMBER = 6; //The initialization of the die when created private final int NO_NUMBER = 0; //the current value of the die int number; public Die() { number = NO_NUMBER; } //this procedure rolls the die public void roll() { number = (int) Math.floor(Math.random()*(MAX_NUMBER - MIN_NUMBER + 1)) +1; } public int getNumber() { return number; } } }
The error I get when I attempt to compile the code is "non-static variable this cannot be referenced from a static context" and it highlights "Die dieOne = new Die();"
I'm terrible at Java so I apologize if there is a simple fix that I was too slow to figure out haha. Also, if there are any other major problems you see with my coding I'd greatly appreciate if you'd point them out to me (although I'm sure BlueJ will do that for me eventually lol).
|
http://www.javaprogrammingforums.com/whats-wrong-my-code/3458-error-program-game-craps.html
|
CC-MAIN-2016-22
|
refinedweb
| 461
| 64.51
|
Many of the XSLT examples in this book use the latest XSLT 2.0 features. Some (but not all) of the examples can be rewritten in 1.0 without too much trouble. Otherwise , if your XSLT processor does not yet support 2.0, check if it can use an EXSLT element ( 4.4.1 ) or a proprietary extension with the same or similar semantics.
Compared to the canceled XSLT 1.1, the list of new features and incompatible changes is much longer in 2.0. Below are some highlights.
The concept of nodesets is replaced by a more general concept of sequences . A nodeset, as the name implies, is a set of nodes, and each node must belong to one of the few types that directly follow from the structure of XML (element node, attribute node, etc.). Contrastingly, a sequence may combine arbitrary values and allows for automatic control over their types; for example, you can create a sequence of integer numbers and let the processor ensure type conformance for you.
This change has had a profound impact on the entire language; all instructions that previously operated on nodesets now are generalized to sequences. Moreover, new attributes have been added to many instructions that make working with sequences (including nodesets) more convenient . For instance, to list the values of all child elements, separated by commas, in 1.0 you had to write
<xsl:for-each <xsl:value-of <xsl:if <xsl:text>, </xsl:text> </xsl:if> </xsl:for-each>
In 2.0, you can simply write
<xsl:value-of
XSLT 2.0 makes it possible to specify and check data types of variables , parameters, functions, and templates. To this end, it borrows a library of data types from XSDL (XML Schema). For example, here's how you declare an integer variable in 2.0:
<xsl:variable
And here is a variable that may contain a sequence of attribute nodes:
<xsl:variable
Note that the integer variable declaration above refers to an XSDL data type and therefore uses the xs : namespace prefix that must resolve to the namespace URI of . In the second example, attribute() is a node type native to XSLT, so no namespace prefix is necessary; the * at the end of the type specification makes this a sequence rather than a single attribute value.
Another powerful concept is grouping . Although there's nothing really new here, as you could emulate this feature with the 1.0 facilities, the new syntax allows for very elegant constructs. You can group nodes (or other members of a sequenceremember, it is generalized!) by
the common value of an arbitrary XPath expression (e.g., group all nodes with the same child or attribute, or group sequence members that return equal values as arguments to some function); or
arbitrary properties of neighbors in the sequence (e.g., group all adjacent nodes sharing some property, or group all nodes starting from a heading node until the next heading ).
This feature makes it possible to "deepen" an XML tree, adding hierarchy to a flat structure (see also 2.3.2 ). The powerful new xsl:for-each-group instruction can be used, for example, to enclose into section s groups of elements that start with a heading :
<xsl:for-each-group <section> <xsl:copy-of </section> </xsl:for-each-group>
The new XPath 2.0 is chock full of goodies , especially in comparison to 1.0. Like XSLT 2.0, the new XPath supports schema-derived types and sequences. It also provides a lot of newand sorely missing in 1.0functions that work with strings, numbers, dates, URIs, qualified names , nodes, and nodesets. Lowercasing a string, matching a regexp, resolving a relative URI, converting a date, finding the node with the highest numeric value in a nodesetall of this is now possible without clumsy workarounds or nonportable extension functions.
Moreover, XPath even encroaches on the domain of XSLT proper, offering its own variants of some XSLT constructs. These variants are not only less verbose but often look more natural from the "traditional programming languages" viewpoint. For example, instead of the old
<xsl:attribute <xsl:choose> <xsl:whentop </xsl:when> <xsl:otherwise> bottom </xsl:otherwise> </xsl:choose> </xsl:attribute>
you can now write simply
<xsl:attribute <xsl:value-of </xsl:attribute>
Also, in XPath 2.0 you can explicitly check if some or every member of a sequence satisfies a condition (in 1.0 the some quantifier was always assumed).
Despite the 1.1 setback, extensibility is in 2.0 too. There's no xsl:script anymore, but you can link up extension functions if your processor supports this (we'll use this feature a lot in Chapter 5). Perhaps more importantly, you can now define new functions written in XSLT [5] and use them in your XPath expressions (this feature will be used even more; Example 4.1 on page 167 is a simple illustration).
[5] Strange but true: A language intended to be functional did not support user -defined functions until version 2.0.
[5] Strange but true: A language intended to be functional did not support user -defined functions until version 2.0.
The ability to create multiple output documents is also present, as it was in 1.1. The instruction that creates a new output document is called xsl:result-document . You can provide several xsl:output instructions, each storing a named collection of output parameters; different xsl:result-document instructions may refer to different xsl:output specifications, thus implementing a content/presentation separation of sorts: Now "presentation" (governed by xsl:output parameters) is removed from "content" (created by an xsl:result-document ). This feature is used in 5.5.2 (page 238).
There is much more that is new in XSLT and XPath 2.0; [6] this section covers only what I think are the most important new features for a practical XSLT programmer. Minor nifty things include the xsl:next-match instruction, which allows firing more than one template rule for the same context in the same mode; the function-available() function to check whether your processor supports a particular function; the unparsed-text () function that reads an arbitrary text resource (file or URL) and returns it as a string without parsing (see 5.1.3.3 for a use case); and more.
[6] For a complete list of changes, see.
[6] For a complete list of changes, see.
Fortunately, you don't have to learn all this at once. Most of your 1.0 stylesheets will work with a 2.0 processor without problems, and those that use 1.1 features or custom extensions ( 4.4.3 ) will likely require only minimal changes.
|
https://flylib.com/books/en/1.501.1.43/1/
|
CC-MAIN-2019-39
|
refinedweb
| 1,111
| 55.84
|
Products and Services
Downloads
Store
Support
Education
Partners
About
Oracle Technology Network
The following test periodically hangs when run with -server. If you run a debug might you might need to increase the time it was before it considers it to be hung. I'm still trying to narrow which release it appeared it. 6u14 is currently the first release where I've seen it hang.
import java.net.*;
import org.jsuffixarrays.*;
public class test extends Thread {
public static void main(String[] args) throws Exception {
int hung = 0;
for (int i = 0; i < 10000; i++) {
URLClassLoader apploader = (URLClassLoader)test.class.getClassLoader();
URLClassLoader ucl = new URLClassLoader(apploader.getURLs(), apploader.getParent());
Class c = ucl.loadClass("test");
Thread t = (Thread)c.newInstance();
t.start();
for (int s = 0; s < 10; s++) {
Thread.sleep(500);
if (!t.isAlive()) {
break;
}
}
if (t.isAlive()) {
hung++;
}
System.out.println("ok " + (i + 1 - hung) + " hung " + hung);
}
}
public void run() {
DivSufSortTest t = new DivSufSortTest();
t.setupForConstraints();
t.invariantsOnRandomLargeAlphabet();
t.sameResultWithArraySlice();
t.invariantsOnRandomSmallAlphabet();
}
}
Hi Tom.
Apologies for not providing a broader context, it follows.
> Is it hanging, as in making no progress, or not terminating?.
> Does it terminate if given a lot more time? It's not GC bound? By debugger do you mean gdb or a Java debugger?
No, it never terminates... at least not in a reasonable time. Normally this loop ends in 2-3 seconds and when hung it does not terminate after 30 minutes or so (the longest we waited to kill it on the build server).
To me It looks like it JITs into something that causes an endless loop. I also checked with jrockit and J9 and these never hung, so it's probably hotspot.
Talking about the debugger, that was a Java debugger, I didn't inspect JIT dumps of what this method compiles to yet, didn't have the time and wanted to check if it's a known issue first.
I'll try to reproduce it with JIT code dumps, I'll let you know if I succeed.
Dawid
On Thu, Mar 3, 2011 at 9:37 PM, Tom Rodriguez <###@###.###> wrote: :).
EVALUATION
The seems to appear with the RPO parsing changes 6384206. I don't think it's the changes themselves but RPO parsing certainly exposed other issues when they went in.
EVALUATION
This appears to be a long standing issue with IdealLoopTree::policy_do_remove_empty_loop. That codes assumes the counted loop has a zero trip guard and will incorrectly change value produced by the loop if it does not. Most normally written loops will get a zero trip guard as a result of peeling. In the case from the bug report the nested loop with complex bounds and an OSR entry point creates a really unusual loop shape. The RPO parsing changes allowed us to optimize it slightly better too. With help from Vladimir I was able to build a test case that failed for normal compiles.
public class Test {
static int i;
static int x1;
static int[] bucket_B;
static void test(Test test, int i, int c0, int j, int c1) {
for (;;) {
if (c1 > c0) {
if (c0 > 253) {
throw new InternalError("c0 = " + c0);
}
int index = c0 * 256 + c1;
if (index == -1) return;
i = bucket_B[index];
if (1 < j - i && test != null)
x1 = 0;
j = i;
c1--;
} else {
c0--;
if (j <= 0)
break;
c1 = 255;
}
}
}
public static void main(String args[]) {
Test t = new Test();
bucket_B = new int[256*256];
for (int i = 1; i < 256*256; i++) {
bucket_B[i] = 1;
}
for (int n = 0; n < 100000; n++) {
test(t, 2, 85, 1, 134);
}
}
}
The fix is most likely to peel the loop before removing it to ensure it has a guard though in the common case this introduces a little redundancy.
EVALUATION
Note that this test case fails with every 1.6.0 release.
EVALUATION
EVALUATION
7024475: loop doesn't terminate when compiled
Reviewed-by: kvn.
|
http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7024475
|
CC-MAIN-2014-10
|
refinedweb
| 645
| 64.1
|
Type: Posts; User: memeloo
sure, here it is:
using System;
using System.IO;
using System.Net;
using System.Xml.Linq;
namespace ConsoleApplication2
{
interestingly it works when you put all the parameters in the call to Create the instance of HttpWebRequest like this:
HttpWebRequest httpWebRequest =
...
ok, I did like you said. then I moved the "entry?" part to post data like this:
HttpWebRequest mineReq = (HttpWebRequest)WebRequest.Create("");
...
String...
I don't think so, though my first thought was exacly the same but then I read that wikipedia states that friendfeed is owned by facebook. besides I use fake accounts anyway ;)
someone will laugh... but I don't know what the password is. could it be my facebook pass when I registered with my facebook account?
sure, I already tried it but I don't see any System.Web dll to add. I added a using System.Web but VS still does not recognize HttpUtility and even IntelliSense does not see it even though it's there...
and you are not about to tell me what I should add?
where do I find a valid user and pass?
you sample code is incomplete and it cannot be tested (the HttpUtility is missing). I also get a "The remote server returned an error: (401) Unauthorized." exception. isn't your firewall blocking...
|
http://forums.codeguru.com/search.php?s=253c70ae3b0607485582918f614aa577&searchid=12814831
|
CC-MAIN-2018-13
|
refinedweb
| 218
| 77.94
|
Introduction
Skype is a telecommunications program that, along with normal chats, allows people to phone via Internet. One of the most important advantages of Skype as compared to other programs of the kind is a gateway to real mobile network operators. Respectively, one can call a real mobile phone, send SMSes, and so on. There is also a Skype version for mobile phones. One can save money on SMSes since sending regular messages within the program is absolutely free. Basically, a mobile phone must work under an operating system. Well, it is possible now to be fully mobile if necessary. And it is this opportunity that many people use nowadays.
Who and Why May Need This?
Trader cannot always sit in front of trading terminal and watch how the trading is performed, neither he/she must do this. However, it would be great to be able to get signals sometimes that would inform the trader about Expert Advisor's actions or about the market state at certain moments. Why not to get this information in his or her mobile phone?
What Kind of Information Would It Be Useful to Get?
Information that can be got using messages in a mobile phone can be divided into two groups:
- current data that do not influence anything and are practically the same as those in the log file;
- useful info that will be helpful for the trader exactly when it incomes.
Let's consider examples of current data:
- Order states. When an order was opened, in what direction, what stops were assigned for it, etc., when it was closed, for what reason, at a loss or at a profit, etc.
- Various market states. For example, when an indicator meets a certain level or a trend changes its direction.
Useful information:
- Error report. All programmers are people, and sometimes some unpleasant situations occur when the Expert Advisor works improperly. It would be not bad to know about the conditions, in which errors occur and whether that results in a fatal halting. This will work, of course, if the Expert Advisor's logic allows one to detect errors.
- Expert Advisor's operating state. For instance, the EA is set up in such a way as to send a message about its operating state every hour while you are on a business trip. And it happens so that the expected message has not income at the hour stated. Everything could happen: from disconnection from the Internet to power cuts. If the terminal works at your home, it would make sense to ask a colleague or the spouse to find out about the reason and restore settings, instead of waiting during a week in the dark.
This division is, of course, of a relative nature, and the list of possible events extends further than this article. Every trader will decide for him or herself what content the message should have. The main thing is to realize that this function is very helpful.
How Does This Work in Skype?
- SMSes. The service is, of course, to be paid for. Everything looks like usually: dial the subscriber's number, type the message, and press "Send".
- Regular messages. This is absolutely free. Just select a user, type a message and press "Send".
How to Do This from an Expert Advisor?
I found two ways how to do this, and both need using of DLLs:
We should prepare a macrofile in advance, i.e. at launching of that file control over keyboard and mouse will be intercepted. Thus, using the sequence of actions, we should activate Skype, find the SMS- sending item in the menu, then dial the subscriber's number in the window that appears, and paste from clipboard the text message initially typed in the Expert Advisor. You can train and polish up the operations beforehand. Thus, we have prepared a file that is an associated document and can be launched as a normal application. By the way, there are very many applications that record and replay macrofiles, so we won't consider specific programs in this article.
Then we have to develop a DLL that will operate as follows. Its first operation will be placing the text from the Expert Advisor into clipboard. The second operation is launching the predefined macrofile. If everything is set up well and all windows and buttons appear in their proper places, there should not occur any problems, the message will be sent.
However, this way is a bit frightening. Intuition suggests me that, if brains start to invent something like that, one has to either find a more pleasing solution or renounce the idea as a whole. A new idea flashed into my mind: Can Skype have an API? Well, I found API and ActiveX interface on their website. Great! Let's consider another way to work with Skype from an Expert Advisor.
It is mostly the same. The subscriber's number and the text to be sent will be passed from the EA to the DLL, which sends the message through the Skype COM object.
How to Realize the Second Way
Let us start with DLL. The main part of all works will be preparing DLL for interaction with the Expert Advisor. First, we write a library that would work when called from several Expert Advisors. Unfortunately, it will be insufficient just to write a function and call it. We are using ActiveX, so it is desirable to create a special separated thread for it and do all work in it. The standard paralleling tool for Mutex functions will not help. There will be crashes that cannot be detected. So we will realize the sequence of calls through the custom messaging system.
DLL Source Code
#include "stdafx.h" #pragma once // Allow use of features specific to Windows XP or later. #ifndef WINVER // Change this to the appropriate value to target other versions of Windows. #define WINVER 0x0501 #endif // Exclude rarely-used stuff from Windows headers #define WIN32_LEAN_AND_MEAN // Include Skype4COM.dll, preliminarily downloaded // from the Skype developers website – #import "Skype4COM.dll" rename("CreateEvent","CreatePluginEvent"), rename("SendMessage","SendChatMessage") #define MT4_EXPFUNC __declspec(dllexport) // Declare message codes for our functions. #define WM_PROC_SENDSKYPESMS WM_USER + 01 #define WM_PROC_SENDSKYPEMESSAGE WM_USER + 02 // Variables for the thread to be used for // sending messages HANDLE hUserThread; DWORD ThreadId; // Structures to store parameters of functions // SendSkypeSMS struct fcpSendSkypeSMS { int ExitCode; char * UserNum; char * Message; }; // SendSkypeMessage struct fcpSendSkypeMessage { int ExitCode; char * UserName; char * Message; }; //+------------------------------------------------------------------+ //| Thread function | //+------------------------------------------------------------------+ DWORD WINAPI ThreadProc(LPVOID lpParameter) { MSG msg; HANDLE hEvent; while(true) { if(PostThreadMessage(GetCurrentThreadId(), WM_USER, 0, 0)) break; }; // Initialize COM CoInitialize(NULL); while(GetMessage(&msg, 0, 0, 0)) { if(msg.message == WM_QUIT) { break; } // Message processor WM_PROC_SENDSKYPESMS else if(msg.message == WM_PROC_SENDSKYPESMS) { fcpSendSkypeSMS* fcp = (fcpSendSkypeSMS* an SMS pSkype->SendSms(fcp->UserNum,fcp->Message,""); } catch(...) { fcp->ExitCode=-1; } } // Deinitialize Skype pSkype = NULL; } catch(...) { //Error is processed here } // Set the event SetEvent(hEvent); } // Message processor WM_PROC_SENDSKYPEMESSAGE else if(msg.message == WM_PROC_SENDSKYPEMESSAGE) { fcpSendSkypeMessage* fcp = (fcpSendSkypeMessage* the message pSkype->SendChatMessage(fcp->UserName, fcp->Message); } catch(...) { fcp->ExitCode=-1; MessageBeep(0); } } // Deinitialize Skype pSkype = NULL; } catch(...) { //Error is processed here } // Set the event SetEvent(hEvent); } }; // Deinitialize COM CoUninitialize(); return 0; } //DLL Initialization //+------------------------------------------------------------------+ //| DLL entry | //+------------------------------------------------------------------+ BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { if(ul_reason_for_call == DLL_PROCESS_ATTACH) { // Create a thread and attach the processor procedure address to it hUserThread = CreateThread(NULL, NULL, ThreadProc, NULL, 0, &ThreadId); if(!hUserThread) { // Error processing if the thread is not created }; } else if(ul_reason_for_call == DLL_PROCESS_DETACH) { // Delete the thread when exiting the library CloseHandle(hUserThread); } return(TRUE); } MT4_EXPFUNC bool __stdcall SendSkypeSMS(int &ExCode,char* sUserNum, char* sMessage) { //Declare the structure of function parameters fcpSendSkypeSMS* fcp; //Declare an event HANDLE hEvent; //The result of function operation by default is false bool Result = false; // Allocate a password for the structure and initialize it fcp = new fcpSendSkypeSMS(); memset(fcp, 0, sizeof(fcpSendSkypeSMS)); // Fill out the structure //By default, the code of the function working end is an error. fcp->ExitCode = -1; fcp->UserNum = sUserNum; fcp->Message = sMessage; // Create an event hEvent = CreateEvent(NULL,FALSE,FALSE, NULL); // Call event WM_PROC_SENDSKYPESMS, pass the data structure address // to processing procedure PostThreadMessage(ThreadId, WM_PROC_SENDSKYPESMS, ); } MT4_EXPFUNC bool __stdcall SendSkypeMessage(int &ExCode,char* sUserName, char* sMessage) { //Declare the structure of function parameters fcpSendSkypeMessage* fcp; //Declare an event HANDLE hEvent; //The result of function operation by default is false bool Result = false; // Allocate memory for the structure and initialize it fcp = new fcpSendSkypeMessage(); memset(fcp, 0, sizeof(fcpSendSkypeMessage)); // Fill out the structure //By default, the code of the function working end is an error. fcp->ExitCode = -1; fcp->UserName = sUserName; fcp->Message = sMessage; // Create an event hEvent = CreateEvent(NULL, FALSE,FALSE, NULL); // Call the event WM_PROC_SENDSKYPESMS, pass the data structure address // to processing procedure PostThreadMessage(ThreadId, WM_PROC_SENDSKYPEMESSAGE, ); }
File DEF
LIBRARY SkypeLib EXPORTS SendSkypeSMS SendSkypeMessage
Expert Advisor to Be Tested
//+------------------------------------------------------------------+ //| SkypeTestExpert.mq4 | //| Copyright © 2007, Alexey Koshevoy. | //+------------------------------------------------------------------+ // Import functions #import "SkypeLib.dll" bool SendSkypeSMS(int &ExCode[], string Num,string Message); bool SendSkypeMessage(int &ExCode[], string User, string Message); #import //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int init() { int ExCode[1]; Alert("Send message..."); Alert(SendSkypeMessage(ExCode, "skype.account.name", "Skype message test")); if(ExCode[0] == -1) Alert("Error sending the message"); else Alert("Message sent"); Alert("Send SMS..."); Alert(SendSkypeSMS(ExCode, "+1234567890", "Skype sms test")); if(ExCode[0] == -1) Alert("Error sending the SMS"); else Alert("SMS sent"); return(0); } //+------------------------------------------------------------------+ //| | //+------------------------------------------------------------------+ int start() { return(0); } //+------------------------------------------------------------------+
The Ea is very simple, its main aim is to send an SMS and a regular message through the DLL we have coded. It acts within the initialization function, so it can also be tested at weekends.
Skype Installation
The application can be downloaded at. It is recommended to install the latest version of the program, since the preceding versions don't support COM interface, they only have an API. However, the API doesn't support sending SMSes.
Well, Skype has already been installed. Now we have to download the COM library. It can be found at, in Downloads. Check the amount on the account to be used for sending SMSes. If there is not enough money, you can add some through Internet. It will not allow to send SMSes without money on the account, but regular messages can be sent without any problems.
For the terminal to access to Skype API, it must be registered. You can check whether it is permitted to work with the API using the menu of Tools->Options->Privacy->Manage other programs access to Skype. It must look approximately like this:
The terminal will be registered at the first attempt to use the library. It cannot be done manually. So, when the library is being installed for the first time, it is necessary to wait until a message is sent in order to have confirmed the permission to use Skype API. Skype will show the following dialog box:
After confirmation, the system will start working in the automated mode.
Installation of SkypeLib
Для In order to install the library named SkypeLib.dll, it is necessary to copy it to the experts/libraries folder in the terminal directory. The library named Skype4COM.dll must also be copied to this folder. Now we have to set up the terminal to be able to work with the DLL. For this, check field "Allow DLL imports" in the "Safety" section when attaching an EA as shown below:
Now we can use the library.
Some Important Details
Having some experience in testing and implementation, I noticed some "subtleties". For example, you have to consider that, if you have enough money on your account and send an SMS to a non-existing number, no error will be reported, the function will work successfully, whereas the message status will be set for “sending...”. This is why it is important to set up function inputs very clearly. It is also very important the you use Skype version 3. 0 (or later versions).
It happens (however, rather rarely) that COM object is not initialized and no messages will be sent. This can only be helped with reinstallation of Skype. The external interface is relatively new, not without bugs, so such unpleasant things may happen. It has happened twice within my knowledge. Let's hope that the later versions will work stabler.
It must also be noted that some additional libraries may be needed for SkypeLib. dll to operate. The problem is especially acute after the first service pack for Visual Studio 2005 has been released. The best way to solve this problem is to create a setup file. All necessary libraries will be included in it automatically. File Skype4COM. dll can be included in it, too.
Files Attached to the Article
- SkypeLib.dll - The library was compiled in Visual C++ 6.0. It does not need any additional files but Skype4COM.dll.
- SkypeLib.zip - The library source code.
- SkypeExample.mq4 - An Expert Advisor for the library to be tested.
Highs and Lows
The following disadvantages can be observed when using Skype SMSes:
- SMSes cost some money
- One cannot send a message to oneself, it is necessary to have another Skype account to get messages.
- Your phone must support the mobile version of Skype. If a computer is used to receive messages, this disadvantage stands no longer.
This method has the following advantages:
- Signals in the real-time mode
- Function that cannot be replaced by anything at the moment. This is not even an advantage, it's just a fact.
Conclusions
We have learned how to send SMSes and regular messages via Skype. In such a way, we have got an interface, which is perhaps not the most convenient, but surely indispensable, to inform us about current events in the terminal. What comes next? Well, for example, Skype allows both sending and RECEIVING messages...
|
https://www.mql5.com/en/articles/1454
|
CC-MAIN-2016-40
|
refinedweb
| 2,276
| 55.34
|
NAME | DESCRIPTION | ATTRIBUTES | SEE ALSO.
See rpc(3NSL) for the definition of the XDR , CLIENT , and SVCXPRT data structures. Note that any buffers passed to the XDR routines must be properly aligned. It is suggested that malloc(3C) be used to allocate these buffers or that the programmer insure that the buffer address is divisible evenly by four.
#include <rpc/xdr.h>
A macro that invokes the destroy routine associated with the XDR stream, xdrs . Destruction usually involves freeing private data structures associated with the stream. Using xdrs after invoking xdr_destroy(), readit is called. The behavior of these two routines is similar to the system calls read() and write() (see read(2) and write(2) , respectively), except that an appropriate handle (read_handle or write_handle ) is passed to the former routines as the first parameter instead of a file descriptor. Note: the XDR stream's op field must be set by the caller.
Warning: this XDR stream implements an intermediate record stream. Therefore there are additional bytes in the stream to provide record boundary information.
This routine initializes the XDR stream object pointed to by xdrs . The XDR stream data is written to, or read from, the standard I/O stream file . The parameter op determines the direction of the XDR stream (either XDR_ENCODE , XDR_DECODE , or XDR_FREE ).
Warning: the destroy routine associated with such XDR streams calls fflush() on the file stream, but never fclose() (see fclose(3C) ).
Failure of any of these functions can be detected by first initializing the x_ops field in the XDR structure (xdrs => x_ops ) to NULL before calling the xdr*_create() function. After the return from the xdr*_create() function, if the x_ops field is still NULL, the call has failed. If the x_ops field contains some other value, the call can be assumed to have succeeded.
See attributes(5) for descriptions of the following attributes:
read(2) , write(2) , fclose(3C) , malloc(3C) , rpc(3NSL) , xdr_admin(3NSL) , xdr_complex(3NSL) , xdr_simple(3NSL) , attributes(5)
NAME | DESCRIPTION | ATTRIBUTES | SEE ALSO
|
http://docs.oracle.com/cd/E19455-01/806-0628/6j9vie84j/index.html
|
CC-MAIN-2014-52
|
refinedweb
| 333
| 63.29
|
SOAP::Lite - Client and server side SOAP implementation
use SOAP::Lite; print SOAP::Lite -> uri('') -> proxy('') -> f2c(32) -> result;
The same code with autodispatch:
use SOAP::Lite +autodispatch => uri => '', proxy => ''; print f2c(32);
Code in OO-style:
use SOAP::Lite +autodispatch => uri => '', proxy => ''; my $temperatures = Temperatures->new(32); # get object print $temperatures->as_celsius; # invoke method
Code with service description:
use SOAP::Lite; print SOAP::Lite -> service('') -> getQuote('MSFT');
Code for SOAP server (CGI):
use SOAP::Transport::HTTP; SOAP::Transport::HTTP::CGI -> dispatch_to('/Your/Path/To/Deployed/Modules', 'Module::Name', 'Module::method') -> handle;
Visual Basic client (through COM interface):
MsgBox CreateObject("SOAP.Lite").new( _ "proxy", "", _ "uri", "urn:xmethods-delayed-quotes" _ ).getQuote("MSFT").result
mod_soap enabled SOAP server:
.htaccess SetHandler perl-script PerlHandler Apache::SOAP PerlSetVar dispatch_to "/Your/Path/To/Deployed/Modules, Module::Name"
ASP/VB SOAP server:
<% Response.ContentType = "text/xml" Response.Write(Server.CreateObject("SOAP.Lite") _ .server("SOAP::Server") _ .dispatch_to("/Your/Path/To/Deployed/Modules") _ .handle(Request.BinaryRead(Request.TotalBytes)) _ ) %>
SOAP::Lite is a collection of Perl modules which provides a simple and lightweight interface to the Simple Object Access Protocol (SOAP) both on client and server side.
This version of SOAP::Lite supports the SOAP 1.1 specification ( ).
The main features of the library are:
See t/*.t, examples/*.pl and the module documentation for a client-side examples that demonstrate the serialization of a SOAP request, sending it via HTTP to the server and receiving the response, and the deserialization of the response. See examples/server/* SOAP::Transport::IO.pm -- SOAP::Transport::IO::Server -- Server interface to IO transport
All methods that
SOAP::Lite provides can be used for both setting and retrieving values. If you provide no parameters, you will get current value, and if parameters are provided, a new value will be assigned to the object and the method in question will return the current object (if not stated otherwise). This is suitable for stacking these calls like:
$lite = SOAP::Lite -> uri('') -> proxy('') ;
The order is insignificant and you may call the new() method first. If you don't do it, SOAP::Lite will do it for you. However, the new() method gives you an additional syntax:
$lite = new SOAP::Lite uri => '', proxy => '' ;
new() accepts a hash with method names as keys. It will call the appropriate methods together with the passed values. Since new() is optional it won't be mentioned anymore.
Provides access to the "SOAP::Transport" object. The object will be created for you. You can reassign it (but generally you should not).
Provides access to the "SOAP::Serializer" object. The object will be created for you. You can reassign it (but generally you should not).
Shortcut for
transport->proxy(). This lets you specify an endpoint (service address) and also loads the required module at the same time. It is required for dispatching SOAP calls. The name of the module will be defined depending on the protocol specific for the endpoint. The prefix
SOAP::Transport will be prepended, the module will be loaded and object of class (with appended
::Client) will be created.
For example, for, the class for creating objects will look for
SOAP::Transport:HTTP::Client;
In addition to endpoint parameter, proxy() can accept any transport specific parameters that could be passed as name => value pairs. For example, to specify proxy settings for HTTP protocol you may do:
$soap->proxy('', proxy => ['http' => '']);
Notice that since proxy (second one) expects to get more than one parameter you should wrap them in array.
Another useful example can be the client that is sensitive to cookie-based authentication. You can provide this with:
$soap->proxy('', cookie_jar => HTTP::Cookies->new(ignore_discard => 1));
You may specify timeout for HTTP transport with following code:
$soap->proxy('', timeout => 5);
Lets you specify an endpoint without changing/loading the protocol module. This is useful for switching endpoints without switching protocols. You should call
proxy() first. No checks for protocol equivalence will be made.
Lets you specify the kind of output from all method calls. If
true, all methods will return unprocessed, raw XML code. You can parse it with XML::Parser, SOAP::Deserializer or any other appropriate module.
Shortcut for
serializer->autotype(). This lets you specify whether the serializer will try to make autotyping for you or not. Default setting is
true.
Shortcut for
serializer->readable(). This lets you specify the format for the generated XML code. Carriage returns <CR> and indentation will be added for readability. Useful in the case you want to see the generated code in a debugger. By default, there are no additional characters in generated XML code.>
Shortcut for
serializer->namespace(). This lets you specify the default namespace for generated envelopes (
'SOAP-ENV' by default).
Shortcut for
serializer->encodingspace(). This lets you specify the default encoding namespace for generated envelopes (
'SOAP-ENC' by default).
Shortcut for
serializer->encoding(). This lets you specify the encoding for generated envelopes. It does not actually change envelope encoding, it will just modify the XML declaration (
'UTF-8' by default). Use
undef value to not generate XML declaration.
Shortcut for
serializer->typelookup(). This gives you access to the
typelookup table that is used for autotyping. For more information see "SOAP::Serializer".
Shortcut for
serializer->uri(). This lets you specify the uri for SOAP methods. Nothing is specified by default and your call will definitely fail if you don't specify the required uri.
WARNING: URIs are just identifiers. They may look like URLs, but they are not guaranteed to point to anywhere and shouldn't be used as such pointers. URIs assume to be unique within the space of all XML documents, so consider them as unique identifiers and nothing else.
Shortcut for
serializer->multirefinplace(). If true, the serializer will put values for multireferences in the first occurrence of the reference. Otherwise it will be encoded as top independent element, right after
method element inside
Body. Default value is
false.
DEPRECATED: Use SOAP::Header instead.
Shortcut for
serializer->header(). This lets you specify the header for generated envelopes. You can specify
root,
mustUnderstand or any other header using "SOAP::Data" class:
$serializer = SOAP::Serializer->envelope('method' => 'mymethod', 1, SOAP::Header->name(t1 => 5)-.
This lets you specify a handler for
on_action event. It is triggered when creating SOAPAction. The default handler will set SOAPAction to
"uri#method". You can change this behavior globally (see "DEFAULT SETTINGS") or locally, for a particular object.
This lets you specify a handler for
on_fault event. The default behavior is to die on an transport error and to do nothing on other error conditions. You may change this behavior globally (see "DEFAULT SETTINGS") or locally, for a particular object.
This lets you specify a handler for
on_debug event. Default behavior is to do nothing. Use
+trace/+debug option for SOAP::Lite instead. If you use if be warned that since this method is just interface to
+trace/+debug it has global effect, so if you install it for one object it'll be in effect for all subsequent calls (even for other objects).
See also: SOAP::Trace;
This lets you specify a handler for
on_nonserialized event. The default behavior is to produce a warning if warnings are on for everything that cannot be properly serialized (like CODE references or GLOBs).
Provides alternative interface for remote method calls. You can always run
SOAP::Lite->new(...)->method(@parameters), but call() gives you several additional options:
If you want to specify prefix for generated method's element one of the available options is do it with call() interface:
print SOAP::Lite -> new(....) -> call('myprefix:method' => @parameters) -> result;
This example will work on client side only. If you want to change prefix on server side you should override default serializer. See examples/server/soap.* for examples.
If for some reason you want to get access to remote procedures that have the same name as methods of SOAP::Lite object these calls (obviously) won't be dispatched. In that case you can originate your call trough call():
print SOAP::Lite -> new(....) -> call(new => @parameters) -> result;
With autodispatch you can make CLASS/OBJECT calls like:
my $obj = CLASS->new(@parameters); print $obj->method;
However, because of side effects autodispatch has, it's not always possible to use this syntax. call() provides you with alternative:
# you should specify uri() my $soap = SOAP::Lite -> uri('') # <<< CLASS goes here # ..... other parameters ; my $obj = $soap->call(new => @parameters)->result; print $soap->call(method => $obj)->result; # $obj object will be updated here if necessary, # as if you call $obj->method() and method() updates $obj # Update of modified object MAY not work if server on another side # is not SOAP::Lite
Additionally this syntax lets you specify attributes for method element:
print SOAP::Lite -> new(....) -> call(SOAP::Data->name('method')->attr({xmlns => 'mynamespace'}) => @parameters) -> result;
You can specify any attibutes and
name of
SOAP::Data element becomes name of method. Everything else except attributes is ignored and parameters should be provided as usual.
Be warned, that though you have more control using this method, you should specify namespace attribute for method explicitely, even if you made uri() call earlier. So, if you have to have namespace on method element, instead of:
print SOAP::Lite -> new(....) -> uri('mynamespace') # will be ignored -> call(SOAP::Data->name('method') => @parameters) -> result;
do
print SOAP::Lite -> new(....) -> call(SOAP::Data->name('method')->attr({xmlns => 'mynamespace'}) => @parameters) -> result;
because in the former call uri() will be ignored and namespace won't be specified. If you run script with
-w option (as recommended) SOAP::Lite gives you a warning:
URI is not provided as attribute for method (method)
Moreover, it'll become fatal error if you try to call it with prefixed name:
print SOAP::Lite -> new(....) -> uri('mynamespace') # will be ignored -> call(SOAP::Data->name('a:method') => @parameters) -> result;
gives you:
Can't find namespace for method (a:method)
because nothing is associated with prefix
'a'.
One more comment. One case when SOAP::Lite will change something that you specified is when you specified prefixed name and empty namespace name:
print SOAP::Lite -> new(....) -> uri('') -> call('a:method' => @parameters) -> result;
This code will generate:
<method xmlns="">....</method>
instead of
<a:method xmlns:....</method>
because later is not allowed according to XML Namespace specification.
In all other aspects
->call(mymethod => @parameters) is just a synonim for
->mymethod(@parameters).
Returns object reference to global defaul object specified with
use SOAP::Lite ... interface. Both class method and object method return reference to global object, so:
use SOAP::Lite proxy => '' ; my $soap = SOAP::Lite->proxy(''); print $soap->self->proxy;
prints
'' (the same as
SOAP::Lite->self->proxy). See "DEFAULT SETTINGS" for more information.
Does exactly the same as autodispatch does, but doesn't install UNIVERSAL::AUTOLOAD handler and only install AUTOLOAD handlers in specified classes. Can be used only with
use SOAP::Lite ... clause and should be specified first:
use SOAP::Lite dispatch_from => ['A', 'B'], # use "dispatch_from => 'A'" for one class uri => ...., proxy => ...., ; A->a; B->b;
The SOAP::Header class is a subclass of the "SOAP::Data" class. It is used in the same way as a SOAP::Data object, however SOAP::Lite will serialize objects of this type into the SOAP Envelope's Header block.
You can use this class if you want to specify a value, a name, atype, a uri or attributes for SOAP elements (use
value(),
name(),
type(),
uri() and
attr() methods correspondingly). For example,
SOAP::Data->name('abc')->value(123) will be serialized into
<abc>123</abc>, as well as will
SOAP::Data->name(abc => 123). Each of them (except the value() method) can accept a value as the second parameter. All methods return the current value if you call them without parameters. The return the object otherwise, so you can stack them. See tests for more examples. You can import these methods with:
SOAP::Data->import('name');
or
import SOAP::Data 'name';
and then use
name(abc => 123) for brevity.
An interface for specific attributes is also provided. You can use the
actor(),
mustUnderstand(),
encodingStyle() and
root() methods to set/get values of the correspondent attributes.
SOAP::Data ->name(c => 3) ->encodingStyle('')
will be serialized into:
('ordered_hash' => [a => 1, b => 2])
will be serialized as an ordered hash, using the
as_ordered_hash method.:
$s->typelookup->{uriReference} = [11, sub { $_[0] =~ m!^http://! }, 'as_uriReference'];
and add the
as_uriReference method to the "SOAP::Serializer" class:
sub SOAP::Serializer::as_uriReference { my $self = shift; my($value, $name, $type, $attr) = @_; return [$name, {'xsi:type' => 'xsd:uriReference', %$attr}, $value]; }
The specified methods will work for both autotyping and direct typing, so you can use either
SOAP::Data->type(uriReference => '')>
or just
''
and it will be serialized into the same type. For more examples see
as_* methods in "SOAP::Serializer".
The SOAP::Serializer provides you with
autotype(),
readable(),
namespace(),
encodingspace(),
encoding(),
typelookup(),
uri(),
multirefinplace() and
envelope() methods. All methods (except
envelope()) are described in the "SOAP::Lite" section.
This method allows you to build three kind of envelopes depending on the first parameter:
envelope(method => 'methodname', @parameters);
or');
or
freeform('something that I want to serialize');
Reserved for nonRPC calls. Lets you build your own payload inside a SOAP envelope. All SOAP 1.1 specification rules are enforced, except method specific ones. See UDDI::Lite as example.');
The xmlschema subroutine tells SOAP::Lite what XML Schema to use when serializing XML element values. There are two supported schemas of SOAP::Lite, they are:, and (default)
For more examples see tests and SOAP::Transport::HTTP.pm
All calls you are making through object oriented interface will return SOAP::SOM object, and you can access actual values with it. Next example gives you brief overview of the class:
my $soap = SOAP::Lite .....; my $som = $soap->method(@parameters); if ($som->fault) { # will be defined if Fault element is in the message print $som->faultdetail; # returns value of 'detail' element as # string or object $som->faultcode; # $som->faultstring; # also available $som->faultactor; # } else { $som->result; # gives you access to result of call # it could be any data structure, for example reference # to array if server didi something like: return [1,2]; $som->paramsout; # gives you access to out parameters if any # for example, you'll get array (1,2) if # server returns ([1,2], 1, 2); # [1,2] will be returned as $som->result # and $som->paramsall will return ([1,2], 1, 2) # see section IN/OUT, OUT PARAMETERS AND AUTOBINDING # for more information $som->paramsall; # gives access to result AND out parameters (if any) # and returns them as one array $som->valueof('//myelement'); # returns value(s) (as perl data) of # 'myelement' if any. All elements in array # context and only first one in scalar $h = $som->headerof('//myheader'); # returns element as SOAP::Header, so # you can access attributes and values # with $h->mustUnderstand, $h->actor # or $h->attr (for all attributes) }
SOAP::SOM object ('<', '>', '<=', '>=', '!', '=').
All nodes in nodeset will be returned in document order.
Accepts a path to a node and returns true/false in a boolean context and a SOM object otherwise.
valueof() and
dataof() can be used to get value(s) of matched node(s).
Returns the value of a (previously) matched node. It accepts a node path. In this case, it returns the value of matched node, but does not change the current node. Suitable when you want to match a node and then navigate through node children:
.
Same as
valueof(), but it returns a "SOAP::Data" object, so you can get access to the name, the type and attributes of an element.
Same as
dataof(), but it returns "SOAP::Header" object, so you can get access to the name, the type and attributes of an element. Can be used for modifying headers (if you want to see updated header inside Header element, it's better to use this method instead of
dataof() method).
Returns the uri associated with the matched element. This uri can also be inherited, for example, if you have
undefined element. To distinguish between these two cases you can first access the
match() method that will return true/false in a boolean context and then get the real value:
if ($som->match('//myparameter')) { $value = $som->valueof; # can be undef too } else { # doesn't exist }
Returns the value (as hash) of the root element. Do exactly the same as
$som->valueof('/') does.
Returns the value (as hash) of the
Envelope element. Keys in this hash will be 'Header' (if present), 'Body' and any other (optional) elements. Values will be the deserialized header, body, and elements, respectively. If called as function (
SOAP::SOM::envelope) it will return a Xpath string that matches the envelope content. Useful when you want just match it and then iterate over the content by yourself. Example:
if ($som->match(SOAP::SOM::envelope)) { $som->valueof('Header'); # should give access to header if present $som->valueof('Body'); # should give access to body } else { # hm, are we doing SOAP or what? }
Returns the value (as hash) of the
Header element. If you want to access all attributes in the header use:
# get element as SOAP::Data object $transaction = $som->match(join '/', SOAP::SOM::header, 'transaction')->dataof; # then you can access all attributes of 'transaction' element $transaction->attr;
Returns a node set of values with deserialized headers. The difference between the
header() and
headers() methods is that the first gives you access to the whole header and second to the headers inside the 'Header' tag:
Returns the value (as hash) of the
Body element.
Returns the value (as hash) of
Fault element:
faultcode,
faultstring and
detail. If
Fault element is present,
result(),
paramsin(),
paramsout() and
method() will return an undef.
Returns the value of the
faultcode element if present and undef otherwise.
Returns the value of the
faultstring element if present and undef otherwise.
Returns the value of the
faultactor element if present and undef otherwise.
Returns the value of the
detail element if present and undef otherwise.
Returns the value of the method element (all input parameters if you call it on a deserialized request envelope, and result/output parameters if you call it on a deserialized response envelope). Returns undef if the 'Fault' element is present.
Returns the value of the
result of the method call. In fact, it will return the first child element (in document order) of the method element.
Returns the value(s) of all passed parameters.
Returns value(s) of the output parameters.
Returns value(s) of the result AND output parameters as one array.
Return an array of MIME::Entities if the current payload contains attachments, or returns undefined if payload is not MIME multipart.
Returns true if payload is MIME multipart, false otherwise.
SOAP::Schema gives you ability to load schemas and create stubs according to these schemas. Different syntaxes are provided:
use SOAP::Lite service => '', # service => 'file:/your/local/path/StockQuoteService.wsdl', # service => 'file:./StockQuoteService.wsdl', ; print getQuote('MSFT'), "\n";
use SOAP::Lite; print SOAP::Lite -> service('') -> getQuote('MSFT'), "\n";
use SOAP::Lite; my $service = SOAP::Lite -> service(''); service=>'file:./quote.wsdl'" -le "print getQuote('MSFT')"
Other supported syntaxes with stub(s)
use SOAP::Lite; my $s = SOAP::Lite -> uri('') -> proxy('') -> on_debug(sub{print@_}) # show you request/response with headers ; print $s->GetVocabulary(SOAP::Data->name(Query => 'something')->uri('')) ->valueof('//FOUND');
or switch it on individually, with
use SOAP::Lite +trace => debug;
or
use SOAP::Lite +trace => [debug => sub {'do_what_I_want_here'}];
Compare this with:
use SOAP::Lite +trace => transport;
which gives you access.
Supports the SOAP Transport architecture. All transports must extend this class.
This class gives you access to Fault generated on server side. To make a Fault message you might simply die on server side and SOAP processor will wrap you message as faultstring element and will transfer Fault on client side. But in some cases you need to have more control over this process and SOAP::Fault class gives it to you. To use it, simply die with SOAP::Fault object as a parameter:
die SOAP::Fault->faultcode('Server.Custom') # will be qualified ->faultstring('Died in server method') ->faultdetail(bless {code => 1} => 'BadError') ->faultactor('');
faultdetail() and faultactor() methods are optional and since faultcode and faultstring are required to represent fault message SOAP::Lite will use default values ('Server' and 'Application error') if not specified.
This class gives you access to a number of subroutines to assist in data formating, encoding, etc. Many of the subroutines are private, and are not documented here, but a few are made public. They are:
Returns a valid xsd:datetime string given a time object returned by Perl's localtime function. Usage: print SOAP::Utils::format_datetime(localtime);
This class gives you access to number of options that may affect behavior of SOAP::Lite objects. They are not true contstants, aren't they?;
By default SOAP::Lite tries to load XML::Parser and if it fails, then to load XML::Parser::Lite. You may skip the first step and use XML::Parser::Lite even if XML::Parser is presented in your system if assign true value like this:
$SOAP::Constants::DO_NOT_USE_XML_PARSER = 1;
By default SOAP::Lite specifies charset in content-type. Since not every toolkit likes it you have an option to switch it off if you set
$DO_NOT_USE_CHARSET to true.
By default SOAP::Lite verifies that content-type in successful response has value 'multipart/related' or 'multipart/form-data' for MIME-encoded messages and 'text/xml' for all other ocassions. SOAP::Lite will raise exception for all other values.
$DO_NOT_CHECK_CONTENT_TYPE when set to true will allow you to accept those values as valid.
Though this feature looks similar to autodispatch they have (almost) nothing in common. It lets you create default object and all objects created after that will be cloned from default object and hence get its properties. If you want use
SOAP::Lite->self->proxy('');:
package My::PingPong; sub new { my $self = shift; my $class = ref($self) || $self; bless {_num=>shift} => $class; } sub next { my $self = shift; $self->{_num}++; }
client:
use SOAP::Lite +autodispatch => uri => 'urn:', proxy => '' ; my $p = My::PingPong->new(10); # $p->{_num} is 10 now, real object returned print $p->next, "\n"; # $p->{_num} is 11 now!, object autobinded
WARNING:
autodispatch (see
implementation of OO:
print $p->SOAP::next, "\n";
See
pingpong.pl for example of a script, that works with the same object locally and remotely.
SOAP:: prefix also gives you ability to access methods that have the same name as methods of SOAP::Lite itself. For example, you want to call method new() for your class
My::PingPong through OO interface. First attempt could be:
my $s = SOAP::Lite -> uri('') -> proxy('') ; my $obj = $s->new(10);
but it won't work, because SOAP::Lite has method new() itself. To provide a hint, you should use
SOAP:: prefix and call will be dispatched remotely:
my $obj = $s->SOAP::new(10);
You can mix autodispatch and usual SOAP calls in the same code if you need it. Keep in mind, that calls with SOAP:: prefix should always be a method call, so if you want to call functions, use
SOAP->myfunction() instead of.
You should also use static binding when you have several different classes in one file and want to make them available for SOAP calls.
SUMMARY: experimental syntax that allows you bind specific URL or SOAPAction to CLASS/MODULE or object:
dispatch_with({ URI => MODULE, # '' => 'My::Class', SOAPAction => MODULE, # '' => 'Another::Class', URI => object, # '' => My::Class->new, })
URI is checked before SOAPAction. You may use both
dispatch_to() and
dispatch_with() syntax and
dispatch_with() has more priority, so first checked URI, then SOAPAction and only then will be checked
dispatch_to(). See t/03-server.t for more information and examples.
Due to security reasons, the current path for perl modules (
@INC) will be disabled once you have chosen dynamic deployment and specified your own
PATH/. If you want to access other modules in your included package you have several options:
use MODULE; $server->dispatch_to('MODULE');
It can be useful also when you want to import something specific from the deployed modules:
use MODULE qw(import_list);
useto
require. The path is unavailable only during the initialization part, and it is available again during execution. So, if you do
requiresomewhere in your package, it will work.
eval 'use MODULE qw(import_list)'; die if $@;
@INCdirectory in your package and then make
use. Don't forget to put
@INCin
BEGIN{}block or it won't work:
BEGIN { @INC = qw(my_directory); use MODULE }
SOAP::Lite provides you option for enabling compression on wire (for HTTP transport only). Both server and client should support this capability, but this logic should be absolutely transparent for your application.
Compression can be enabled by specifying threshold for compression on client or server side:
print SOAP::Lite -> uri('') -> proxy('', options => {compress_threshold => 10000}) -> echo(1 x 10000) -> result ;
my $server = SOAP::Transport::HTTP::CGI -> dispatch_to('My::Parameters') -> options({compress_threshold => 10000}) -> handle;
For more information see COMPRESSION section in HTTP transport documentation.
SOAP::Lite implements an experimental (yet.
To use .NET client and SOAP::Lite server
use fully qualified names for your return values, e.g.:
return SOAP::Data->name('myname') ->type('string') ->uri('') ->value($output);
Use namespace that you specify for URI instead of ''.
In addition see comment about default incoding in .NET Web Services below.
To use SOAP::Lite client and .NET server
For example, use
on_action(sub{join '', @_}).
Specify
$SOAP::Constants::DO_NOT_USE_CHARSET = 1 somewhere in your code after
use SOAP::Lite if you are getting error:
Server found request content type to be 'text/xml; charset=utf-8', but expected 'text/xml'
Any of following actions should work:
Use
SOAP::Data->name(Query => 'biztalk')->uri('') instead of
SOAP::Data->name('Query' => 'biztalk').
Example of SOAPsh call (all parameters should be in one line):
> perl SOAPsh.pl "" "" "on_action(sub{join '', @_})" "GetVocabulary(SOAP::Data->name(Query => 'biztalk')->uri(''))"
instead of
my @rc = $soap->call(add => @parms)->result; # -- OR -- my @rc = $soap->add(@parms)->result;
use
my $method = SOAP::Data->name('add') ->attr({xmlns => ''}); my @rc = $soap->call($method => @parms)->result;; } } }
Thanks to Petr Janata <petr.janata@i.cz>, Stefan Pharies <stefanph@microsoft.com>, Brian Jepson <bjepson@jepstone.net>, and others for description and examples.://...';
See TROUBLESHOOTING section in documentation for HTTP transport.
Probably you didn't register Lite.dll with 'regsvr32 Lite.dll'
Probably you have two Perl installations in different places and ActiveState's Perl isn't the first Perl specified in PATH. Rename the directory with another Perl (at least during the DLL's startup) or put ActiveState's Perl on the first place in PATH.
SAX 2.0 has a known bug in org.xml.sax.helpers.ParserAdapter rejects Namespace prefix used before declaration
().
That means that in some cases SOAP messages created by SOAP::Lite may not be parsed properly by SAX2/Java parser, because Envelope element contains namespace declarations and attributes that depends on this declarations. According to XML specification order of these attributes is not significant. SOAP::Lite does NOT have a problem parsing such messages., don't have this problem and difference in processing time can be significant. For XML encoded string that has about 20 lines and 30 tags, number of call could be about 100 instead of one for the same string encoded as base64.() somewhere in your code after
use SOAP::Lite and before actual processing/sending:
*SOAP::Serializer::as_string = \&SOAP::Serializer::as_base64;
Be warned that last two methods will affect all strings and convert them into base64 encoded. It doesn't make any difference for SOAP::Lite, but it may make a difference for other toolkits.
As soon as you have telnet access to the box and XML::Parser is already installed there (or you have Perl 5.6 and can use XML::Parser::Lite) you may install your own copy of SOAP::Lite even if hosting provider doesn't want to do it.
Setup
PERL5LIB environment variable. Depending on your shell it may look like:
PERL5LIB=/you/home/directory/lib; export PERL5LIB
lib here is the name of directory where all libraries will be installed under your home directory.
Run CPAN module with
perl -MCPAN -e shell
and run three commands from CPAN shell
> o conf make_arg -I~/lib > o conf make_install_arg -I~/lib > o conf makepl_arg LIB=~/lib PREFIX=~ INSTALLMAN1DIR=~/man/man1 INSTALLMAN3DIR=~/man/man3
LIB will specify directory where all libraries will reside.
PREFIX will specify prefix for all directories (like lib, bin, man, though it doesn't work in all cases for some reason).
INSTALLMAN1DIR and
INSTALLMAN3DIR specify directories for manuals (if you don't specify them, install will fail because it'll try to setup it in default directory and you don't have permissions for that).
Then run:
> install SOAP::Lite
Now in your scripts you need to specify:
use lib '/your/home/directory/lib';
somewhere before
'use SOAP::Lite;'.
SOAP SOAP/Perl library from Keith Brown ( ) or ( )
A lot of thanks to Tony Hong <thong@xmethods.net>, Petr Janata <petr.janata@i.cz>, Murray Nesbitt <murray@ActiveState.com>, Robert Barta <rho@bigpond.net.au>, Gisle Aas <gisle@ActiveState.com>, Carl K. Cunningham <cc@roberts.de>, Graham Glass <graham-glass@mindspring.com>, Chris Radcliff <chris@velocigen.com>, Arun Kumar <u_arunkumar@yahoo.com>, and many many others
for providing help, feedback, support, patches and comments.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
Paul Kulchenko (paulclinger@yahoo.com) Byrne Reese (byrne@majordojo.com)
|
http://search.cpan.org/~byrne/SOAP-Lite-0.65_5/lib/OldDocs/SOAP/Lite.pm
|
CC-MAIN-2017-26
|
refinedweb
| 4,896
| 55.44
|
The code is now on CodePlex at and on nuget just search for "fastJSON" . I will do my best to keep this article and the source code on CodePlex in sync.
This is the smallest and fastest polymorphic JSON serializer, smallest because it's only 25kb when compiled, fastest because most of the time it is (see performance test section) and polymorphic because it can serialize and deserialize the following situation correctly at run-time with what ever object you throw at it:
class animal { public string Name { get; set;} }
class cat: animal { public int legs { get; set;} }
class dog : animal { public bool tail { get; set;} }
class zoo { public List<animal> animals { get; set;} }
var zoo1 = new zoo();
zoo1.animals = new List<animal>();
zoo1.animals.Add(new cat());
zoo1.animals.Add(new dog());
This is a very important point because it simplifies your coding immensely and is a cornerstone of object orientated programming, strangely few serializers handle this situation, even the XmlSerializer in .NET doesn't do this and you have to jump through hoops to get it to work. Also this is a must if you want to replace the BinaryFormatter serializer which what most transport protocols use in applications and can handle any .NET object structure (see my WCF Killer article).
XmlSerializer
JSON (Java Script Object Notation) is a text or human readable format invented by Douglas Crockford around 1999 primarily as a data exchange format for web applications (see). The benefits of which are ( in regards to XML which was used before):
So its good for the following scenarios:
$type
$schema
$map
object
HashTable
DataSet
DataTable
In this section I will discuss some of the JSON alternatives that I have personally used. Although I can't say it is a comprehensive list, it does however showcase the best of what is out there.
If you are using XML, then don't. It's too slow and bloated, it does deserve an honorable mention as being the first thing everyone uses, but seriously don't. It's about 50 times slower than the slowest JSON in this list. The upside is that you can convert to and from JSON easily.
Probably the most robust format for computer to computer data transfer. It has a pretty good performance although some implementation here beat it.
The most referenced JSON serializer for the .NET framework is Json.NET from () and the blog site (). It was the first JSON implementation I used in my own applications.
I had to look around a lot to find this gem (), which is still at version 0.5 since 2007. This was what I was using before my own implementation and it replaced the previous JSON serializer which was Json.NET. Admittedly I had to change the original to fit the requirements stated above.
An amazingly fast JSON serializer from Demis Bellot found at (). The serializer speed is astonishing, although it does not support what is needed from the serializer. I have included it here as a measure of performance.
By popular demand and my previous ignorance about the Microsoft JSON implementation and thanks to everyone who pointed this out to me, I have added this here.
To use the code do the following:
// to serialize an object to string
string jsonText = fastJSON.JSON.Instance.ToJSON(c);
// to deserialize a string to an object
var newobj = fastJSON.JSON.Instance.ToObject(jsonText);
The main class is JSON which is implemented as a singleton so it can cache type and property information for speed.
// you can set the defaults for the Instance which will be used for all calls
JSON.Instance.UseOptimizedDatasetSchema = true; // you can control the serializer dataset schema
JSON.Instance.UseFastGuid = true; // enable disable fast GUID serialization
JSON.Instance.UseSerializerExtension = true; // enable disable the $type and $map inn the output
// you can do the same as the above on a per call basis
public string ToJSON(object obj, bool enableSerializerExtensions)
public string ToJSON(object obj, bool enableSerializerExtensions, bool enableFastGuid)
public string ToJSON(object obj, bool enableSerializerExtensions, bool enableFastGuid, bool enableOptimizedDatasetSchema)
// Parse will give you a Dictionary<string,object> with ArrayList representation of the JSON input
public object Parse(string json)
// if you have disabled extensions or are getting JSON from other sources then you must specify
// the deserialization type in one of the following ways
public T ToObject<T>(string json)
public object ToObject(string json, Type type)
JSON.Instance.SerializeNullValues = true; // enable disable null values to output
public string ToJSON(object obj, bool enableSerializerExtensions, bool enableFastGuid, bool enableOptimizedDatasetSchema, bool serializeNulls)))
}
All test were run on the following computer:
The tests were conducted under three different .NET compilation versions
The Excel screen shots below are the results of these test with the following descriptions:
The following is the basic test code template, as you can see it is a loop of 5 tests of what we want to test each done count time (1000 times). The elapsed time is written out to the console with tab formatting so you can pipe it to a file for easier viewing in an Excel spreadsheet.
int count = 1000;
private static void fastjson_serialize()
{
Console.WriteLine();
Console.Write("fastjson serialize");
for (int tests = 0; tests < 5; tests++)
{
DateTime st = DateTime.Now;
colclass c;
string jsonText = null;
c = CreateObject();
for (int i = 0; i < count; i++)
{
jsonText = fastJSON.JSON.Instance.ToJSON(c);
}
Console.Write("\t" + DateTime.Now.Subtract(st).TotalMilliseconds + "\t");
}
}
The test data are the following classes which show the polymorphic nature we want to test. The "colclass" is a collection of these data structures. In the attached source files more exotic data structures like Hashtables, Dictionaries, Datasets etc. are included.
[Serializable()]
public class baseclass
{
public string Name { get; set; }
public string Code { get; set; }
}
[Serializable()]
public class class1 : baseclass
{
public Guid guid { get; set; }
}
[Serializable()]
public class class2 : baseclass
{
public string description { get; set; }
}
[Serializable()]
public class colclass
{
public colclass()
{
items = new
List<baseclass>();
date = DateTime.Now;
multilineString = @"
AJKLjaskljLA
ahjksjkAHJKS
AJKHSKJhaksjhAHSJKa
AJKSHajkhsjkHKSJKash
ASJKhasjkKASJKahsjk
";
gggg = Guid.NewGuid();
//hash = new Hashtable();
isNew = true;
done= true;
}
public bool done { get; set; }
public DateTime date {get; set;}
//public DataSet ds { get; set; }
public string multilineString { get; set; }
public List<baseclass> items { get; set; }
public Guid gggg {get; set;}
public decimal? dec {get; set;}
public bool isNew { get; set; }
//public Hashtable hash { get; set; }
}
In this section we will see the performance results for exotic data types like datasets, hash tables, dictionaries, etc.. The comparison is between fastJSON and the BinaryFormatter as most of the other serializers can't handle these data types. These include the following:
As you can see from the above picture v1.4 is noticably faster. The speed boost make fastJSON faster than SerializerStack in all tests even on .net v3.5.
Guid
UseFastGuid = false
Datasets
int
long
ChangeType
Dictionary
TryGetValue
I did a lot of performance tuning with a profiler and here are my results: :
DateTime
JSONParameters.DateTimeMilliseconds
.
DateTime
Tick
On a different note, I recently got a Raspberry Pi, installed mono on it and copied fastJSON on it, the results are below:
Raspberry Pi:
i7 4702MQ and 8gb
as you can see the Raspberry is ~100x slower, but still works.
Raspberry
You can check out previous versions of fastJSON here.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Parse()
ToDynamic().
|
http://www.codeproject.com/Articles/159450/fastJSON?fid=1610850&df=90&mpp=25&noise=3&prof=True&sort=Position&view=None&spc=Relaxed&select=4477951&fr=51
|
CC-MAIN-2014-41
|
refinedweb
| 1,222
| 51.28
|
Kinect v2 avatar controller with unity
I am trying to control 3D model with kinect v2. I am using Unity3D. I installed requiements. I drawed a point man. just like this pic:
[
But when I try 3d character the character looks like this:
[
This is my code:
void FixedUpdate () { //GameObject tanımlanmış mı kontrolü yapılır. if (BodySourceManager == null) { return; } //Tanımlı olduğu için içindeki scriptin ataması yapılır. _BodyManager = BodySourceManager.GetComponent<BodySourceManager>(); //Script ataması tamamlanlmış mı kontrolü yapılır. if (_BodyManager == null) { return; } //BodySourceManager scripti içerisindeki fonksiyon çağırılarak body değerleri alınır. Windows.Kinect.Body[] data = _BodyManager.GetData(); //Data değerleri başarıyla atanmışmı kontrolü yapılır. if (data == null) { return; } //Takip edilebilir kaç kişi var ise onun id numarası kayıt altına alınır. List<ulong> trackedIds = new List<ulong>(); foreach (var body in data) { if(body == null) { continue; } if (body.IsTracked) { trackedIds.Add(body.TrackingId); int JointOrder=0; foreach(var joints in jointTypes) { Windows.Kinect.Joint jointPoint = body.Joints[joints]; Vector3 JointPositionV = new Vector3(jointPoint.Position.X, jointPoint.Position.Y, jointPoint.Position.Z); BodyJoints[JointOrder].transform.position = JointPositionV * 20; JointOrder++; } } } }
Why does the body look like a monster??
- Unity Admob Integegration: Ads doent show anymore - but they used to?
I have a bit of a problem. I used to monetize my apps via admob or appodeal. I had one app monetized via appodeal and another one with around the same traffic via admob. I realized that admob generates more cash, so i changed my project from appodeal to admob. Even tho Im doing what is ask of me in the tutorials, and the debugger always states that a "dummy ad" is showing. My device will NOT display the ads. It will however do that on my other unity game.
All I am doing is this:
private InterstitialAd interstitial; private void LoadInterstitial() { MobileAds.Initialize(_appID); interstitial = new InterstitialAd(_adUnitId); AdRequest request = new AdRequest.Builder().Build(); interstitial.LoadAd(request); if (interstitial.IsLoaded()) { interstitial.Show(); } }
I have also noticed, that in my other project form earlier this year I didnt have to do the "MobileAds.Initizalize(_appID)" part. I didtn event need to provide an app id.
Can anyone help me? It used to work like a charm but now there is nothing!
THANKS :)
- Unity Hololens Crashes
I am coding an application that uses the camera using Unity and the Hololens. It works ok. Then I changed something (explained later) and I got the following errors after a crash:
d3d11: failed to create staging 2D texture w=896 h=504 d3dfmt=87 [887a0005]
d3d11: failed to lock buffer 1104C69C of size 4194304 [0x8007000E].
DrawBuffers() got a range of indices but no index buffer (Filename: C:\buildslave\unity\build\Runtime/GfxDevice/d3d11/DrawBuffersD3D11.cpp Line: 137)
I have searched for these errors and there are no solutions applicable. I hope I could get some insights on this.
What I was doing and what I changed
Basically the program acquired a frame from the camera in a array of bytes
byte[] _latestImage;
Originally this image is applied to a Texture as in
_videoTexture.LoadRawTextureData(_latestImage); _videoTexture.wrapMode = TextureWrapMode.Clamp; _videoTexture.Apply(); _videoPanelUIRenderer.sharedMaterial.SetTexture("_MainTex", _videoTexture);
where
_videoTextureis a Texture2D and
_videoPanelUIRendereris a Renderer.
This works right. Then I processed the array _latestImage to convert it to Grey inside a function
ProcessSync. This also works right with the only problem: Since the array is being processed (into Grey) but also is being updated automatically by the camera, when applying into a texture, it flickers, sometimes grey, and sometimes in color. But other than that, no crash.
So my next step was to Clone that array at the start of the processing function so that I can process this new array and apply it to a texture without the interference of new data coming from the camera.
so I did:
void ProcessSync(byte[] rawimage, Matrix4x4 cTwMatrix, Matrix4x4 pMatrix) { int rr, gg, bb; int p = 0; int yval; byte[] image=(byte[])rawimage.Clone();//<--THIS is the only change for (int y = 0; y < height; y++) for (int x = 0; x < width; x++) { //...some processing here } //Then apply it to the texture like indicated above }
When I apply this, the application works fine, and I can see that I am getting the grey image...but after some time it crashes with the message above.
My image is 896x504 so I guess
d3d11: failed to create staging 2D texture w=896 h=504 d3dfmt=87 [887a0005]
means that somehow the Texture2D failed to be created but why? My texture is only created once when the video mode is being initialized so I don't understand why this happens.
I guess the error could be related with me cloning the image. Can anyone help me here?
- saving gameObject layer always ends up as default (Unity + VS)
So, I've been following this guide: To make a space shooter game.
The idea is that two objects under layer "Enemy" won't collide, But when the object under layer "Player" collides with "Enemy" it becomes part of "invulnerable" layer that doesn't collide with anything.
but it seems that one line at the code (this one:)
gameObject.layer = correctLayer;
turns my object into "Default" layer every time. this is the code:
using System.Collections; using System.Collections.Generic; using UnityEngine; [AddComponentMenu("WaterEffects/ForCamera")] public class HitHandler : MonoBehaviou { public int health = 1; //Object health float invulnTimer = 0.25f; //Time in which the gameObject is invulnerable int correctLayer; // save the original layer of the object void start() { correctLayer = gameObject.layer; gameObject.SetActive(true); } void OnTriggerEnter2D() { Debug.Log("Trigger!"); health--; invulnTimer = 2f; gameObject.layer = 10; //put object in invulnerable layer } // Update is called once per frame void Update() { invulnTimer -= Time.deltaTime; if (invulnTimer <= 0) { gameObject.layer = correctLayer; //returns object to original layer (doesnt work) } if (health <= 0) { Die(); } } void Die() { Destroy(gameObject); // Destroys object } }
I have no idea why the start function doesn't save the right layer, even though in unity i have defined the objects as their reflective layers.
Note: I have made the objects Kinematic and checked IsTrigger. When the first mentioned line of code is not in use it does work.
- How to get Unique KinectID for kinect camera
I tried to get unique id for the kinect camera using the following code:
var kinectId = KinectSensor.GetDefault().UniqueKinectID
When i debug through the code and evaluate the expression I am able to see a value being assigned but When I am jst running through the code, no value is being assigned. Did anyone face this issue?
- Displaying WriteableBitmap in Image in C# Visual Studio 2017
I'm using Visual Studio 2017. I've got a
WriteableBitmapthat I want to display to the user. To do that, I've got this component in my
MainWindow.xaml:
<Image x:
Now I try to assign the image to the component like so in the
MainWindow.xaml.cs:
FrameDisplayImage.Source = this.colorBitmap;
This doesn't work, the error is that the name
FrameDisplayImageis not available in the current context.
I'm probably missing some include or connection between the xaml and the cs - but I'm completely new to C# and can't get it to work. Can someone point me in the right direction?
- Where can I find and understand Kinect V2 Basic Face Tracking algorithm?
I'm working on my thesis using Kinect Windows V2 and I'm so excited and surprised of the Basic Face Tracking SDK of the Kinect. However, I've searched for some time but I hardly found papers discussing about its algorithms. Therefore, I wish to know from any experts here where can I have the source to understand the algorithm in order to fully utilize it?
Any reply is much appreciated. Thank you.
|
http://quabr.com/45648685/kinect-v2-avatar-controller-with-unity
|
CC-MAIN-2017-47
|
refinedweb
| 1,278
| 56.96
|
C++ provides statements break and continue to alter the flow of the control. Given below I have explained how break can be used to terminate a switch statement’s execution. This article discusses how to use break in a repetition statement.
the break statement, when executed in a while, for, do...while or switch statement, causes immediate exit from that statement. Program execution continues with the next statement. Common uses of a switch statement are to escape early from a loop or to skip the remainder of a switch statement. There is code given ahead in the article that demonstrates the break statement exiting a for repetition statement.
When the if statement detects that count is 5, the break statement executes. This terminates the for statement, and the program proceeds to line 18 (immediately after the for statement), which displays a message indicating the control variable value that terminated the loop. The for statement fully executes its body only four times instead of 10. The control variable count is defined outside the for statement header, so that we can use the control variable both in the loop’s body and after the loop completes its execution.
#include <iostream>
using namespace std;
int main()
{
unsigned int count; //control variable also used after loop terminates
for ( count = 1; count <= 10; ++count) //loop 10 times
{
if ( count == 5 )
break; // break loop only if count is 5
cout << count << " " ;
} // end for
cout << "\nBroke out of loop at count = " << count < endl;
}
// end main
1 2 3 4 5
Broke out of loop at count = 5
|
https://kodlogs.com/blog/2664/what-does-break-do-in-c
|
CC-MAIN-2021-04
|
refinedweb
| 260
| 59.84
|
Deep Learning with Tensorflow 2.0 Tutorial – Getting Started with Tensorflow 2.0 and Keras for Beginners
Classification using Fashion MNIST dataset
What is TensorFlow?
Deep Learning.
TensorFlow architecture works in three parts:
- Preprocessing the data
- Build the model
- Train and estimate the model
Why Every Data Scientist should Learn Tensorflow 2.x and not Tensorflow 1.x?
- API Cleanup
- Eager execution
- No more globals
- Functions, not sessions (session.run())
- Use Keras layers and models to manage variables
- It is faster
- It takes less space
- More consistent
For more information you can visit these links:-
- Google I/O:
-
-
You can
install TensorFlow by running the following command in the
Anaconda admin shell.
pip install tensorflow
If you have
GPU in your machine then you can run this command to install the GPU version of
TensorFlow.
pip install tensorflow-gpu
Fashion MNIST dataset
We are going to use the Fasion Mnist dataset. It consists of a training set of 60,000 examples and a test set of 10,000 examples. All the 70,000 images show individual articles of clothing at low resolution (28 by 28 pixels). The grayscale images are from 10 categories(T-shirt/top, Trouser, Pullover, Dress, Coat, Sandal, Shirt, Sneaker, Bag, Ankle boot) as seen here:
You can download the actual dataset from here.
In this notebook we are goint to use the
fashion_mnist dataset which is available in
keras.
import tensorflow as tf from tensorflow import keras
print(tf.__version__)
2.1.0
The necessary python libraries are imported here-
numpyis used to perform basic operations.
pyplotfrom
matplotlibis used to visualize the results.
pandasis used to read the dataset.
import numpy as np import pandas as pd import matplotlib.pyplot as plt
Here we are loading the
fashion_mnist dataset from
keras.
mnist = keras.datasets.fashion_mnist
The dataset is downloaded in
TFModuleWrapper.
type(mnist)
module
Now we load the data into real variables using
load_data(). It return 2 tuples. The first tupes has the
training data and the second tuple has the
test data.
(X_train, y_train), (X_test, y_test) = mnist.load_data()
By using
shape we can see that it has 60,000 images for training and each image is of size 28×28 in
X_train and a corresponding label for each image in
y_train.
X_train.shape, y_train.shape
((60000, 28, 28), (60000,))
np.max() gives the maximum value. Hence the maximum value in
X_train is 255. We can even see the minimum value using
np.min(X_train). The minimum value will be 0.
np.max(X_train)
255
np.mean() gives the mean value. The mean value in
X_train is 72.94
np.mean(X_train)
72.94035223214286
As we know the images are divided into 10 categories. The 10 categories are encoded using a numerical value as show below.
y_train
array([9, 0, 0, ..., 3, 0, 5], dtype=uint8)
These are all the class name in their proper order.
top is encoded as
0,
trouser is encoded as
1 and so on.
class_names = ['top', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
Data Exploration
X_train.shape
(60000, 28, 28)
The testing data set containes 10000 images of size 28×28.
X_test.shape
(10000, 28, 28)
Here we have plotted the second image of our training set i.e. the image at index 1.
The
plt.figure() function in pyplot module of matplotlib library is used to create a new figure. The
plt.imshow() function in pyplot module of matplotlib library is used to display data as an image.
plt.colorbar() displays the colour bar besides the image. You can see that the values are between
0 and 255.
plt.figure() plt.imshow(X_train[1]) plt.colorbar()
As you can see the image is a top and the value at index 1 of
y_train also corresponds to the class name
top.
y_train
array([9, 0, 0, ..., 3, 0, 5], dtype=uint8)
Neural Network model doesn’t take value greater than 1. So we need to bring all the values between
0 and 1. To do this we will divide all the values in the training and testing dataset by 255 as the greatest value in our dataset is 255.
X_train = X_train/255.0 X_test = X_test/255.0
Now we can see that all the values are between
0 and 1.
plt.figure() plt.imshow(X_train[1]) plt.colorbar()
Build the model with TF 2.0
We will import the necessary layers to build the model. The Neural Network is constructed from 3 type of layers:
Input layer— initial data for the neural network.
Hidden layers— intermediate layer between input and output layer and place where all the computation is done.
Output layer— produce the result for given inputs.
from tensorflow.keras import Sequential from tensorflow.keras.layers import Flatten, Dense
Flatten() is used as the
input layer to convert the data into a 1-dimensional array for inputting it to the next layer. Our image 2D image will be converted to a single 1D column.
input_shape = (28,28) because the size of our input image is 28×28.
Dense() layer is the regular deeply connected neural network layer. It is most common and frequently used layer. We have a dense layer with
128 neurons with activation function
relu. The rectified linear activation function or ReLU for short is a piecewise linear function that will output the input directly if it is positive, otherwise, it will output zero.
The
output layer is a
dense layer with
10 neurons because we(Flatten(input_shape = (28, 28))) model.add(Dense(128, activation = 'relu')) model.add(Dense(10, activation = 'softmax'))
model.summary()
Model: "sequential_1" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= flatten_1 (Flatten) (None, 784) 0 _________________________________________________________________ dense_2 (Dense) (None, 128) 100480 _________________________________________________________________ dense_3 (Dense) (None, 10) 1290 ================================================================= Total params: 101,770 Trainable params: 101,770 Non-trainable params: 0 _________________________________________________________________
Model compilation
Loss Function: A loss function is used to optimize the parameter values in a neural network model. Loss functions map a set of parameter values for the network onto a scalar value that indicates how well those parameter accomplish the task the network is intended to do.
Optimizer: Optimizers are algorithms or methods used to change the attributes of your neural network such as weights and learning rate in order to reduce the losses.
Metrics: A metric is a function that is used to judge the performance of your model. Metric functions are similar to loss functions, except that the results from evaluating a metric are not used when training the model.
Here we are
compiling the model and
fitting it to the training data. We will use 10
epochs to train the model. An epoch is an iteration over the entire data provided.
model.compile(optimizer='adam', loss = 'sparse_categorical_crossentropy', metrics = ['accuracy']) model.fit(X_train, y_train, epochs = 10)
Train on 60000 samples Epoch 9/10 60000/60000 [==============================] - 5s 79us/sample - loss: 0.2472 - accuracy: 0.9081 Epoch 10/10 60000/60000 [==============================] - 5s 80us/sample - loss: 0.2374 - accuracy: 0.9120
Now we will evaluate the accuracy using the
test data. We have got an accuracy of 88.41%.
test_loss, test_acc = model.evaluate(X_test, y_test) print(test_acc)
10000/10000 [==============================] - 1s 81us/sample - loss: 0.3312 - accuracy: 0.8841 0.8841
Now we are going to do predictions using
sklearn and see the accuracy. For that we will import
accuracy_score from
sklearn.
from sklearn.metrics import accuracy_score
predict_classes generates class predictions for the input samples. Here we are giving
X_test containing 10000 images as the input. We are even predicting the accuracy. In multilabel classification,
accuracy_score computes subset accuracy: the set of labels predicted for a sample must exactly match the corresponding set of labels in
y_test.
y_pred = model.predict_classes(X_test) accuracy_score(y_test, y_pred)
0.8841
Now we will use this model to perform predictions on an input image.
y_pred
array([9, 2, 1, ..., 8, 1, 5], dtype=int64)
predict() returns an array unlike
predict_class() which returns categorical values. The array contains the confidence level for each of the class.
pred = model.predict(X_test) pred
array([[2.3493649e-07, 1.7336136e-09, 3.9774801e-09, ..., 1.7785656e-03, 3.6985359e-08, 9.9811894e-01], [7.2894422e-06, 5.1075269e-15, 9.9772221e-01, ..., 2.2120526e-12, 6.0182694e-09, 2.4706193e-16], [1.3015335e-07, 9.9999988e-01, 3.9984838e-12, ..., 1.3045939e-23, 3.1408490e-11, 2.1719039e-15], ...
As you can see for the test image at index 0,
predict has retured this array. In this the value at index 9 is the greatest. This shows that the model has predicted the test image at index 0 to have class 9 which is
ankle boot.
pred[0]
array([2.3493649e-07, 1.7336136e-09, 3.9774801e-09, 1.0847069e-08, 2.9475926e-09, 1.0172284e-04, 3.8994517e-07, 1.7785656e-03, 3.6985359e-08, 9.9811894e-01], dtype=float32)
argmax() returns the index of the maximum value. Hence we can see that the predicted class is 9 as maximum value is found at index position 9.
np.argmax(pred[0])
9
For the second image in the
test data i.e. the image at index 1 the predicted class is 2 which is
pullover.
np.argmax(pred[1])
2
The model gives an accuracy of
91.2% on the
training data and
88.41% on
test data. Hence. To avoid overfitting we can use
Convolutional Neural Networks.
|
https://kgptalkie.com/deep-learning-with-tensorflow-2-0-tutorial-getting-started-with-tensorflow-2-0-and-keras-for-beginners/
|
CC-MAIN-2021-17
|
refinedweb
| 1,557
| 58.79
|
On Tue, 10 May 2005, Simon Marlow wrote: > > 2. The GHC build could start using -fignore-all-packages to insulate > itself from the environment (or, simpler but more hacky: > -ignore-package lang). This isn't a *solution* as such, because > the problem affects everyone, not just us. I'm slightly surprised that this isn't already the default, and that probably explains the recent argument. In the C world the only libraries that matter to the build environment are the ones you explicitly pull in. Overlaps still matter but only within your program. On the other hand Perl's module namespace is global, and a (usually implicit) search path is used to resolve conflicts. I greatly prefer the former model. Perl is a real pain if you want multiple parallel installations of slightly different versions of the same code - you effectively need a separate Perl installation for each installed version of a program that uses Perl. Perhaps the missing idea is the package configuration step, during which its dependencies are resolved to installed libraries on the build machine and any conflicts are dealt with. The.
|
http://www.haskell.org/pipermail/libraries/2005-May/003764.html
|
CC-MAIN-2014-10
|
refinedweb
| 185
| 53.41
|
Eric's “Killing Comment Spam“ post and Luke Hutteman's comment sparked a little adventure for me. Of course, it's not complete or very functional. It's more of a motivation piece to get something started. I might have to jump into the .Text source to see about implementing some sort of plugin. I know .Text (Community Server :: Blogs) is provider based so it might be fairly easy to implement this into the Comment Provider... if there is such a beast. Here's a little bit of test code that grabs the MT-BlackList from the Comment Spam ClearingHouse.
namespace BlackList{ class Check { public static void Main(string[] args) { ArrayList expressions = new ArrayList(); expressions = BuildBlackList(); if ( expressions.Count > 0 ) { foreach (string expression in expressions) { try { Regex pattern = new Regex(expression, RegexOptions.Multiline|RegexOptions.IgnoreCase); if (pattern.IsMatch("01-logo.com")) Console.WriteLine("Found A Match"); pattern = null; } catch {} } } Console.ReadLine(); } private static ArrayList BuildBlackList() { // In reality this file would be local and downloaded once a // day. Or, if we were in a web environment we could cache it. // But, hey, its just a demo to spark some thought. // string url = ""; ArrayList expressions = new ArrayList(); WebResponse response = null; try { WebRequest request = WebRequest.Create(url); if (request != null) { response = request.GetResponse(); using (StreamReader sr = new StreamReader(response.GetResponseStream())) { String line; while ((line = sr.ReadLine()) != null) { if (line.Substring(0,1) != "#" ) expressions.Add(line); } } } } catch(Exception) { throw; } return expressions; } }}
I finally got around to installing Lookout. Wow! What an amazing search tool. I don't know how I ever got along without this killer Outlook plugin. Looks like it uses the open source Lucene.Net search engine too.
Wow!. I have the feeling we are going to see some really cool stuff now that these products are under one roof.
Virtual Server 2005 is in the release candidate development stage. Virtual Server allows you to run multiple x86-based operating systems concurrently on a single physical server.
VM technology serves a variety of purposes. It enables hardware consolidation, because multiple operating systems can run on one computer. Key applications for VM technology include cross-platform integration as well as the following:
Information on the 2.0 Framework Beta is everywhere. My RSS reader is going nuts with all the excitement. Take a look at Backwards Breaking Changes from version 1.1 to 2.0 as you start to migrate.
Update: An overview of the changes can be found here.
“Tech Previews“
NET 1.1 SP1 - A flavor for Win2K3 and another for other OSes.
I need to take a break more often...
~~~Mono includes a compiler for the C# language, an ECMA-compatible runtime engine (the Common Language Runtime, or CLR),and class libraries. The libraries include Microsoft .NET compatibility libraries (including ADO.NET and ASP.NET), Mono's own and third party class libraries. Mono's runtime can be embedded into applications for simplified packaging and shipping. In addition, the Mono project offers an IDE, debugger, and documentation browser.
If you have questions about the project, read the project launch statement or visit our list of Frequently Asked Questions.
For details on the project's future direction, read the roadmap, and download Mono 1.0.~~~
The way these guys move we'll have 2.0 features by the end of the year. Amazing.
|
http://weblogs.asp.net/markbrown/archive/2004/07.aspx
|
CC-MAIN-2013-48
|
refinedweb
| 552
| 61.63
|
Subject: Re: [boost] Boost and auto_ptr (was Boost 1.60.0 beta 1...)
From: Nevin Liber (nevin_at_[hidden])
Date: 2015-11-11 17:42:32
On 11 November 2015 at 15:08, Jonathan Wakely <jwakely.boost_at_[hidden]>
wrote:
> That doesn't mean implementors have to stop providing it, it only
> means it is no longer defined by the standard.
>
I'm not convinced they can.
Quoting [namespace.std]: "The behavior of a C++ program is undefined if
it adds declarations or definitions to namespace std or to a namespace
within namespace std unless otherwise specified."
And there is no wording in diff.cpp14.depr] which otherwise specifies it.
Or does this fall under it being UB, so vendors can define the behavior
however they like? (Seems kind of wrong because we have a UB detector [aka
constexpr] with defined semantics and are looking to define more of what
happens with UB [contracts], but I digress...)
--
|
https://lists.boost.org/Archives/boost/2015/11/226515.php
|
CC-MAIN-2022-05
|
refinedweb
| 155
| 65.73
|
Cont computations as question-answering boxes
From HaskellWiki
Current revision
1 Basic idea and definitions
The basic idea behind the Cont monad is that in place of values of type t, you work with functions of type (t -> r) -> r, where r is some "response" type. Breaking this down a bit, you can think of a function of type t -> r as a question about a value of type t which has a response of type r -- for a yes or no question, r might be Bool, for instance. Then a function of type (t -> r) -> r, is like a box which takes a question about a value of type t, and produces an answer from that question.
In Haskell syntax, we define a new datatype to wrap up this idea:
newtype Cont r t = Cont ((t -> r) -> r) -- a value of type Cont r t is of the form Cont f, -- where f is a function of type (t -> r) -> r
We'd also, for convenience, define a function:
runCont (Cont f) q = f q
Which, given a Cont computation and a question, basically asks the question to get a response.
The simplest way to make such a box is for the box to just hang on to a value of type t, and answer questions about it truthfully, by simply applying them to the value. (The fun will happen later, when we come up with more twisted ways to get answers.)
This is embodied in the continuation monad by the function:
return :: t -> Cont r t -- return takes a value of type t -- and produces a Cont computation of type t with response type r. return x = Cont (\q -> q x) -- produce a Cont computation which given a question q, -- applies the question to the value x.
(The notation (\x -> ...) is a Lambda abstraction.)
Now, given a computation of type (Cont r t), and a continuation which is a function taking a value of type t to some computation of type (Cont r s), we'd like to have a way to join them together, producing a computation of type (Cont r s). That's a bit brain twisting, so let's think about how we might do it...
We're constructing a box which is going to receive a question q about a value of type s, and has to answer it somehow.
We have a box, which we'll call x, which answers questions about a value of type t.
We also have a function, f, which given a value of type t, will give a box which answers a question about a value of type s.
So what do we do? We ask x the question "if f were applied to your value v of type t, how would the resulting box respond to the question q?"
The operation which does this funny gluing together is called
>>= (pronounced bind), and is implemented like this:
(>>=) :: Cont r t -> (t -> Cont r s) -> Cont r s x >>= f = Cont (\q -> runCont x (\v -> runCont (f v) q))
So we have what is effectively a fancy version of function application, which instead of working with straightforward values, works with these funky boxes that answer questions about values of the appropriate type.
2 Laws
There are three things which are true of the operations we've defined so far:
return v >>= fis the same as
f v
x >>= returnis the same as
x
(x >>= f) >>= gis the same as
x >>= (\v -> f v >>= g)
You might want to try to verify them as an exercise. These are the three monad laws, which makes
Cont r a monad for any given response type r.
3 Being sneaky: manipulating questions and responses
With only these operations, things are rather boring. The first and second rules above basically tell us that anything we can express just in terms of
>>= and
return, we can also express without.
However, by working with black boxes that answer questions about values of type t, rather than values of type t directly, the boxes we construct can take steps to manipulate the question or response.
Given any function f which turns a question about a value of type s into a question about a value of type t, we can turn a box x which answers questions about a value of type t into a box which answers questions about a value of type s. In code:
withCont :: ((s -> r) -> (t -> r)) -> Cont r t -> Cont r s withCont f x = Cont (runCont x . f)
That is, simply apply the function to the question first, and then ask x how it would answer.
Furthermore, given any function (r -> r), which transforms responses somehow, and any box x, we can easily construct a box which asks the box x how it would respond to a question, and then transforms the response.
mapCont :: (r -> r) -> Cont r t -> Cont r t mapCont f x = Cont (f . runCont x)
You certainly can't do either of these things with plain values! For example, let's consider the value
mapCont not (return 0) :: Cont Bool Integer. It is a box that gives the opposite response to any True/False question that one would get if one asked the same question about the number 0. For example, we might do something like:
ghci> runCont (mapCont not (return 0) >>= \t -> return (t < 0 && t > 0)) id True
The value 't' in the above is apparently a number which gives the appearance of simultaneously being both less than and greater than 0! Of course, what's really happening is that the test is turning out False and being negated after.
4 Being sneakier: Making the result depend directly on the question
There's an interesting insight to be had in thinking about the question that the computation
x is given in the application
x >>= f.
The question which x receives involves f, the computation which conceptually 'follows' after x is finished deciding on what value to supply to it. Can a carefully-constructed x somehow sneakily manage to recover the function f from that question, and use it in determining what value it will then supply to that question?
The answer is that effectively, yes, it can.
callCC :: ((t -> Cont r s) -> Cont r t) -> Cont r t callCC g = Cont (\q -> runCont (g (\v -> Cont (\_ -> q v))) q)
TODO: Finish the explanation of what this means in terms of the question/answer approach.
|
http://www.haskell.org/haskellwiki/index.php?title=Cont_computations_as_question-answering_boxes&diff=prev&oldid=21123
|
CC-MAIN-2013-20
|
refinedweb
| 1,081
| 59.87
|
- Hula Dancing: the 6 o'clock Show
This Sun ONE Secure Portal 6.0 recipe is similar to the recipe for the Secure Portal 3 called "OWA Luau with Rewriter Fire Dancing: the 3 o'clock Show" on page 22. This recipe explains the details that are particular to version 6.0.
Main Course: Internet ExplorerIngredients
Client
Internet Explorer 5.5SP2 + December 2002 Security update
Exchange
8 modifications to exchweb scripts and/or HTML component files
Portal Server
Sun ONE Portal Server 6.0 + 6.0SRAExchangeFixes
New Exchange-specific ruleset (owa_sp3_ruleset.xml)
Advantages
No client required for access.
Exposes native Exchange functionality to the web browser.
No client configuration required.
Encryption/Decryption done using SSL.
User interface is the same when accessed from within or outside the internal corporate network.
Takes advantage of new 6.0 architecture where the ruleset can be associated with a particular Gateway which may be used to access the Exchange server.
Disadvantages
Requires changes to Exchange server exposed scripts and component files in addition to configuration changes and fixes for the portal server software.
Integration is fragile in the sense that rules and modifications are very strict and inflexible or major functionality will fail or be inaccessible.
Exchange Feature Completeness
For a complete feature listing, refer to the section "Exchange Feature Completeness ~99%" on page 23 under the Sun ONE Portal Server 3 recipe. Feature completeness for the 6.0 rewriter integration is on par with that list, except for the additional known problems described below.
Know Problems With Exchange
Problem 1: Rich Text Editing in Email Composition Does Not Work
This feature operates from an ActiveX control which will not appear in the menu bar when the OWA interface is accessed through the Sun ONE Portal Server Gateway.
Workaround: In the ctrl_FormatBar20.htc file, add quotation marks to the following line. . .
<attach event=ondocumentready handler=onDocumentReady />
so it looks like the following:
<attach event="ondocumentready" handler="onDocumentReady" />
Problem 2: Submenu Does Not Display Correctly From Folder View
This submenu is opened by right mouse selecting over a folder name when in the folder view of OWA. The menu is not displayed correctly because a necessary event (ondocumentReady) never fires for the handler in ctrl_DropMenu20.htc to create the DHTML necessary for the menu contents.
Workaround: In the ctrl_DropMenu20.htc file, add quotation marks to the following line. . .
<attach event=ondocumentready handler=dOnReady />
so it looks like the following:
<attach event="ondocumentready" handler="dOnReady" />
What
Create a new rewriter ruleset for Exchange.
Install the Portal 6 patch containing Exchange-related fixes.
Make necessary modifications to Exchange controls files.
Enable Rewriting of CSS content.
NOTE
Any change made to the Outlook Web Access source .htc, .js, or .xsl files that exist in the Exchweb folder is unsupported by Microsoft.3 Any customization changes which affect these files that have already been made may affect or prevent a successful integration using this document. Future minor and major releases of Exchange from Microsoft may overwrite these changes, and make other modifications that break the integration through the rewriter. Upgrading to new releases of either product should be made in a controlled, responsible manner in a testing only environment.
How
To Create a New Rewriter Ruleset for Exchange
Log in to the Administration Console from a browser that has local access to the scripts and tools that you downloaded for these recipes.
Select View: Service Management.
Under the Portal Server Configuration section in the left view pane, select the link next to Rewriter.
In the right view pane, select New under the Rules section.
Change the Ruleset id attribute value to something easily identifiable like owa_sp3_ruleset.
Select save.
Select Upload link next to the new ruleset name.
As the local file, choose the owa_sp3_ruleset.xml file (one of the downloadable files for this article)
Select the Gateway link under the SRAP Configuration section of the left view pane.
Select the Edit link for the profile which will be used by the Gateway node accessing the Exchange server.
Under the Domain-Based Rulesets section in the right view pane, add the domain for the Exchange server if it is not there already, or modify the existing mapping to use the new ruleset.
Select Save.
Restart the gateway node(s) to reread the new profile information.
See "Obtaining the Scripts and Tools for this Article" on page 3.
... <RuleSet id="owa_sp3_ruleset"> ...
sub.domain.com|owa_sp3_ruleset
Sub and domain are the subdomain if one exists, and DNS domain of the Exchange server.
To Install Portal 6 Patch Containing Exchange-Related Fixes
For information on how to obtain Sun ONE Secure Portal patches, see "Obtaining the Required Patches" on page 5.
The patch you need for this recipe is called 6.0SRAExchangeFixes (patch ID 115156-01).
If you have added or changed files in the Portal web-apps directory, back it up in case the changes are overwritten or lost when the service is redeployed.
Uncompress and untar the patch contents.
Install the patch using the Solaris patchadd command, first on the profile and platform nodes, and then on the Gateway node.
# cp install_dir/SUNWps/web_apps \ install_dir/SUNWps/web_apps_pre6.0SRAExchangeFixes
# gunzip 6.0SRAExchangeFixes.tar.gz # tar -xvf 6.0SRAExchangeFixes.tar
# patchadd 115156-01 Checking installed patches... Executing prepatch script... Verifying sufficient filesystem capacity (dry run method)... Installing patch packages... Patch number 115156-01 has been successfully installed. See /var/sadm/patch/115156-01/log for details Executing postpatch script... Checking for previous patch revisions... Restarting SunONE Portal Server Gateway w/ original settings. stopping gateway ... done. starting gateway ... done. Gateway restarted. Please wait a moment before connecting to it. Postpatch processing complete. Patch packages installed: SUNWpsgw SUNWpsrw
To Make Necessary Modifications to Exchange Controls Files.
Follow the steps outlined in the 3.0 Rewriter recipe for making changes to these files using the modfiles.ksh script, or by editing the files directly. See "To Update the Exchange Files" on page 28.
To Enable Rewriting of CSS Content
Log in to the Portal Administration Console.
Select View: Service Management.
Select the link next to Gateway in the left view pane.
Select the Edit link next to the appropriate Gateway profile in the right view pane.
Under the MIME mappings sections, add CSS=text/html.
Select Save.
Restart the Gateway.
Why
Do I Need to Create a New Rewriter Ruleset?
By creating a separate ruleset specifically for Exchange-related integration, the ruleset can be maintained and modified independently of other default rulesets to prevent rule trumping and to extend the ability to create a particular Gateway node Exchange users will log in to in order to access OWA. The owa_sp3_ruleset.xml file is a migration of the rewriter rules required for the 3.0 rewriter recipe. For more information about what the rules are and why they are required, refer to the tables in the 3.0 recipe.
Do I Need to Install a Portal Patch For Exchange to Work?
The Exchange integration requires a combination of configuration changes (the rewriter ruleset), Exchange modifications (the control files), and fixes or enhancements in the Portal Server Gateway component. The Portal patch contains the following fixes:
BugID 4780863 Gateway strips off XML declaration tag.
BugID 4788050 Rewriter should ignore comments which occur prior to opening the XSL tag.
BugID 4778676 Gateway should not translate special characters (XML Entities) when rewriting XML.
Pages or response bodies that contain an XML namespace identifier which look like <?xml version="1.0" ?> end up having the root tag dropped. The direct effect on Exchange is not clear unless something depends on this root element being present.
If the opening XSL tag is preceded by anything else, the page will be rewritten. The correct fix for this particular problem needs to be carefully considered because there might be times when the XSL code has to be rewritten because it is used in a transform that will control URL values.
For example, when an email message is expanded, Exchange sends a DAV SEARCH request with the following message body:
<searchrequest xmlns="DAV:"> <sql>SELECT "" as prop1, " ft.com/exchange/smallicon" as prop2, "" as prop3, "urn:schemas:httpmail:hasattachment" as prop4,"" as prop5, " urn:schemas:httpmail:datereceived" as prop6, "" as prop7,"urn:schemas:httpmail:read" as read, " s" as messageclass, "DAV:href" as davhref FROM Scope('SHALLOW TRAVERSAL OF ""') WHERE " .microsoft.com/mapi/proptag/0x67aa000b" = false AND "DAV:isfolder" = false ORDER BY " icrosoft.com/mapi/sent_representing_name" ASC, "urn:schemas:httpmail:datereceived" DESC</sql> <range type="find" rows="1">WHERE " " >= CAST("System Administrator" AS "string")</range> </searchrequest>
There are no URL references which matter that are not being rewritten correctly, but the > character is being translated by the Gateway XML parser. By the time it gets to the Exchange backend, the XML is no longer syntactically correct for the request to be serviced and a multistatus response is sent with a 404 status in the response body.
BugID 4781754 Not rewriting the URLs in CSS Content. CSS is used in many places through the OWA code. This is a fix for added functionality done in Portal 3 that has not yet been ported to the portal server 6 software.
Do I Need to Make Modifications to Exchange Files?
For more information about the specific reasons these changes must be made for the integration to work, refer to the 3.0 Rewriter recipe.
Why Do I Need to Enable the Rewriting of CSS Content?
CSS content is used in various places throughout OWA. To keep the interface consistent with what a user would see accessing the Exchange server directly, it is necessary to enable the rewriting of CSS content.
|
http://www.informit.com/articles/article.aspx?p=100606&seqNum=9
|
CC-MAIN-2019-04
|
refinedweb
| 1,602
| 57.27
|
What would you do to improve the following?
func sign<T: SignedNumberType>(value: T) -> Int { return value == (0 as T) ? 0 : (value > 0 ? 1 : -1) }
or if you like it typed:
func sign<T: SignedNumberType>(value: T) -> T { return (value == (0 as T) ? 0 : (value > 0 ? 1 : -1)) as T }
Here’s what I call the Groffian Lapse In Judgement:
extension Bool: RawRepresentable { public typealias RawValue = Int public var rawValue: Int {return self ? 1 : 0} public init?(rawValue: Int) { self = rawValue == 1 } } func signbadTheSailor< T: protocol<SignedNumberType, IntegerLiteralConvertible> where T.IntegerLiteralType: SignedIntegerType > (value: T) -> T { let theSign = (value > 0).rawValue - (value < 0).rawValue let result: T.IntegerLiteralType = numericCast(theSign) return T(integerLiteral: result) }
Thanks.
5 Comments
I don’t know who this person is, but I would ask them, “Who hurt you?”
Why? Why would you do this? Nesting ternary operators…? C’mon
*begins weeping*
In all seriousness though, what does better mean? Space? Readability? Performance? …All I’ve figured is that you *definitely* need T (womp womp womp)
Okay. Taking this seriously …
Minimum: linebreak before each colon.
—
Use an if … else if … return. Any compiler since, oh, 1980 will generate the same code. Any programmer since 1880 (before which nobody was born who could have taken up a programming language that could express either) would understand it at a glance as she would not a chained ternary.
—
Consider that 1.0 + 3.0*2.7 – 9.1 almost never == 0.0. Create a generic (wiggly equal sign, opt-x on an en_US Mac keyboard — sorry, I’m on my iPad) operator which uses ==, but specialized for FloatingPointType by testing for proportional difference (lt) epsilon.
(Avoiding trouble with XML tag delimiters.)
I use an actual epsilon character because I’m fancy.
Remember to make epsilon larger for Float than you’d prefer for Double. And avoid putting zero in the denominator, probably using a guard to test the nonzero operand for small-enough. Oh, and by the way, CGFloat is Float in 32-bit architecture, Double in 64. And CGRect, and …
Contemplate that operands could be equal-enough while also (lt) or (gt). It doesn’t carry the postulate you probably assume that (gt), (eq), and (lt) partition the set of numbers. Test for equal-enough first.
|
https://ericasadun.com/2016/03/21/sign-of-the-times/
|
CC-MAIN-2021-31
|
refinedweb
| 377
| 60.51
|
Cracking a Captcha . Nullcon| EMC2 CTF 2015
by, 01-15-2015 at 05:01 PM (0 Views).
Any way on Sunday night I got bit bored with drones and decided to take a sneak peak at the CTF, but by that time the winners were declared and score board was closed. I went straight to my favorite web and reversing challenges and decide to solve one of those. Web 5 was a captcha sovler for 500 point ands I decided that would be easy.
The challenge was to break maximum number of captcha and submit using a given session token in a time frame of 2 minutes.
Analyzing the captcha we easily understand that , there are 5 easily visible colours.
Black == background
dark violet == dots
Gray == lines
Letters == In some form of light violet colors.
Form the look of it, it was an easily crack-able captcha .
This is small AI problem where we need to create a program that could recognize these captchas. We need to teach our AI program what is right and what is
wrong. So the first step is to build a training data set, that goes as an input for our captcha solver . For creating the training data people choose
different methods, they depend on neural networks, Vector Space Search etc. In our current situation we do not have a complicated data set. The captcha is simple and has only [a-z,A-Z ] characters in it.
Building the Training Data set.
Step 1 :
The captcha image we are provided was a PNG file, which is in RGBA mode [Red Green Blue Alpha] . ref: en.wikipedia.org/wiki/RGBA_color_space. We will have to bring it down to a maxium of 255 colour space. And the best way to do that is to
convert the image to gif form png. We will use python PHL module to do that.
"
captcha_image = captcha_image.convert("P")
"
Next step is the find the image pixel concentration . Plot the colour and the respective pixel count.
We can use phil histogram and plot . And we get the following.
[-] Image pixel concentration
0 8344
190 938
53 301
96 184
204 113
205 69
60 24
210 14
211 7
95 4
Here 0 stands for Black and has the most pixel count 8344 followed by color 190. At this point I assumed color 204 and 205 are those that that are used for captcha letters.
Step 2:
Remove the noises from the image. This is easy to do as we can simply remove those pixels that are not used for captcha letters.
Simply plot those captcha letter colors to a new image and remove everything else.
if pix == 204 or pix == 205: # these are the numbers to get
captcha_filtered.putpixel((y,x),0)
Now we would get an image whose background is white with all noises removed.
Step 3:
Next step is to find the captcha letter spacing, and slice each characters out of the captcha .
This would be easy as we have only three different colours in our new image. 255,204,205 .
Horizontal position where letter start and stop .
|a|s|d|f|e
image 1 Line Spacing is [(5, 13), (35, 43), (65, 73), (95, 102), (125, 133), (155, 163)]
Image 2 Line Spacing is [(5, 13), (35, 43), (66, 73), (96, 102), (125, 133), (155, 163)]
Each letters in the captcha occupied almost the same space .
Cut each characters and place them inside a folder.
Rename each letter images[file name] to there respective letter .
Now we will have a folder with sliced letter named with there respective letter.
Final Solution algorithm:
The final algorithm to solve the captcha would be.
a) read a new captcha , session cookie
b) filter noise out
c) Slice filtered captcha and extract each letter
d) compare it with those letters kept in the letter folder and find the best match,
c) best match would be the captcha letter
d) continue for all letters in captcha
e) Submit the full captcha along with session cookie to application
f) fetch new captcha with session cookie, goto step b
Compare two images in Python:
There are multiple ways to compare an image in python .
1) Calculate the root mean square
ref:
2) Euclidean distance
3) Normalized cross-correlation
We will choose the normalized cross relation.
PHIL module's difference returns the absolute value of the difference between the two images.
ImageChops.difference(image1, image2) ⇒ image
out = abs(image1 - image2)
Our images are in the same shape and size. So this is the best bet.
My program had 97% success rate and after 50 successful entries I got the flag.My program had 97% success rate and after 50 successful entries I got the flag.PHP Code:
from PIL import Image,ImageChops
from operator import itemgetter
import urllib2,hashlib,time,urllib
import cStringIO,glob
#we have kept all our letters in this folder
files_names = glob.glob("/root/ctf/let/*.*")
#we need to get the captcha at the same time get the session cookie, and use it for all solved captcha request.
response = urllib2.urlopen('')
cookie = response.headers['Set-Cookie']
#print cookie
#lets make 500 request read teach captcha
for x in range(1,500):
captcha =""
opener = urllib2.build_opener()
opener.addheaders =[
('Accept', 'application/json, text/javascript, */*; q=0.01'),
('Referer', ''),
('Cookie' ,cookie),]
response = opener.open('')
length = response.headers['content-length']
# read the captch and we will save them with there content length */
print "[-] Image Content length " , length
image_read = response.read()
#cStringIO to create an object from memmory
#image_read = Image.open("/root/ctf/u.png")
image_read = cStringIO.StringIO(image_read)
captcha_image = Image.open(image_read)
#im = Image.open("/root/ctf/de")
captcha_image = captcha_image.convert("P")
temp = {}
captcha_filtered = Image.new("P",captcha_image.size,255)
#print im.histogram()
his = captcha_image.histogram()
values = {}
for i in range(256):
values[i] = his[i]
print "[-] Image pixel concentration \n"
for color,concentrate in sorted(values.items(), key=itemgetter(1), reverse=True)[:10]:
print color,concentrate
for x in range(captcha_image.size[1]):
for y in range(captcha_image.size[0]):
pix = captcha_image.getpixel((y,x))
temp[pix] = pix
if pix == 204 or pix == 205: # these are the numbers to get
captcha_filtered.putpixel((y,x),0)
captcha_filtered.save("/root/ctf/images/"+length+".gif")
inletter = False
foundletter=False
start = 0
end = 0
letters = []
for y in range(captcha_filtered.size[0]): # slice across
for x in range(captcha_filtered.size[1]): # slice down
pix = captcha_filtered.getpixel((y,x))
if pix != 255:
inletter = True
if foundletter == False and inletter == True:
foundletter = True
start = y
if foundletter == True and inletter == False:
foundletter = False
end = y
letters.append((start,end))
inletter=False
print "[-] Horizontal Position Where letter start and stop \n"
print letters
print "\n"
count = 0
for letter in letters:
m = hashlib.md5()
im3 = captcha_filtered.crop(( letter[0] , 0, letter[1],captcha_filtered.size[1] ))
#Match current letter with sample data
#im3.save("/root/ctf/let/%s.gif"%(m.hexdigest()),quality=95)
count += 1
base = im3.convert('L')
#print files_names
class Fit:
letter = None
difference = 0
best = Fit()
for letter in files_names:
#print letter
current = Fit()
current.letter = letter
sample_path = letter
#print sample_path
sample = Image.open(sample_path).convert('L').resize(base.size)
difference = ImageChops.difference(base, sample)
for x in range(difference.size[0]):
for y in range(difference.size[1]):
current.difference += difference.getpixel((x, y))
if not best.letter or best.difference > current.difference:
best = current
#final captcha decoded
tmp = best.letter[14:15]
captcha = captcha+tmp
#let us post the captcha to the server along with the session token
print "[+] Captcha is ", captcha
url = ''
data = urllib.urlencode({'solution' : captcha.strip(), 'Submit' : 'Submit'})
req = opener.open(url, data)
response = req.read()
print response
GitHub Code:
Ref:
vBulletin Message
Trackbacks
Total Trackbacks 0
Trackback URL:
|
http://garage4hackers.com/entry.php?b=3103&s=5e635f1eca02b10693432bcfaac672f5
|
CC-MAIN-2020-50
|
refinedweb
| 1,283
| 67.35
|
MDI child forms are an essential element of Multiple-Document Interface (MDI) Applications, as these forms are the center of user interaction.
In the following procedure, you will create MDI child form that displays.
Note
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Customizing Development Settings in Visual Studio.
To create MDI child forms
Create a new Windows Forms project. In the Properties Windows for the form, set its IsMdiContainer property to
true, and its
WindowsStateproperty to
Maximized.
This designates the form as an MDI container for child windows.
From the
Toolbox, drag a MenuStrip control to the form. Set its
Textproperty to File.
Click the ellipses (…) next to the Items property, and click Add to add two child tool strip menu items. Set the
Textproperty for these items to New and.
Note
The MDI child form you created in this step is a standard Windows Form. As such, it has an Opacity property, which enables you to control the transparency of the form. However, the Opacity property was designed for top-level windows. Do not use it with MDI child forms, as painting problems can occur.
This form will be the template for your MDI child forms.
The Windows Forms Designer opens, displaying Form2.
From the Toolbox, drag a RichTextBox control to the form.
In the Properties window, set the
Anchorproperty to Top, Left and the
Dockproperty to Fill.
This causes the RichTextBox control to completely fill the area of the MDI child form, even when the form is resized.
Double click the New menu item to create a Click event handler for it.
Insert code similar to the following to create a new MDI child form when the user clicks the New menu item.
Note
In the following example, the event handler handles the Click event for
MenuItem2. Be aware that, depending on the specifics of your application architecture, your New menu item may not be
MenuItem2.
Protected Sub MDIChildNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click Dim NewMDIChild As New Form2() 'Set the Parent Form of the Child window. NewMDIChild.MdiParent = Me 'Display the new form. NewMDIChild.Show() End Sub
protected void MDIChildNew_Click(object sender, System.EventArgs e){ Form2 newMDIChild = new Form2(); // Set the Parent Form of the Child window. newMDIChild.MdiParent = this; // Display the new form. newMDIChild.Show(); }
private: void menuItem2_Click(System::Object ^ sender, System::EventArgs ^ e) { Form2^ newMDIChild = gcnew Form2(); // Set the Parent Form of the Child window. newMDIChild->MdiParent = this; // Display the new form. newMDIChild->Show(); }
In Visual C++, add the following
#includedirective at the top of Form1.h:
#include "Form2.h"
In the drop-down list at the top of the Properties window, select the menu strip that corresponds to the File menu strip and set the MdiWindowListItem property to the Window ToolStripMenuItem.
This will enable the Window menu to maintain a list of open MDI child windows with a check mark next to the active child window.
Press F5 to run the application. By selecting New from the File menu, you can create new MDI child forms, which are kept track of in the Window menu item.
Note
When an MDI child form has a MainMenu component (with, usually, a menu structure of menu items) and it is opened within an MDI parent form that has a MainMenu component (with, usually, a menu structure of menu items), the menu items will merge automatically if you have set the MergeType property (and optionally, the MergeOrder property). Set the MergeType property of both MainMenu components and all of the menu items of the child form to MergeItems. Additionally, set the MergeOrder property so that the menu items from both menus appear in the desired order. Moreover, keep in mind that when you close an MDI parent form, each of the MDI child forms raises a Closing event before the Closing event for the MDI parent is raised. Canceling an MDI child's Closing event will not prevent the MDI parent's Closing event from being raised; however, the CancelEventArgs argument for the MDI parent's Closing event will now be set to
true. You can force the MDI parent and all MDI child forms to close by setting the CancelEventArgs argument to
false.
See Also
Multiple-Document Interface (MDI) Applications
How to: Create MDI Parent Forms
How to: Determine the Active MDI Child
How to: Send Data to the Active MDI Child
How to: Arrange MDI Child Forms
|
https://docs.microsoft.com/en-us/dotnet/framework/winforms/advanced/how-to-create-mdi-child-forms
|
CC-MAIN-2017-39
|
refinedweb
| 771
| 64.1
|
How to use DropBox with Raspberry Pi
>>IMAGE get one – it’s free.
2. Download and Set Up DropBox Uploader
Next, you need to get Dropbox Uploader onto your Pi
cd ~ this ensures you are in /home/pi
git clone
ls
(If this fails, you may need to install git with
sudo apt-get install git-core)
You should be able to see a directory called Dropbox-Uploader
cd Dropbox-Uploader
ls
You should now see three files, one of which is called dropbox_uploader.sh. This is the script we’re going to use.
3. Now the fiddly bit – API keys
Run the script with
./dropbox_uploader.sh (if it fails, try
chmod +x dropbox_uploader.sh)
You should see this…
You then need to visit this link, login to DropBox and create an “app” by clicking the “create app” button.
Then choose “Dropbox API app”, “Files and Datastores”, and answer the final question “Can your app be limited to its own, private folder?” – either answer is OK, depending on your needs.
Then you need to give your app a unique name, and you will be assigned some keys to go with the name. Now you need to type in those keys here…
Once you’ve entered your keys and answered the question “app” or “full”, your Pi will request an authorisation token and you will be given a web URL you need to visit to activate it…
This is the part which annoyed me, as I was using a different computer to ssh into the Pi and couldn’t cut and paste the “rather tricky to type accurately” URL. But once you’ve got past that hurdle it should all just work. :)
If it works, you should see this in your browser…
4. Now you can use DropBox Uploader on your Raspberry Pi…
…from the command line like this…
cd home/pi/Dropbox-Uploader
./dropbox_uploader.sh upload /home/pi/name_of_upload_file name_of_upload_file
This will upload the file you choose to your DropBox account.
…or use it in a Python script like this…
from subprocess import call photofile = "/home/pi/Dropbox-Uploader/dropbox_uploader.sh upload /home/pi/photo00001.jpg photo00001.jpg" call ([photofile], shell=True)
And, if you look at the DropBox Uploader documentation, there’s a lot more commands you can make use of…
- upload
- download
- delete
- move
- list
- mkdir
I think this is brilliant. Yes you have to jump through a couple of hoops, but to be able to take a photo and see it on my PC, phone or Nexus 7 tablet within 30 seconds is pretty darned cool. I’ll jump through a couple of hoops for something that cool.
Here’s what it looks like in action, taking a photo and uploading to DropBox automatically. The DropBox upload photo part starts at 5m 7s.
Update April 2015 – progress bar gone :(
There is no longer a progress bar by default when you are uploading. This is a real shame. I installed dropbox uploader on a new setup and for ages I thought that it wasn’t working, when in fact it was just uploading a 30 Mb file and was taking about 10 minutes to do it on a slow connection.
I don’t know where the progress bar has gone, but it is sorely missed. I redid the “linking with dropbox” process 3 times, thinking it wasn’t working, before I thought to try a smaller file and found that it was working OK. Patience, and monitoring “top” for the curl command threw some light on things.
I’ve now found out you can put the progress bar back in if you edit the file…
nano /home/pi/Dropbox-Uploader/dropbox_uploader.sh
…and change
SHOW_PROGRESSBAR=0 to
SHOW_PROGRESSBAR=1
#Default values
TMP_DIR="/tmp"
DEBUG=0
QUIET=0
SHOW_PROGRESSBAR=1
SKIP_EXISTING_FILES=0
ERROR_STATUS=0
YAY! :)
Now _that_ is a handy piece of software :-)
It’s brilliant isn’t it? What I love about it is that it’s basically a bash script using curl, so nothing much to install. You can call it from a Python script, and once you’ve done the initial setup it “just works”. :)
You forgot to mention an easy way to manage/navigate dropbox with nice addon dropShell
LOL. I didn’t forget anything, I didn’t even know about it :p
But I will delve into that further when I get the chance – it sounds interesting. Thanks for the tip. :)
Hi Alex
I got through the procedure, and got the message –
Success! KCuploader2 is connected to your Dropbox.
However, when I tried to upload a file called colours.jpg, it failed:
pi@raspberrypi ~/Dropbox-Uploader $ ./dropbox_uploader.sh upload /home/pi/colours.jpg
> Uploading “/home/pi/colours.jpg” to “/colours.jpg”… FAILED
An error occurred requesting /upload
pi@raspberrypi ~/Dropbox-Uploader $
Can you see what I’m doing wrong?
Cheers
Kieran
Not unless it’s something silly like colours.jpg being in a directory other than /home/pi or internet connectivity?
Try a different command? e.g. list.
I haven’t played with this at all, but it would tell you if there was a general connectivity issue or a problem with the file you tried to upload.
hall
Same problem. Did you resolve it?
Steve says: I am a mech eng and noooo expert but I just managed to load up dropbox and add files. Some points are: 1) Case sensitive; 2) I don’t think it will like the “/”. I used the command $ ./dropbox_uploader.sh /home/pi/Photos/IMG0052.JPG IMG_0052.JPG to test the ADAFRUIT PiCam BUT 3) I had to make a directory in Dropbox for Photos first. This is why I don’t think it likes the “/”. Cheers Steve
Same problem here, too. Will try again with it at some point, though, as this could be really useful.
Am wondering if I listed the wrong access level when setting up the Pi. If anyone can tell me how to change this retrospectively, either via Dropbox or via the Pi, then I’m all ears.
Go to the app URL above, delete your app and try again, would be my suggestion.
Did you guys give dropboax uploader access to your whole dropbox or just a specific directory? I gave it access to the whole lot. Just wondering if it makes a difference?
Worked perfectly second time around. Looks like I did list the wrong access level when setting up the Pi. I had to delete the Dropbox app, and unlink the Pi (./dropbox_uploader.sh unlink) before I could redo the Pi setup. Thanks for a really useful tutorial.
So which access level was the wrong one? And which was the right one? I’ve never tried anything other than full access.
I think first time around I told Dropbox to give the app access to the app folder only, and then mistakenly told Dropbox Uploader that it had full access. I’ve now got it working with full access, but I’ve no reason to think that folder access wouldn’t work.
Excellent – thanks :)
This looks great to use just done the Dropbox app and installed the keys
can you advise as I have never had the pi on the web direct what browser would you recommend. I do not use any desktop programs with it.
Terry
I did the web browser bit with my laptop (hence the comment about having to retype the tricky URL). But you can use Midori as a browser if you’re patient. (It’s not the Pi’s strength – frankly it’s too darned slow for me, but web browsing is not what it’s for IMHO – I have plenty of other devices that do that well.)
Thanks for quick reply despite being a very old noob well I cut my teeth on Nascom and ZX81. I had saved the web link but it has timed out so start again tomorrow.
It is easy to copy paste from PI using Putty to a Vistal Laptop.
It took me a time to find just highlight the pi text with left mouse click and hold drag to end of the text. Do nothing more in Putty
Open the text edit program and do a ctrl v and the pi text is pasted to your program or browser address bar
Terry
Hi Terry,
Join the club….ZX81 was my first intro to programming…1kb or a 16kb wobbly RAM pack! Is it me or was Z80 machine code a damn site easier than Linux???
Anyway, just to add to your comments about copy/paste….
Alex, as I assume you are copying the other way (ie copy from PC and paste to RPi) you select the text from your browser (or wherever) and CTRL C as usual then use PUTTY and just right-click. The text is pasted straight away. The other way, highlighting PUTTY text automatically copies it to the clipboard.
Dave
Hi Alex,
Brilliant!!
Your instructions are great! Unlike most things I’ve tried to do with the Pi, I went from reading your post to uploading a file to dropbox in about 5 minutes!!!
Thanks again……now we just need a GUI method! ;-)
Dave
Thank you Dave. That would be mission accomplished then. Clear, precise instructions that work first time is what I strive for. I don’t do GUI on pi (yet).
All worked first time today thanks a lot for you time and effort.
PI to DropBox to Laptop takes 11 seconds .
Result :)
Cool. Works. Give it a try :) Thank You
I tried it and it works perfectly. Thanks.
I just have one question. By any chance, does anybody know a simple way to get (and use) the information given by the instruction “list” inside my python script ?
I would like for exemple that my python script compare the content of a dropbox (remote) folder with a local folder. I have tried to google this issue but I did not find anything I could really use.
I have to confess that I am still a newbie with both python and RPI (but oh boy, I have so much fun ;) )
Thanks, great article
I have been using Dropbox with my Rpi from the beginning, but via my linux workstation and the “sshfs” command.
On the Rpi, I use “sshfs :Dropbox Dropbox”
Then I use the Rpi Dropbox directory as normal.
Works like a champ.
How do you do this. Could you please link a more detailed explanation.
Thanks in advance.
Oh, oh!
git clone
returned:
Cloning into ‘Dropbox-Uploader’…
error: The requested URL returned error: 503 while accessing https:/github.com/
andreafabrizi/Dropbox-Uploader.git/info/refs
fatal: HTTP request failed
pi@raspberrypi ~ $
Problems in Andea’s directory?
Help please.
I got it working! Going to Andrea’s site took me through it. The above git clone command evidently didn’t like the …-Uploader.git at the end, wanted …-Uploader/ (no .git)
Here is the link to her site: – good luck everybody – cool stuff!
I seem to have linked it to the wrong a/f. Unlink didn’t seem to work for me. What’s the easiest way to uninstall the Dropbox-Uploader and start a fresh?
Thank you, and very helpful. I had this working on another SD and it works seamlessly!
It’s just a bash script, so not really “installed” as such. I don’t know quite what it does with the keys and token though. The only foolproof way would be to flash a fresh SD card, but it’s probably really only a question of finding and deleting a couple of files.
Okay, no worries. I think it’ll be as quick to do a fresh SD ;)
All working. It was down to me using ‘f’ instead of ‘a’. Fresh SD did the job. I’m sure theres a quicker way, but for me it was quicker to just do a fresh install. This is part of an art exhibition in london at some point in spring next year. I’ll send some pics over to see your script on a big scale ;)
Great work.
Excellent – sounds great :)
Could I ask where the default configuration file is? I don’t see one in the location stored in the code – I have the default installation.
Thanks for a great product,
TIm
I think you’d be best off contacting the author through his GitHub account :)
If I understand correctly what you’re looking for the file is .dropbox_uploader (with a dot at the front) in your home directory.
Type ls -al for a listing including any config files.
It contains details of your APPKEY, APPSECRET, ACCESS_LEVEL, OAUTH_ACCESS_TOKEN and OAUTH_ACCESS_TOKEN_SECRET.
Thanks Neil – I eventually emailed the author and he kindly put me on the right track. I use DU with a couple of piCams to look at the view from my windows when traveling – very nice. It’s also good for tracking your home IP remotely without use a DDNS – very handy.
Hi, Thanks for the tutorial the upload to dropbox works only manually “./dropbox_uploader.sh upload /home/pi/ocr_pi.png”
but if i run it with the attached Python script it shows some error on line 4
Please help ..
Thanks.
Nick.
Hi, great tutorial.
is there a script that takes the last created file and uploads it to Dropbox?
not sure if i have missed something as your video does it but i can’t see any code to do this.
this is what i have so far: –
from subprocess import call
import os
import glob
newest = max(glob.iglob(‘*.jpg’), key=os.path.getctime)
photofile = “/home/pi/Dropbox-Uploader/dropbox_uploader.sh upload /home/pi/ newest”
call ([photofile], shell=True)
so as you can see i have just replaced the file name with the ‘newest’ object but it just sees it as a file name.
Thanks,
i think i have it, i can up load a folder and use the -s optional parameter to skip existing files. much simpler.
Thanks,
Doesn’t really matter now, but to fix your original script you’d simply need to change it to:
photofile = “/home/pi/Dropbox-Uploader/dropbox_uploader.sh upload /home/pi/" + newest
Thanks, that works much better.
To upload any file from command line try:
write python app:
from subprocess import call
import sys
TheCall = “/home/pi/Dropbox-Uploader/dropbox_uploader.sh upload ” + sys.argv[1] + ” /DropboxDestination”
call ([TheCall], shell=True)
The, from the command line do something like: python dropbox.py /home/pi/test.txt
I can’t get the Uploader to work. I got through the tutorial OK, but could not see the .jpg on the Dropbox. I used:
./dropbox_uploader.sh upload /home/pi/name_of_upload_file with my .jpg file name. All I get is Uploader help file.
I decided to re-install the Dropbox-Uploader again, removing the old directory. I can do the git command to download the file OK. But, now I can’t run even run this script:
./dropbox_uploader.sh I just get the help file again.
I found the trouble. If I use the Andrea script without the .git at the end, replaced by a forward slash, it works.
Uploader wont work. Reinstalled Dropbox-uploader and getting help file. removed .git from:
git clone
to get: git clone and it still goes into help menu
Any ideas?
I’ve just had a look at this myself – looks like the syntax of the script has changed slightly (maybe Alex could add a note to the article above) and the ‘upload’ option now requires a destination filename in Dropbox. I.e. instead of:
./dropbox_uploader.sh upload /home/pi/myfile.jpg
you now need to do:
./dropbox_uploader.sh upload /home/pi/myfile.jpg myfile.jpg
Thanks for that. Will make changes in the text. I’m still using the old version on my RasPiCamcorder.
I following the steps as above, but when I run Run the script with ./dropbox_uploader.sh (if it fails, try chmod +x dropbox_uploader.sh) for the first time, I do not get the option of adding my app, I just get the help menu.
Why is that?
Dave
Maybe dropbox_uploader.sh is already linked to your account? Try
rm ~/.dropbox_uploader
and then try again?
I tried the code a couple different ways (please forgive me if I have reposted this) I have a couple questions. one: are you suppose to have a app folder inside the dropbox folder and suppose to direct the files to go into that folder? I change the destination folder to three subfolders in the same folder that the .sh is in. (i.g. /home/pi/subfolder1/subfolder2/subfolder3/tada.jpg) but when I run the code it “no such directory or file found /home/pi/……. I have a couple prematations of the order of the directories and beginning slashes and no slashes…so far it all ends with depression and failure.
Have you done ‘mkdir -p /home/pi/subfolder1/subfolder2/subfolder3’ ? Linux doesn’t auto-create “missing” folders for you.
(If it’s not that, I don’t have any other suggestions as I don’t use this Dropbox script)
I figured it out what was happening. I had misspelled the the first folder so it was giving me an error. If anyone can tell me how to: make this run on boot and repeat it and run a script that cleans the folders. I have the clean script and I know how to get this one to run. I just need something to the them together and make it run constantly.
Make it run at boot: edit rc.local
Make it repeat: edit crontab
Searching google (or the Raspberry Pi forums) will give you *lots* more info about either of them :)
…and/or have a look at
Yup, that worked, thank you.
Hi all. Brilliant solution. Thanks for the excellent guides, Alex.
I’ve a but I can’t crack. Dropbox-uploader works great when I call it from command line, but when I try to do so within a script, I am prompted to enter the app key as if I’ve not linked the app. For some reason if I initiate the shell script while not in the Dropbox-Uploader folder, I get the same result: requesting the app key. Even tried an os.chdir in the script to get around this, thusly:
#!/usr/bin/env python
#picamera_test.py
import time
import picamera
from subprocess import call
import os
import glob
newest = max(glob.iglob(‘*.jpg’), key=os.path.getctime)
camera = picamera.PiCamera()
try:
camera.start_preview()
time.sleep(2)
camera.capture(‘test.jpg’)
camera.stop_preview()
os.chdir(“/home/pi/Dropbox-Uploader”)
photofile = “./dropbox_uploader.sh upload /home/pi/” + newest + “Code/Pi” #tried with and without specifying filename to place
call([photofile], shell=True)
finally:
camera.close()
Any help is greatly appreciated.
Was using sudo to run the script. Apparently I linked to app as pi and not root. Seeming fine now.
OK cool. Glad you got it sorted :)
Lesson learned for edification of all: link the dropbox app to both pi AND root. That way, it always works. Great site and projects!
…and the easiest way to do that is to simply link to the dropbox app as the pi user (as Alex explains above) and then do a:
sudo cp /home/pi/.dropbox_uploader /root/
(copies the settings file from pi’s home directory to root’s home directory)
:-)
[…] Installing Dropbox on a Raspberry Pi […]
I have a problem with the starting upload a file at boot. Could anyone help me?
Sorry for spam but, i found resolve for my problem i have just to “sudo cp /home/pi/.dropbox_uploader /root/”
I don’t think it’s spam. You’re completely on topic :)
Hy Mr, i have problem
while i write scrip… git clone
but show // error: server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none while accessing
fatal: HTTP request failed
i hope help you,,, thank you
hello, thx for a good tutorial
but is there a way to download whole dropbox at once win this script?
nevermind. i simply the name of folder blank(‘/’) and it started downloading
Note that if you have a *lot* of files in your Dropbox folder you may hit the rate limit on the number of API requests you can make per day
(the dropbox API is designed to be used for as-needed file access, rather than bulk-downloading file access)
Yeah, I’ve got a lot. Thx for a hint.
Thanks for the tutorial,
I have one small problem, every time a photo uploads to dropbox it overwrites the last photo that was sent. Any ideas on how to fix this?
Thanks
Are you using the same file name for each photo? If you use a unique name for each shot, surely that won’t happen?
That is probably the problem, How can I change that? I am really new to working with the RasPi.
Without saying how you’re taking the photo, I can’t really help. If you’re using raspistill, the bit after the ‘-o’ defines the file name
e.g. raspistill -t 500 -o /home/pi/photo.jpg
photo.jpg should be different for each photo
I am using the adafruit Pi cam python program after adding their 2.8 PiTFT touchscreen.
OK. Well there must be a way to specify the filename somewhere in that. I’ve never tried it. :)
The pictures appear to get a unique file name when saved in the Pi folder (consecutive numbering) but after the uploader moves the file to dropbox the file name is changed to Photo. makes me think something needs to be modified in the uploader..
Thanks, Alex, to your excellent tutorial, my Raspi located very far away is sending me every night on my dropbox the pics of the day. It has been working for 6 months now….GREAT.
But the internet connection at the place where the raspi is, is not reliable and the signal drop down from time to time…I am thinking to add to your python script:
01.from subprocess import call
02.photofile = “/home/pi/Dropbox-Uploader/dropbox_uploader.sh upload /home/pi/photo00001.jpg photo00001.jpg”
03.call ([photofile], shell=True)
some sort of loop or while true
but I don’t know really the exact syntax to apply
Have you an idea ?
Michel
i would like to use this to up date files at multiple sites updates would be as needed upload for home and download to sites maybe once a week. Would be willing to listen to any advice please and thank you.
Photos are in Photos Folder.
/home/pi/Photos
I am trying to get this to work. I have gotten it Connected (I think) but there is no app folder that pops up. Shouldn’t there be like a folder in Dropbox if things done right. I changed the syntax so I don’t get the menu but I getting a “no such file or directory exist” error. But it does… Help.
I got the token error when upload my appkey & appsec.
it told no such folder or dictionary .
anyone who can help me with it、
Thanks in advance!
Umm, what? You don’t need to ‘upload’ your appkey and secret.
Try following the instructions again, but more carefully?
im trying to upload a photo(that captured with pressing a buttun on raspberry input)to dropbox.can i use this app to my project?
Yes, with modifications. :)
|
http://raspi.tv/2013/how-to-use-dropbox-with-raspberry-pi
|
CC-MAIN-2018-51
|
refinedweb
| 3,914
| 74.49
|
About |
Projects |
Docs |
Forums |
Lists |
Bugs |
Get Gentoo! |
Support |
Planet |
Wiki
On Aug 29, 2005, at 10:26 PM, Brian Harring wrote:
>
> On Tue, Aug 30, 2005 at 01:09:49PM +1000, Finn Thain wrote:
>>>
>>> I was looking at it more as a place to develop some new portage
>>> features...Gentoo/Darwin has always been lurking, this is more in
>>> the
>>> area of just getting offsets working.
>> Excepting that, if you can leverage
>> existing packages, prefixed installs are much more useful -- having a
>> complete set of deps installed on a prefix is not much better than a
>> stage3 chroot with your home directory bind mounted below it.
Maybe so, but we can't have one without the other. First get packages
to install in a prefix, then work up from there. The issue of
leveraging existing packages is currently handled by
package.provided, which we all know doesn't really serve our
purposes, but I see no reason work couldn't be done in parallel on
these issues...if you have an ebuild repo talking to and
understanding a vendor repo such as apples Receipts or whatever, that
will work wether the packages get installed in a prefix or not,
likewise if we have packages that can be installed to an alt-prefix,
they should work regardless of how portage is resolving the deps.
> The rewrite's general core is intended to allow for alt
> formats/repos/whatever jammed into it; that said, making seperate
> formats play nice with each other (unless they can natively) isn't
> something I think is incredibly easy to pull off, as mentioned above.
Right, this would be a great feature, but I look at this as multi-
level deps, which should come later IMHO. My goal for having a branch
of some base packages is to hash out the namespace and all the other
issues of portage managing a flat set of deps under an offset root.
Once that is functional, making the offset repo talk to another repo,
regardless of vendor, host, location, etc could be looked at.
I know that its good to get a solid design before running off and
writing a bunch of code, but it seems to me the portage rewrite has
been thought out sufficiently to allow for this type of feature
expansion in the future, without limiting what we can do right now.
--Kito
--
gentoo-osx@g.o mailing list
Updated Jun 17, 2009
Summary:
Archive of the gentoo-osx mailing list.
Donate to support our development efforts.
Your browser does not support iframes.
|
http://archives.gentoo.org/gentoo-osx/msg_8891a53c370e666dd673640cc82dae52.xml
|
CC-MAIN-2014-42
|
refinedweb
| 427
| 64.04
|
I'm new to react, I'm curious how to do this properly.
suppose I have this form, by clicking button, I want to get textbox value,
var form = React.createClass({
submit : function(e){
//how to get textbox value?
},
render : function(){
return (
<form>
<input type="text" id="textbox" value="hey, get me"/>
<button onClick={this.submit}>Get it</button>
</form>
);
}
});
One way to accomplish this is using refs.
After building your component, you may find yourself wanting to "reach out" and invoke methods on component instances returned from render(). link to refs docs
Refs are basically the html elements / react instances you want to access. In this case, we want to get Input html element. We get input element by this.refs.inputValue. Then read its value by usual js rule.
var form = React.createClass({ submit : function(e){ e.preventDefault(); console.log(this.inputValue.value); }, render : function(){ return ( <form onSubmit={this.submit}> <input type="text" id="textbox" defaultValue="hey, get me" ref={ function(node){ this.inputValue = node }.bind(this) } /> <button onClick={this.submit}>Get it</button> </form> ); } });
here is a jsfiddle for your example, you can check the console for the input value.
Another way to accomplish the same thing is to make your input a controlled element. That means you assign input's value attribute to this.state.inputValue and you pass a onChange event handler as onChange={yourInputHandlerFunction}.
See the answer which explains this way of accomplishing the same thing.
|
https://codedump.io/share/0K7HYRgOcJsb/1/react-js--get-siblings-or-parent-value
|
CC-MAIN-2018-26
|
refinedweb
| 242
| 52.56
|
Interface an inertial measurement unit (IMU) with raspberry pi
First things first, if you have not checked out my previous blog about how to interface an ultrasonic sensor and a camera with raspberry pi, then have a quick read this blog.
“Knowing yourself is the beginning of all wisdom.” — Aristotle
This robot can sense it’s environment. But it has very less information about itself. I get a feeling, it’s a good time to make this robot wiser, after all it is getting older by the day ;p.
What does it mean, “knowing oneself” for a robot, I hear someone asking. The robot can know about it’s presence. Here’s a caveat, It can not magically know where it is in the 3D space directly, however, what it can know/track is it’s movement. This, in robotics, is called (jargon alert ⚠️ ) State Estimation.
The sensor or rather a bunch of sensors used for this purpose are together called an Inertial Measurement Unit (IMU).
There can be a number of sensors for different IMUs. The one that I am using (GY-521 module (MPU-6050)) has:
- 3 axis accelerometer (measures acceleration along 3 orthogonal axes)
- 3-axis gyroscope (measures angular velocity along 3 separate axes)
- Temperature sensor (you know what it does ;p)
From a hardware point of view, how to connect an IMU with raspberry pi?
This IMU has 8 pins, from VCC to INT. We only use the first 4 pins to connect it to the PI. These are:
- VCC — Voltage Common Collector (power input).
- GND — Ground.
- SCL — Serial Clock Line for IIC/I²C communication.
- SDA — Serial Data Line for IIC/I²C communication.
Following are the connections with the GPIO pins of PI:
# — Sensor — — — — — — ——PI (GPIO) — — — or — — — PI (Pin Num)
- VCC — — — — — — — — — 5V pin — — — -which is— — — — Pin 4
- GND — — — — — — — — — GND — — — — which is— — —- Pin 6
- SCL — — — — — — — — — GPIO 3- — — — which is — — — — Pin 5
- SDA — — — — — — — — — GPIO 2- — — — which is — — — Pin 3
Once the connections are made and raspberry pi is powered on, the IMU light switches on.
Great. The IMU has been interfaced with the raspeberry pi. Before running a program. I²C communication has to be enabled in raspberry pi.
Follow the steps below to enable the I²C communication in pi:
- Run the following command to start the raspberry configuration tool.
sudo raspi-config
2. Select no. 5 which says Interfacing options.
3. Select and enable the I2C (P5).
Now, let’s test this sensor by writing a small basic program in python.
In order to use code from a dedicated standard library for MPU-6050 IMU, install the library from here and import it.
from mpu6050 import mpu6050
sensor = mpu6050(0x68)
while (1):
accelerometer_data = sensor.get_accel_data()
temp = sensor.get_temp()
gyro_data = sensor.get_gyro_data() print("Acceleration")
print("-----------------")
print(accelerometer_data) print("-----------------")
print("Temperatue")
print("-----------------")
print(temp) print("-----------------")
print("Gyro data")
print("-----------------")
print(gyro_data)
print("-----------------")
Code is available at the repository mentioned below.
SharadRawat/pi_sensor_setup
This repository contains code required to get meaningfull data from camera, IMU and how instructions are sent to Motor…
github.com
The output is as follows:
Hmm. I know what you are thinking. Z- component of acceleration should be somewhere around 9.8 m/s² (acc. due to gravity). But it is not. Cheaper IMUs have a big disadvantage, they produce noisy measurements and are sensitive to temperature based fluctuations.
As a result, I will try to make the sensor model keeping this problem in mind and can further use a filtering technique (Kalman Filter) to make this data more reliable. But this is for future blogs. Let’s not get ahead of ourselves.
In this blog, we learnt how to connect the IMU with raspberry pi and how to extract three types of data from it. This robot has enough sensors now for me to start working on the software module.
Thanks for reading this long blog. We have made a good progress and if you like this blog, please clap.
|
https://sharad-rawat.medium.com/interface-an-inertial-measurement-unit-imu-with-raspberry-pi-3d7b9583db09?source=user_profile---------2----------------------------
|
CC-MAIN-2021-43
|
refinedweb
| 654
| 66.13
|
Vue.js 2 Authentication Tutorial, Part 1
Vue.js 2 Authentication Tutorial, Part 1
In Part 1 of this 3 part series, we introduce Vue.js, how it compares to other JavaScript frameworks, and show a bit of the code you can employ with it.
Join the DZone community and get the full member experience.Join For Free
Learn how to add document editing and viewing to your web app on .Net (C#), Node.JS, Java, PHP, Ruby, etc.
Vue.js was developed by Evan You, an ex-Google software engineer. Just before launching Vue.js 2.0, he started to work on Vue.js full time and as a result, Vue.js 2 is now significantly lighter, smaller in size, and faster. Currently, many popular products use Vue.js to build their user interfaces. Such platforms include Laravel Spark, Grammarly, Statamic, Laracasts, and more. There is a comprehensive list of projects using Vue.js on Github. Vue.js 2's documentation is very detailed, and there is a vibrant community of users.
Vue.js 2, Angular 2, and React
Vue.js was inspired by AngularJS in its early days of development, thus making some of its syntaxes look very similar to AngularJS, e.g.
v-show,
v-if and
v-for. Angular 2 came onto the scene with a completely new framework in terms of API design, underlying language, and many add-ons, which was initially disturbing for a lot of developers. Now Vue.js 2, despite being a full rewrite, made its API largely compatible with Vue.js 1.0, thus making it super easy for developers to transition from Vue.js 1.0 to 2.0. Whoop! Whoop!
Vue.js 2.0 comes bundled with some major changes:
- The rendering layer is now based on a lightweight virtual-DOM implementation, Snabbom.
- Detection of static class names and attributes so that they are never diff after the initial render.
- Detection of subtrees without dynamic bindings and hoisting them out of the render function, which as a result leads to diff skipping on each re-render.
- It supports server-side rendering with client-side hydration. React and Angular 2 also provides server-side rendering.
- Support for JSX. The template syntax is still available for use, but you can always drop down to the virtual-DOM layer whenever you feel constrained by the use of templates.
- The template-to-virtual-DOM compiler and the runtime can be separated, so you can pre-compile templates and ship your app with only the runtime, which is less than 12kb min+gzip.
AngularJS(Angular 1) uses two-way binding between scopes, while Vue enforces a one-way data flow between components.
Vue.js 2 and Angular 2 are similar in a way because they both offer component-based systems.
React and Vue.js are also similar in many ways. They both:
- Utilize a virtual DOM.
- Provide composable view components.
- Have a core library and have sister libraries for handling state, routing, network requests, etc. the state changes. To avoid unnecessary re-rendering, you have to manually implement
shouldComponentUpdate. In Vue.js, a component’s dependencies are automatically tracked during its render, so the system knows precisely which components actually need to re-render.
According to this benchmark, Vue 2's app size is smaller than Angular 2.
Understanding Key Concepts in Vue.js 2
Vue.js 2 is similar to React and Angular 2 in a few ways. There are few key concepts that will help you get started easily. I'll give a basic overview of these concepts to nourish your understanding of Vue.js. They are:
- Directives
- Components
- Template/JSX
You can decide to use Vue.js 2 by simply invoking methods on a Vue instance or by going the component-composing route.
<div id="app"> <p></p> </div>
var app = new Vue({ el: '#app', data: { message: 'Hello, it is this easy!' } })
The result of the code above on the browser will be Hello, it is this easy!. The value of any property in the data object within a new Vue instance will be rendered to the DOM easily. The curly braces `` are used to display the property on the web page.
Directives
It's very easy to toggle the display of items on a web page with inbuilt directives such as
v-if,
v-show like so:
<div id="app"> <p v-</p> </div>
var app = new Vue({ el: '#app', data: { message: 'Hello, it is this easy!' }, methods: { visible: function() { return true; } } });
If for any reason, the
visible function returns false, the paragraph would not be displayed on the web page. What about iterations and loops? Check out the code below:
<div id="app"> <ol> <li v- </li> </ol> </div>
var app = new Vue({ el: '#app', data: { items: [ { name: 'Prosper Otemuyiwa' }, { name: 'Goodness Kintakunte' }, { name: 'Lynda' } ] } });
On the page, it will simply display:
Prosper Otemuyiwa Goodness Kintakunte Lynda
Components
Vue.js 2 also leverages components. It allows you to build large applications composed of small, self-contained smaller components.
An example of a component is an HTML5 tag, say
<header>. A header can have attributes, it can be styled and also possess its own behavior. In Vue.js 2, you'll be able to build your own custom component by registering it like so:
Vue.component('app-nav', { template: "<li>This is the application's navbar</li>" })
Then, you can use it in another component like so:
<div> <app-nav></app-nav> </div>
So, your component will now be
<app-nav></app-nav>.
Vue.js 2 provides some methods that are triggered at various points from creating a component up until the component is destroyed. This is called the Instance Lifecycle, also known as the Component's Lifecycle. Each Vue instance goes through a series of initialization steps when it is created - for example, it needs to set up data observation, compile the template, mount the instance to the DOM, and update the DOM when data changes. So you can execute custom logic in these hooks. These lifecycle hooks are:
beforeCreate,
created,
beforeMount,
mounted,
beforeUpdate,
updated,
activated,
deactivated,
beforeDestroy and
destroyed.
Vue.js 2 Lifecycle hooks
- beforeCreate() : This method is called synchronously after the Vue instance has just been initialized, before data observation and event/watcher setup.
- created() : This method is called synchronously after the Vue instance is created. Data observation, computed properties, methods and event callbacks have already been set up at this stage but the mounting phase has not started yet.
- beforeMount() : This method is called right before the component is mounted. So it is called before the
rendermethod is executed.
- mounted() : This method is called after the component has just been mounted.
- beforeUpdate() : This method is called when the data changes, before the virtual DOM is re-rendered and patched.
- updated() : This method is called after a data change causes the virtual DOM to be re-rendered and patched.
- activated() : This method is called when a kept-alive component is activated.
- deactivated() : This method is called when a kept-alive component is deactivated.
- beforeDestroy() : This method is called right before a Vue instance or component is destroyed. At this stage, the instance is still fully functional.
- destroyed() : This method is called after a Vue instance or component has been destroyed. When this hook is called, all directives of the Vue instance have been unbound, all event listeners have been removed, and all child Vue instances have also been destroyed.
Vue.js 2 possess some built-in components such as
component,
transition,
transition-group,
keep-alive and
slot. You can take advantage of these components in your app. Check out how to use them.
Props
Props is the short form for
properties. Properties are attributes of a component. In fact, props are how components talk to each other. A tag in HTML such as
<img> has an attribute, a.k.a. a
prop called
src that points to the location of an image.
In Vue.js 2, you can pass data from the parent scope into child components. A typical example is this:
Vue.component('tag-list', { props: ['item'], template: '<li></li>' }) var app = new Vue({ el: '#app', data: { tagList: [ { tag: '5kbae' }, { tag: 'Based on Logistics' }, { tag: 'Image management' } ] } })
<div id="app"> <ol> <tag-list</todo-item> </ol> </div>
It will display these items on the web page like so:
5kbae Based on Logistics Image management
Template/JSX
Vue.js 2 uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying Vue instance’s data. All Vue.js templates are valid HTML that can be parsed by spec-compliant browsers and HTML parsers.
You can also decide to use JSX. JSX is the combination of HTML and JavaScript code in the same file. The browser is not meant to understand it. It must first be transpiled into standard JavaScript before the browser can understand. An example of JSX usage in Vue.js is:
data: { text: 'Hello world' }, render (h) { return ( <div id='message'>, { this.text } </div> ); }
Now, by default, Vue doesn't support JSX, but with the help of babel-plugin-transform-vue-jsx we can use JSX with Vue. Oh, the ecosystem should be thanked for this great tool. Whoop! Whoop!
With Vue 2, you can use the
render function to create a reactive element. And you can use JSX in it like so:
new Vue({ el: '#app', data: { msg: 'Click to see the message.' }, methods: { hello () { alert('This is the message.') } }, render: function render(h) { return ( <span class=my-class-3 style= on-click={ this.hello } > { this.msg } </span> ) } });
Can you see the power of JSX manifesting itself in Vue? Awesome! You can check out more information on JSX in Vue here.
In my next post, we'll go over how to build an application with Vue.js 2.
Extend your web service functionality with docx, xlsx and pptx editing. Check out ONLYOFFICE document editors for integration. }}
|
https://dzone.com/articles/vuejs-2-authentication-tutorial-part-1
|
CC-MAIN-2019-13
|
refinedweb
| 1,659
| 66.33
|
Macro tips
From Nemerle Homepage
Some quick notes about using macros and quotations. This should really be merged with macros' documentation page, but it will wait, because our parsetree structure is going to be changed soon and this will also impact quotations (simplyfiy them) a lot.
Quotations
For best reference of how to write quotations, take a look at algorithm used to translate them in the sources. This code is quite self explaining (at least if you just need to know how to write quotations).
Match cases.
Compiler API available from macros
Macros are arbitrary functions and they can reference any external classes. It is sometimes also useful to use Nemerle compiler API from withing a macro. It is usually done using two methods
- Using static helper functions from Nemerle.Compiler namespace
- Using the instance of typer to make more advanced things, like typing some code fragment, asking for defined local variables in current scope, etc.VisibleLocalVariables(msg) { def typer = Nemerle.Macros.ImplicitCTX(); when (typer.IsMainPass) { Message.Hint(""); Message.Hint($"Variables in $msg"); Message.Hint($"$(msg.Location)"); def locals = typer.LocalContext.GetLocals(); mutable count = 0; foreach ((name : Nemerle.Compiler.Parsetree.Name, _value : Nemerle.Compiler.LocalValue) in locals) { Message.Hint($" Variable: '$(name.Id)'"); count++; } Message.Hint($"In this location $count variable(s) are visible."); } <[ () ]> } ... mutable x = 0; PrintVisibleLocalVariables("some location");This code print:
Main.n(18,5):Warning: hint: Variables in "some location" Main.n(18,5):Warning: hint: Main.n:18:32:18:46: Main.n(18,5):Warning: hint: Variable: 'x' Main.n(18,5):Warning: hint: In this location 1 variable(s) are visible.
This is the way how you can get some compiler's internals for your own usage. Feel free to ask for new useful methods to be created in compiler if you need them.
|
http://nemerle.org/Macro_tips
|
crawl-001
|
refinedweb
| 299
| 52.87
|
Rules & Conventions
Rules
- No Spamming
- Please think before you post and be constructive.
- Don't post copyrighted material or intellectual property without permission and proper attribution (also see copyrightpage).
Conventions
- This site is intended for scientific collaboration. It is not to be used for:
- Research unrelated to climate, ecosystems, and carbon or water cycling.
- Commentaries on climate change or the vast conspiracy behind climate science.
- Rambling about random subjects - stick to research ideas and activities such as measurements, methodology, results, and relevant discussions about these things.
- Cite relevant research papers mentioned in your text.
- Please look at the content of the site before posting or editing and try to be consistent with the style (such as it is) of this content.
- Before creating a page, make sure it is consistent with the namespace and pagename conventions used on this site. The topic index is a good way to familiarize yourself with the site's organization. For example: If you add a research project, give it a namespace (
new_project/) and first describe it with a new
overview/page in that namespace (ie. newproject:overview). You can add site-specific pages, like measurement logs, preliminary data, etc., to the project namespace (ie. new_project:soilcollectionlog). If you add procedures or other info that can be generalized to other projects, put them in the appropriate namespace (procedures, or instruments for example).
- Please send us an email if you are contributing to, or would like to contribute, the site. We'd love to chat with people with similar research projects and interests.
|
https://earthscinotebook.readthedocs.io/en/latest/wiki/standards/
|
CC-MAIN-2019-09
|
refinedweb
| 257
| 55.64
|
Hi, I'm trying to count the number of unique IP addresses present in an apache log file. I am using a text file to store the unique IP addresses as this needs to scale to large numbers of IP addresses (upwards of 100 million) so using a dictionary or any other data structure stored in memory would make the machine run out of RAM.
import re import os import fileinput def ipCounter(myline): if ippattern.search(myline): #search for all existing ips and store in list iplist = ippattern.findall(myline) #Open the IP file in read mode ip_file = open("unique_ips.txt",'r') for eachip in iplist: for line in ip_file: if line.find(eachip) > 0: break else: print "adding to file..." #Close file and open in append mode ip_file.close() ip_file = open("unique_ips.txt",'a') #Now write the new IP address found to the file ip_file.write(eachip) #Close file again ip_file.close() ippattern = re.compile(r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b") #Iterate through all files in directory for fname in os.listdir(os.getcwd()): if fname.find('LOG' or 'log')> 0: print "Processing....."+fname inputlog = fname #Open the log and start going through it line by line for line in fileinput.input(inputlog): ipCounter(line) fileinput.close()
My final output file does'nt seem to get populated by any addresses, I'm not sure about the part in ipCounter() where I check if the IP address is already present and if not, append it to the file. I would be grateful for any help.
Thanks,
Adi
|
https://www.daniweb.com/programming/software-development/threads/282731/counting-millions-of-unique-ip-addresses
|
CC-MAIN-2018-30
|
refinedweb
| 282
| 76.62
|
3 years ago.
how to reduce the footprint of the binary image
Hi, I'm quite new to the mbed platform (and the ARM Cortex microcontrollers).
I am using the platformio build system (ie. gcc) which has support for mbed.
My question is about the generated .bin file, which I find huge. For example, the simple led blink example:
#include "mbed.h" DigitalOut myled(LED1); int main() { while(1) { myled = 1; wait(1); myled = 0; wait(1); } }
produces a firmware.bin file of 12620 bytes (for a Nucleo f031k6). Note that I gave a quick try to the online IDE and the produced file is almost the same size.
I find this way too big, so I was wondering if there is a way to disable mbed features I don't need. I mean the little F031K6 only have 32k of flash, so it's very hard to make something useful of it if I cannot shrink somehow the binary firmware.
How do you make your firmware files smaller? I haven't found any clue on the mbed.org site, but I may have missed something.
Thanks,
David
You need to log in to post a question
|
https://os.mbed.com/questions/70299/how-to-reduce-the-footprint-of-the-binar/
|
CC-MAIN-2019-35
|
refinedweb
| 197
| 85.08
|
Top React Hooks — Swipes and States
Hooks contains our logic code in our React app.
We can create our own hooks and use hooks provided by other people.
In this article, we’ll look at some useful React hooks.
React Swipeable
React Swipeable is a library that lets us handle swipe events in our app.
For instance, we can write:
import React from "react";
import { useSwipeable, Swipeable } from "react-swipeable";export default function App() {
const handlers = useSwipeable({
onSwiped: eventData => console.log("swiped")
});
return <div {...handlers}> swipe here </div>;
}
We use the
useSwipeable hook which takes an object with some options.
onSwiped is a callback that runs when the we swipe on the elements with the
handlers .
We can add options to the 2nd argument of the
useSwipeable hook.
For instance, we can write:
import React from "react";
import { useSwipeable, Swipeable } from "react-swipeable";export default function App() {
const handlers = useSwipeable({
onSwiped: eventData => console.log("swiped"),
onSwipedLeft: eventData => console.log("swiped left"),
onSwipedRight: eventData => console.log("swiped right"),
onSwipedUp: eventData => console.log("swiped up"),
onSwipedDown: eventData => console.log("swiped down"),
onSwiping: eventData => console.log("swiping")
});
return <div {...handlers}> swipe here </div>;
}
to add more handlers that handlers different kinds of swiping.
React Tracked
The React Tracked is a package that lets us manage shared states.
To install it, we run:
npm install react-tracked
Then we can use it by writing:
import React from "react";
import { createContainer } from "react-tracked";const useValue = ({ reducer, initialState }) =>
React.useReducer(reducer, initialState);
const { Provider, useTracked } = createContainer(useValue);const initialState = {
count: 0
};const reducer = (state, action) => {
switch (action.type) {
case "increment":
return { ...state, count: state.count + 1 };
case "decrement":
return { ...state, count: state.count - 1 };
default:
throw new Error(`unknown action type: ${action.type}`);
}
};const Counter = () => {
const [state, dispatch] = useTracked();
return (
<div>
<div>
<span>Count: {state.count}</span>
<button type="button" onClick={() => dispatch({ type: "increment" })}>
increment
</button>
<button type="button" onClick={() => dispatch({ type: "decrement" })}>
decrement
</button>
</div>
</div>
);
};export default function App() {
return (
<>
<Provider reducer={reducer} initialState={initialState}>
<Counter />
<Counter />
</Provider>
</>
);
}
We create the
useValue function which takes the
reducer and
initial state and pass them to the
useReducer hook.
Then we call
createContainer get the value.
The reducer is like another reducer we see.
The
Counter component gets and sets the state with the
useTracked hook.
state has the states we have.
dispatch is a function to dispatch our actions.
Then in
App , we use the
Provider returns from
createContainer to let us share states with the provider.
The state is accessible with anything inside.
reducer has the reducer we created earlier.
initialState has the initial state.
And we put the
Counter inside it to let us get and set the shared state.
Conclusion
React Swipeable lets us watch for swipe events and handle them.
React Tracked lets us created shared states like other popular state management solutions.
|
https://hohanga.medium.com/top-react-hooks-swipes-and-states-1559b734ba77
|
CC-MAIN-2021-25
|
refinedweb
| 473
| 60.11
|
This article is in need of a technical review.
Summary
getAttributeNS returns the string value of the attribute with the specified namespace and name. If the named attribute does not exist, the value returned will either be
null or
"" (the empty string); see Notes for details.
Syntax
attrVal = element.getAttributeNS(namespace, name)
Parameters
namespace
- The namespace in which to look for the specified attribute.
name
- The name of the attribute to look for.
Return value
The string value of the specified attribute. If the attribute doesn't exist, the result is
null.
Examples
The following SVG document reads the value of the
foo attribute in a custom namespace.
<svg xmlns="" xmlns: <circle id="target" cx="12" cy="12" r="10" stroke="#444" stroke- <script type="text/javascript"> var ns = ''; var circle = document.getElementById( 'target' ); alert( 'attribute test:foo: "' + circle.getAttributeNS( ns, 'foo' ) + '"' ); </script> </svg>
In an HTML5 document the attribute has to be accessed with
test:foo since namespaces are not supported.
<!DOCTYPE html> <html> <body> <svg xmlns="" xmlns: <circle id="target" cx="12" cy="12" r="10" stroke="#444" stroke- </svg> <script type="text/javascript"> var ns = ''; var circle = document.getElementById( 'target' ); console.log('Attribute value: ' + circle.getAttribute('test:foo')); </script> </body> </html>
Notes
Namespaces are only supported in XML documents. HTML5 documents have to use
getAttribute() instead.
getAttributeNS() differs from
getAttribute() in that it allows you to further specify the requested attribute as being part of a particular namespace, as in the example above, where the attribute is part of the fictional "specialspace" namespace on Mozilla.
Prior to the DOM4 specification, this method was specified to return an empty string rather than null for non-existent attributes. However, most browsers instead returned null. Starting with DOM4, the specification now says to return null. However, some older browsers return an empty string. For that reason, you should use
hasAttributeNS() to check for an attribute's existence prior to calling
getAttributeNS() if it is possible that the requested attribute does not exist on the specified element.
DOM methods dealing with element's attributes:
Browser compatibility
Gecko notes
Starting in Gecko 13.0 (Firefox 13.0 / Thunderbird 13.0 / SeaMonkey 2.10),
null is always returned instead of the empty string, as per the DOM4 specification. Previously, there were cases in which an empty string could be returned.
|
https://developer.mozilla.org/en-US/docs/Web/API/Element/getAttributeNS
|
CC-MAIN-2015-11
|
refinedweb
| 387
| 59.09
|
Openpyxl library to write excel file with styles
Openpyxl probably the most popular python library for read/write Excel xlsx files. In this article, I will be sharing with you how to write data into excel file with some formatting.
Let’s get started with openpyxl.
If you have not yet installed this openpyxl library in your working environment, you may use the below command to install it.
pip install openpyxl
And we shall import the library and modules at the beginning of the script:
import openpyxl from openpyxl.styles import Alignment, Border, Side, Font
Now I am going to create a new excel with the sheet name as “Demo”:
workbook = openpyxl.Workbook() sheet = workbook.active sheet.title = "Demo"
Assuming if you have the below data that you want to write into the excel file:
raw_data = [["University Name", "No. of Students", "Address", "Contact"], ["National University of Singapore", "35908", "21 Lower Kent Ridge Rd, Singapore 119077", "68741616"], ["Nanyang Technological University", "31687", "50 Nanyang Ave, 639798", "67911744"], ["Singapore Management University", "8182", "81 Victoria St, Singapore 188065", "68280100"]]
You can loop through the list to get the value and assign it to a particular excel cell. Note that the excel row and columns always starts from 1.
for row_idx, rec in enumerate(raw_data): for col_idx, val in enumerate(rec): sheet.cell(row=row_idx+1, column=col_idx+1).value = val
if you save your data now via the below code, you will see that the saved excel does not come with any formatting (default formatting)
workbook.save("Demo.xlsx")
As you can see, the format does not look good and some of the column width needs to be adjusted in order to see the full content. Let’s apply some styling to the cells.
Let’s draw the borders for each of the cells, you can specify the color of the border as well as the border style. for more border styles, you can refer to this openpyxl document. you can also use different style for different side of the borders.
thin = Side(border_style="thin", color="303030") black_border = Border(top=thin, left=thin, right=thin, bottom=thin)
you can also give different width for the different columns as per below :
sheet.column_dimensions["A"].width = 27 sheet.column_dimensions["B"].width = 12 sheet.column_dimensions["C"].width = 33 sheet.column_dimensions["D"].width = 8
Define your own font style:
font = Font(name='Calibri', size=9, bold=True, color='07101c')
Define the alignment style, and you can definitely use different alignment style for different columns. Here I just defined 1 style for all cells.
align = Alignment(horizontal="center", wrap_text= True, vertical="center")
Next, Let’s apply the above styles to each of the cell and save the worksheet:
for label in ["A", "B", "C", "D"]: for col_idx in range(row_num): idx = label + str(col_idx + 1) sheet[idx].alignment = algin sheet[idx].font = font sheet[idx].border = black_border workbook.save("Demo.xlsx")
The final output should be similar to the below, which looks much better with the styling.
As per always, welcome to any comments or questions.
|
https://www.codeforests.com/2020/06/11/openpyxl-to-write-excel-with-styles/
|
CC-MAIN-2022-21
|
refinedweb
| 507
| 55.84
|
import "google.golang.org/appengine/user"
Package user provides a client for App Engine's user authentication service.
oauth.go user.go user_vm.go
IsAdmin returns true if the current user is signed in and is currently registered as an administrator of the application.
LoginURL returns a URL that, when visited, prompts the user to sign in, then redirects the user to the URL specified by dest.
LoginURLFederated is like LoginURL but accepts a user's OpenID identifier.
LogoutURL returns a URL that, when visited, signs the user out, then redirects the user to the URL specified by dest.
OAuthConsumerKey returns the OAuth consumer key provided with the current request. This method will return an error if the OAuth request was invalid. }
User represents a user of the application.
Current returns the currently logged-in user, or nil if the user is not signed in..
String returns a displayable name for the user.
Package user imports 5 packages (graph) and is imported by 165 packages. Updated 2019-08-30. Refresh now. Tools for package owners.
|
https://godoc.org/google.golang.org/appengine/user
|
CC-MAIN-2019-39
|
refinedweb
| 175
| 57.67
|
Table of Contents
Our early learning of Haskell has two distinct aspects. The first is coming to terms with the shift in mindset from imperative programming to functional: we have to replace our programming habits from other languages. We do this not because imperative techniques are bad, but because in a functional language other techniques work better.
Our second challenge is learning our way around the standard Haskell libraries. As in any language, the libraries act as a lever, enabling us to multiply our problem solving power. Haskell libraries tend to operate at a higher level of abstraction than those in many other languages. We'll need to work a little harder to learn to use the libraries, but in exchange they offer a lot of power.
In this chapter, we'll introduce a number of common functional programming techniques. We'll draw upon examples from imperative languages to highlight the shift in thinking that we'll need to make. As we do so, we'll walk through some of the fundamentals of Haskell's standard libraries. We'll also intermittently cover a few more language features along the way.
In most of this chapter, we will concern ourselves with code that has no interaction with the outside world. To maintain our focus on practical code, we will begin by developing a gateway between our “pure” code and the outside world. Our framework simply reads the contents of one file, applies a function to the file, and writes the result to another file.
-- file: ch04/InteractWith.hs -- Save this in a source file, e.g. Interact.hs "error: exactly two arguments needed" -- replace "id" with the name of our function below myFunction = id
This is all we need to write simple, but complete, file
processing programs. This is a complete program. We can
compile it to an executable named
InteractWith as follows.
$
ghc --make InteractWith[1 of 1] Compiling Main ( InteractWith.hs, InteractWith.o ) Linking InteractWith ...
If we run this program from the shell or command prompt, it will accept two file names: the name of a file to read, and the name of a file to write.
$
./Interacterror: exactly two arguments needed
$
./Interact hello-in.txt hello-out.txt
$
cat hello-in.txthello world
$
cat hello-out.txthello world
Some of the notation in our source file is new. The
do
keyword introduces a block of actions that
can cause effects in the real world, such as reading or writing
a file. The
<- operator is the equivalent of
assignment inside a
do block. This is enough explanation to
get us started. We will talk in much more detail about these
details of notation, and I/O in general, in Chapter 7, I/O..
Has only
splits quite have
organized our code. We only need to match a single carriage return or newline at a time, examining one element of the list at a oberving-empty. This can further help the readability of our code.
This style of creating and reusing small, powerful pieces of code is a fundamental part of functional programming.
Let's hook our
splitLines function
into the little framework we wrote earlier. Make a copy of
the
Interact. This makes
Usually, when we define or apply a function in Haskell, we write the name of the function, followed by its arguments. This notation is referred to as prefix, because the name of the function comes before its arguments.
If a function or constructor takes two or more arguments, we have the option of using it in infix form, where we place it between its first and second arguments. This allows us to use functions as infix operators.
To define or apply a function or value constructor using infix notation, we enclose its name in backtick characters (sometimes known as backquotes). Here are simple infix definitions of a function and a type.
-- file: ch04/Plus.hs a `plus` b = a + b data a `Pair` b = a `Pair` b deriving (Show) -- we can use the constructor either prefix or infix foo = Pair 1 2 bar = True `Pair` "quux"
Since infix notation is purely a syntactic convenience, it does not change a function's behavior.
ghci>
1 `plus` 23
ghci>
plus 1 23
ghci>
True `Pair` "something"True `Pair` "something"
ghci>
Pair True "something"True `Pair` "something"
Infix notation can often help readability. For
instance, the Prelude defines a function,
elem, that indicates whether a value is
present in a list. If we use
elem using
prefix notation, it is fairly easy to read.
ghci>
elem 'a' "camogie"True
If we switch to infix notation, the code becomes even easier to understand. It is now clearer that we're checking to see if the value on the left is present in the list on the right.
ghci>
3 `elem` [1,2,4,8]False
We see a more pronounced improvement with some useful functions from the
Data.List module.
The
isPrefixOf function tells us if one list
matches the beginning of another.
ghci>
:module +Data.List
ghci>
"foo" `isPrefixOf` "foobar"True
The
isInfixOf and
isSuffixOf functions match anywhere in a list
and at its end, respectively.
ghci>
"needle" `isInfixOf` "haystack full of needle thingies"True
ghci>
"end" `isSuffixOf` "the end"True
There is no hard-and-fast rule that dictates when you ought to use infix versus prefix notation, although prefix notation is far more common. It's best to choose whichever makes your code more readable in a specific situation.
As the bread and butter of functional programming, lists deserve some serious attention. The standard prelude defines dozens of functions for dealing with lists. Many of these will be indispensable tools, so it's important that we learn them early on.
For better or worse, this section is going to read a bit like a “laundry list” of functions. Why present so many functions at once? These functions are both easy to learn and absolutely ubiquitous. If we don't have this toolbox at our fingertips, we'll end up wasting time by reinventing simple functions that are already present in the standard libraries. So bear with us as we go through the list; the effort you'll save will be huge.
The
Data.List module is the “real”
logical home of all standard list functions. The Prelude merely
re-exports a large subset of the functions exported by
Data.List. Several useful functions in
Data.List are not re-exported
by the standard prelude. As we walk through list functions in
the sections that follow, we will explicitly mention those that
are only in
Data.List.
ghci>
:module +Data.List
Because none of these functions is complex or takes more than about three lines of Haskell to write, we'll be brief in our descriptions of each. In fact, a quick and useful learning exercise is to write a definition of each function after you've read about it.
The
length function tells us how many
elements are in a list.
ghci>
:type lengthlength :: [a] -> Int
ghci>
length []0
ghci>
length [1,2,3]3
ghci>
length "strings are lists, too"22
If you need to determine whether a list is empty, use the
null function.
ghci>
:type nullnull :: [a] -> Bool
ghci>
null []True
ghci>
null "plugh"False
To access the first element of a list, we use the
head function.
ghci>
:type headhead :: [a] -> a
ghci>
head [1,2,3]1
The converse,
tail, returns all
but the head of a list.
ghci>
:type tailtail :: [a] -> [a]
ghci>
tail "foo""oo"
Another function,
last, returns the
very last element of a list.
ghci>
:type lastlast :: [a] -> a
ghci>
last "bar"'r'
The converse of
last is
init, which returns a list of all but the
last element of its input.
ghci>
:type initinit :: [a] -> [a]
ghci>
init "bar""ba"
Several of the functions above behave poorly on empty lists, so be careful if you don't know whether or not a list is empty. What form does their misbehavior take?
ghci>
head []*** Exception: Prelude.head: empty list
Try each of the above functions in ghci. Which ones crash when given an empty list?
When we want to use a function like
head, where we know that it might blow up
on us if we pass in an empty list, the temptation might
initially be strong to check the length of the list before we
call
head. Let's construct an
artificial example to illustrate our point.
-- file: ch04/EfficientList.hs myDumbExample xs = if length xs > 0 then head xs else 'Z'
If we're coming from a language like Perl or
Python, this might seem like a perfectly natural way to write
this test. Behind the scenes, Python lists are arrays; and
Perl arrays are, well, arrays. So they necessarily know how
long they are, and calling
len(foo) or
scalar(@foo) is a perfectly natural thing to do.
But as with many other things, it's not a good idea to blindly
transplant such an assumption into Haskell.
We've already seen the definition of the list
algebraic data type many times, and know that a list doesn't
store its own length explicitly. Thus, the only way that
length can operate is to walk the entire
list.
Therefore, when we only care whether or not a
list is empty, calling
length isn't a
good strategy. It can potentially do a lot more work than we
want, if the list we're working with is finite. Since Haskell lets
us easily create infinite lists, a careless use of
length may even result in an infinite
loop.
A more appropriate function to call here instead
is
null, which runs in constant time.
Better yet, using
null makes our code
indicate what property of the list we really care about. Here
are two improved ways of expressing
myDumbExample.
-- file: ch04/EfficientList.hs mySmartExample xs = if not (null xs) then head xs else 'Z' myOtherExample (x:_) = x myOtherExample [] = 'Z'
Functions that only have return values defined for a
subset of valid inputs are called partial
functions (calling
error doesn't qualify
as returning a value!). We call functions that return valid
results over their entire input domains
total functions.
It's always a good idea to know whether a function you're using is partial or total. Calling a partial function with an input that it can't handle is probably the single biggest source of straightforward, avoidable bugs in Haskell programs.
Some Haskell programmers go so far as to give partial
functions names that begin with a prefix such as
unsafe, so that they can't shoot themselves in
the foot accidentally.
It's arguably a deficiency of the standard prelude that
it defines quite a few “unsafe” partial
functions, like
head, without also
providing “safe” total equivalents.
Haskell's name for the “append” function is
(++).
ghci>
:type (++)(++) :: [a] -> [a] -> [a]
ghci>
"foo" ++ "bar""foobar"
ghci>
[] ++ [1,2,3][1,2,3]
ghci>
[True] ++ [][True]
The
concat function takes a list of
lists, all of the same type, and concatenates them
into a single list.
ghci>
:type concatconcat :: [[a]] -> [a]
ghci>
concat [[1,2,3], [4,5,6]][1,2,3,4,5,6]
It removes one level of nesting.
ghci>
concat [[[1,2],[3]], [[4],[5],[6]]][[1,2],[3],[4],[5],[6]]
ghci>
concat (concat [[[1,2],[3]], [[4],[5],[6]]])[1,2,3,4,5,6]
The
reverse function returns the
elements of a list in reverse order.
ghci>
:type reversereverse :: [a] -> [a]
ghci>
reverse "foo""oof"
For lists of Bool, the
and and
or functions
generalise their two-argument
cousins,
(&&) and
(||), over lists.
ghci>
:type andand :: [Bool] -> Bool
ghci>
and [True,False,True]False
ghci>
and []True
ghci>
:type oror :: [Bool] -> Bool
ghci>
or [False,False,False,True,False]True
ghci>
or []False
They have more useful cousins,
all
and
any, which operate on lists of any
type. Each one takes a predicate as its first argument;
all returns
True if that
predicate succeeds on every element of the list, while
any returns
True if the
predicate succeeds on at least one element of the list.
ghci>
:type allall :: (a -> Bool) -> [a] -> Bool
ghci>
all odd [1,3,5]True
ghci>
all odd [3,1,4,1,5,9,2,6,5]False
ghci>
all odd []True
ghci>
:type anyany :: (a -> Bool) -> [a] -> Bool
ghci>
any even [3,1,4,1,5,9,2,6,5]True
ghci>
any even []False
The
take function, which we
already met in the section called “Function application”, returns a
sublist consisting of the first k
elements from a list. Its converse,
drop,
drops k elements from the start of the
list.
ghci>
:type taketake :: Int -> [a] -> [a]
ghci>
take 3 "foobar""foo"
ghci>
take 2 [1][1]
ghci>
:type dropdrop :: Int -> [a] -> [a]
ghci>
drop 3 "xyzzy""zy"
ghci>
drop 1 [][]
The
splitAt function
combines the functions of
take and
drop, returning a pair of the input list,
split at the given index.
ghci>
:type splitAtsplitAt :: Int -> [a] -> ([a], [a])
ghci>
splitAt 3 "foobar"("foo","bar")
The
takeWhile and
dropWhile functions take predicates:
takeWhile takes elements from the
beginning of a list as long as the predicate returns
True, while
dropWhile drops
elements from the list as long as the predicate returns
True.
ghci>
:type takeWhiletakeWhile :: (a -> Bool) -> [a] -> [a]
ghci>
takeWhile odd [1,3,5,6,8,9,11][1,3,5]
ghci>
:type dropWhiledropWhile :: (a -> Bool) -> [a] -> [a]
ghci>
dropWhile even [2,4,6,7,9,10,12][7,9,10,12]
Just as
splitAt “tuples
up” the results of
take and
drop, the functions
break (which we already saw in the section called “Warming up: portably splitting lines of text”) and
span
tuple up the results of
takeWhile and
dropWhile.
Each function takes a predicate;
break consumes its input while its
predicate fails, while
span consumes
while its predicate succeeds.
ghci>
:type spanspan :: (a -> Bool) -> [a] -> ([a], [a])
ghci>
span even [2,4,6,7,9,10,11]([2,4,6],[7,9,10,11])
ghci>
:type breakbreak :: (a -> Bool) -> [a] -> ([a], [a])
ghci>
break even [1,3,5,6,8,9,10]([1,3,5],[6,8,9,10])
As we've already seen, the
elem function indicates whether a value
is present in a list. It has a companion function,
notElem.
ghci>
:type elemelem :: (Eq a) => a -> [a] -> Bool
ghci>
2 `elem` [5,3,2,1,1]True
ghci>
2 `notElem` [5,3,2,1,1]False
For a more general search,
filter
takes a predicate, and returns every element of the list on
which the predicate succeeds.
ghci>
:type filterfilter :: (a -> Bool) -> [a] -> [a]
ghci>
filter odd [2,4,1,3,6,8,5,7][1,3,5,7]
In
Data.List, three predicates,
isPrefixOf,
isInfixOf, and
isSuffixOf, let us test for the presence
of sublists within a bigger list. The easiest way to use them
is using infix notation.
The
isPrefixOf function tells us
whether its left argument matches the beginning of its right
argument.
ghci>
:module +Data.List
ghci>
:type isPrefixOfisPrefixOf :: (Eq a) => [a] -> [a] -> Bool
ghci>
"foo" `isPrefixOf` "foobar"True
ghci>
[1,2] `isPrefixOf` []False
The
isInfixOf function indicates
whether its left argument is a sublist of its right.
ghci>
:module +Data.List
ghci>
[2,6] `isInfixOf` [3,1,4,1,5,9,2,6,5,3,5,8,9,7,9]True
ghci>
"funk" `isInfixOf` "sonic youth"False
The operation of
isSuffixOf shouldn't
need any explanation.
ghci>
:module +Data.List
ghci>
".c" `isSuffixOf` "crashme.c"True
The
zip function takes two lists and
“zips” them into a single list of pairs. The
resulting list is the same length as the shorter of the two
inputs.
ghci>
:type zipzip :: [a] -> [b] -> [(a, b)]
ghci>
zip [12,72,93] "zippity"[(12,'z'),(72,'i'),(93,'p')]
More useful is
zipWith, which takes
two lists and applies a function to each pair of elements,
generating a list that is the same length as the shorter of
the two.
ghci>
:type zipWithzipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
ghci>
zipWith (+) [1,2,3] [4,5,6][5,7,9]
Haskell's type system makes it an interesting challenge to
write functions that take variable numbers of
arguments[8]. So
if we want to zip three lists together, we call
zip3 or
zipWith3,
and so on up to
zip7 and
zipWith7.
We've already encountered the standard
lines function in the section called “Warming up: portably splitting lines of text”, and its standard counterpart,
unlines. Notice that
unlines always places a newline on the
end of its result.
ghci>
lines "foo\nbar"["foo","bar"]
ghci>
unlines ["foo", "bar"]"foo\nbar\n"
The
words function splits an input
string on any white space. Its counterpart,
unwords, uses a single space to join a
list of words.
ghci>
words "the \r quick \t brown\n\n\nfox"["the","quick","brown","fox"]
ghci>
unwords ["jumps", "over", "the", "lazy", "dog"]"jumps over the lazy dog"
Unlike traditional languages, Haskell has neither a
for loop nor a
while loop. If we've
got a lot of data to process, what do we use instead? There are
several possible answers to this question.
A straightforward way to make the jump from a language that has loops to one that doesn't is to run through a few examples, looking at the differences. Here's a C function that takes a string of decimal digits and turns them into an integer.
int as_int(char *str) { int acc; /* accumulate the partial result */ for (acc = 0; isdigit(*str); str++) { acc = acc * 10 + (*str - '0'); } return acc; }
Given that Haskell doesn't have any looping constructs, how should we think about representing a fairly straightforward piece of code like this?
We don't have to start off by writing a type signature, but it helps to remind us of what we're working with.
-- file: ch04/IntParse.hs import Data.Char (digitToInt) -- we'll need ord shortly asInt :: String -> Int
The C code computes the result incrementally as
it traverses the string; the Haskell code can do the same.
However, in Haskell, we can express the equivalent of a loop as a
function. We'll call ours
loop just to
keep things nice and explicit.
-- file: ch04/IntParse.hs loop :: Int -> String -> Int asInt xs = loop 0 xs
That first parameter to
loop is the
accumulator variable we'll be using. Passing zero into it is
equivalent to initialising the
acc variable
in C at the beginning of the loop.
Rather than leap into blazing code, let's think about the data we have to work with. Our familiar String is just a synonym for [Char], a list of characters. The easiest way for us to get the traversal right is to think about the structure of a list: it's either empty, or a single element followed by the rest of the list.
We can express this structural thinking directly by pattern matching on the list type's constructors. It's often handy to think about the easy cases first: here, that means we will consider the empty-list case.
-- file: ch04/IntParse.hs loop acc [] = acc
An empty list doesn't just mean “the input string is empty”; it's also the case we'll encounter when we traverse all the way to the end of a non-empty list. So we don't want to “error out” if we see an empty list. Instead, we should do something sensible. Here, the sensible thing is to terminate the loop, and return our accumulated value.
The other case we have to consider arises when the input list is not empty. We need to do something with the current element of the list, and something with the rest of the list.
-- file: ch04/IntParse.hs loop acc (x:xs) = let acc' = acc * 10 + digitToInt x in loop acc' xs
We compute a new value for the accumulator, and give it
the name
acc'. We then call the
loop function again, passing it the
updated value
acc' and the rest of the
input list; this is equivalent to the loop starting another
round in C.
Each time the
loop function calls
itself, it has a new value for the accumulator, and it
consumes one element of the input list. Eventually, it's
going to hit the end of the list, at which time the
[] pattern will match, and the recursive calls
will cease.
How well does this function work? For positive integers, it's perfectly cromulent.
ghci>
asInt "33"33
But because we were focusing on how to traverse lists, not error handling, our poor function misbehaves if we try to feed it nonsense.
ghci>
asInt ""0
ghci>
asInt "potato"*** Exception: Char.digitToInt: not a digit 'p'
We'll defer fixing our function's shortcomings to Q: 1.
Because the last thing that
loop does
is simply call itself, it's an example of a tail recursive
function. There's another common idiom in this code, too.
Thinking about the structure of the list, and handling the
empty and non-empty cases separately, is a kind of approach
called structural recursion.
We call the non-recursive case (when the list is empty) the base case (sometimes the terminating case). We'll see people refer to the case where the function calls itself as the recursive case (surprise!), or they might give a nod to mathematical induction and call it the inductive case.
As a useful technique, structural recursion is not confined to lists; we can use it on other algebraic data types, too. We'll have more to say about it later.
Consider another C function,
square,
which squares every element in an array.
void square(double *out, const double *in, size_t length) { for (size_t i = 0; i < length; i++) { out[i] = in[i] * in[i]; } }
This contains a straightforward and common kind of loop, one that does exactly the same thing to every element of its input array. How might we write this loop in Haskell?
-- file: ch04/Map.hs square :: [Double] -> [Double] square (x:xs) = x*x : square xs square [] = []
Our
square function consists of two
pattern matching equations. The first
“deconstructs” the beginning of a non-empty list,
to get its head and tail. It squares the first element, then
puts that on the front of a new list, which is constructed by
calling
square on the remainder of the
empty list. The second equation ensures that
square halts when it reaches the end of
the input list.
The effect of
square is to construct
a new list that's the same length as its input list, with
every element in the input list substituted with its square in
the output list.
Here's another such C loop, one that ensures that every letter in a string is converted to uppercase.
#include <ctype.h> char *uppercase(const char *in) { char *out = strdup(in); if (out != NULL) { for (size_t i = 0; out[i] != '\0'; i++) { out[i] = toupper(out[i]); } } return out; }
Let's look at a Haskell equivalent.
-- file: ch04/Map.hs import Data.Char (toUpper) upperCase :: String -> String upperCase (x:xs) = toUpper x : upperCase xs upperCase [] = []
Here, we're importing the
toUpper
function from the standard
Data.Char module,
which contains lots of useful functions for working with
Char data.
Our
upperCase function follows a
similar pattern to our earlier
square
function. It terminates with an empty list when the input
list is empty; and when the input isn't empty, it calls
toUpper on the first element, then
constructs a new list cell from that and the result of calling
itself on the rest of the input list.
These examples follow a common pattern for writing recursive functions over lists in Haskell. The base case handles the situation where our input list is empty. The recursive case deals with a non-empty list; it does something with the head of the list, and calls itself recursively on the tail.
The
square and
upperCase functions that we just defined
produce new lists that are the same lengths as their input
lists, and do only one piece of work per element. This is
such a common pattern that Haskell's prelude defines a
function,
map, to make it easier.
map takes a function, and applies it to
every element of a list, returning a new list constructed from
the results of these applications.
Here are our
square and
upperCase functions rewritten to use
map.
-- file: ch04/Map.hs square2 xs = map squareOne xs where squareOne x = x * x upperCase2 xs = map toUpper xs
This is our first close look at a function that
takes another function as its argument. We can learn a lot
about what
map does by simply inspecting
its type.
ghci>
:type mapmap :: (a -> b) -> [a] -> [b]
The signature tells us that
map takes
two arguments. The first is a function that takes a value of
one type,
a, and returns a
value of another type,
b.
Since
map takes a function as
argument, we refer to it as a
higher-order function. (In spite of the
name, there's nothing mysterious about higher-order functions;
it's just a term for functions that take other functions as
arguments, or return functions.)
Since
map abstracts out the pattern
common to our
square and
upperCase functions so that we can reuse
it with less boilerplate, we can look at what those functions
have in common and figure out how to implement it
ourselves.
-- file: ch04/Map.hs myMap :: (a -> b) -> [a] -> [b] myMap f (x:xs) = f x : myMap f xs myMap _ _ = []
We try out our
myMap function to give
ourselves some assurance that it behaves similarly to the
standard
map.
ghci>
:module +Data.Char
ghci>
map toLower "SHOUTING""shouting"
ghci>
myMap toUpper "whispering""WHISPERING"
ghci>
map negate [1,2,3][-1,-2,-3]
This pattern of spotting a repeated idiom, then abstracting it so we can reuse (and write less!) code, is a common aspect of Haskell programming. While abstraction isn't unique to Haskell, higher order functions make it remarkably easy.
Another common operation on a sequence of data is to comb through it for elements that satisfy some criterion. Here's a function that walks a list of numbers and returns those that are odd. Our code has a recursive case that's a bit more complex than our earlier functions: it only puts a number in the list it returns if the number is odd. Using a guard expresses this nicely.
-- file: ch04/Filter.hs oddList :: [Int] -> [Int] oddList (x:xs) | odd x = x : oddList xs | otherwise = oddList xs oddList _ = []
Let's see that in action.
ghci>
oddList [1,1,2,3,5,8,13,21,34][1,1,3,5,13,21]
Once again, this idiom is so common that the
Prelude defines a function,
filter, which
we have already introduced. It removes the need for
boilerplate code to recurse over the list.
ghci>
:type filterfilter :: (a -> Bool) -> [a] -> [a]
ghci>
filter odd [3,1,4,1,5,9,2,6,5][3,1,1,5,9,5]
The
filter function takes a
predicate and applies it to every element in its input list,
returning a list of only those for which the predicate
evaluates to
True. We'll revisit
filter again soon, in the section called “Folding from the right”.
Another common thing to do with a collection is reduce it to a single value. A simple example of this is summing the values of a list.
-- file: ch04/Sum.hs mySum xs = helper 0 xs where helper acc (x:xs) = helper (acc + x) xs helper acc _ = acc
Our
helper function is tail
recursive, and uses an accumulator parameter,
acc, to hold the current partial sum of the
list. As we already saw with
asInt, this
is a “natural” way to represent a loop in a pure
functional language.
For something a little more complicated, let's take a look at the Adler-32 checksum. This is a popular checksum algorithm; it concatenates two 16-bit checksums into a single 32-bit checksum. The first checksum is the sum of all input bytes, plus one. The second is the sum of all intermediate values of the first checksum. In each case, the sums are computed modulo 65521. Here's a straightforward, unoptimised Java implementation. (It's safe to skip it if you don't read Java.)
public class Adler32 { private static final int base = 65521; public static int compute(byte[] data, int offset, int length) { int a = 1, b = 0; for (int i = offset; i < offset + length; i++) { a = (a + (data[i] & 0xff)) % base; b = (a + b) % base; } return (b << 16) | a; } }
Although Adler-32 is a simple checksum, this code isn't particularly easy to read on account of the bit-twiddling involved. Can we do any better with a Haskell implementation?
-- file: ch04/Adler32.hs import Data.Char (ord) import Data.Bits (shiftL, (.&.), (.|.)) base = 65521 adler32 xs = helper 1 0 xs where helper a b (x:xs) = let a' = (a + (ord x .&. 0xff)) `mod` base b' = (a' + b) `mod` base in helper a' b' xs helper a b _ = (b `shiftL` 16) .|. a
This code isn't exactly easier to follow than
the Java code, but let's look at what's going on. First of
all, we've introduced some new functions. The
shiftL function implements a logical
shift left;
(.&.) provides bitwise
“and”; and
(.|.) provides
bitwise “or”.
Once again, our
helper function is
tail recursive. We've turned the two variables we updated on
every loop iteration in Java into accumulator parameters.
When our recursion terminates on the end of the input list, we
compute our checksum and return it.
If we take a step back, we can restructure our
Haskell
adler32 to more closely resemble
our earlier
mySum function. Instead of
two accumulator parameters, we can use a pair as the
accumulator.
-- file: ch04/Adler32.hs adler32_try2 xs = helper (1,0) xs where helper (a,b) (x:xs) = let a' = (a + (ord x .&. 0xff)) `mod` base b' = (a' + b) `mod` base in helper (a',b') xs helper (a,b) _ = (b `shiftL` 16) .|. a
Why would we want to make this seemingly
meaningless structural change? Because as we've already seen
with
map and
filter,
we can extract the common behavior shared by
mySum and
adler32_try2 into a higher-order
function. We can describe this behavior as “do
something to every element of a list, updating an
accumulator as we go, and returning the accumulator when
we're done”.
This kind of function is called a
fold, because it “folds up”
a list. There are two kinds of fold over lists,
foldl for folding from the left (the
start) and
foldr for folding from the
right (the end).
Here is the definition of
foldl.
-- file: ch04/Fold.hs foldl :: (a -> b -> a) -> a -> [b] -> a foldl step zero (x:xs) = foldl step (step zero x) xs foldl _ zero [] = zero
The
foldl function takes a
“step” function, an initial value for its
accumulator, and a list. The “step” takes an
accumulator and an element from the list, and returns a new
accumulator value. All
foldl does is call
the “stepper” on the current accumulator and an
element of the list, and passes the new accumulator value to
itself recursively to consume the rest of the list.
We refer to
foldl as a “left
fold” because it consumes the list from left (the
head) to right.
Here's a rewrite of
mySum using
foldl.
-- file: ch04/Sum.hs foldlSum xs = foldl step 0 xs where step acc x = acc + x
That local function
step just adds two
numbers, so let's simply use the addition operator instead,
and eliminate the unnecessary
where
clause.
-- file: ch04/Sum.hs niceSum :: [Integer] -> Integer niceSum xs = foldl (+) 0 xs
Notice how much simpler this code is than our
original
mySum? We're no longer using
explicit recursion, because
foldl takes
care of that for us. We've simplified our problem down to two
things: what the initial value of the accumulator should be
(the second parameter to
foldl), and how
to update the accumulator (the
(+)
function). As an added bonus, our code is now shorter, too,
which makes it easier to understand.
Let's take a deeper look at what
foldl is doing here, by manually writing
out each step in its evaluation when we call
niceSum
[1,2,3].
-- file: ch04/Fold.hs foldl (+) 0 (1:2:3:[]) == foldl (+) (0 + 1) (2:3:[]) == foldl (+) ((0 + 1) + 2) (3:[]) == foldl (+) (((0 + 1) + 2) + 3) [] == (((0 + 1) + 2) + 3)
We can rewrite
adler32_try2
using
foldl to let us focus on the
details that are important.
-- file: ch04/Adler32.hs adler32_foldl xs = let (a, b) = foldl step (1, 0) xs in (b `shiftL` 16) .|. a where step (a, b) x = let a' = a + (ord x .&. 0xff) in (a' `mod` base, (a' + b) `mod` base)
Here, our accumulator is a pair, so the result of
foldl will be, too. We pull the final
accumulator apart when
foldl returns, and
bit-twiddle it into a “proper” checksum.
A quick glance reveals that
adler32_foldl isn't really any shorter
than
adler32_try2. Why should we use a
fold in this case? The advantage here lies in the fact that
folds are extremely common in Haskell, and they have regular,
predictable behavior.
This means that a reader with.
This line of reasoning applies to other
higher-order library functions, including those we've already
seen,
map and
filter. Because they're library functions
with well-defined behavior, we only need to learn what they do
once, and we'll have an advantage when we need to understand
any code that uses them. These improvements in readability
also carry over to writing code. Once we start to think with
higher order functions in mind, we'll produce concise code
more quickly.
The counterpart to
foldl is
foldr, which folds from the right of a
list.
-- file: ch04/Fold.hs foldr :: (a -> b -> b) -> b -> [a] -> b foldr step zero (x:xs) = step x (foldr step zero xs) foldr _ zero [] = zero
Let's follow the same manual evaluation process with
foldr (+) 0 [1,2,3] as we did with
niceSum in the section called “The left fold”.
-- file: ch04/Fold.hs foldr (+) 0 (1:2:3:[]) == 1 + foldr (+) 0 (2:3:[]) == 1 + (2 + foldr (+) 0 (3:[]) == 1 + (2 + (3 + foldr (+) 0 [])) == 1 + (2 + (3 + 0)).
There is a lovely intuitive explanation of how
foldr works: it replaces the empty list
with the
zero value, and every constructor
in the list with an application of the step function.
-- file: ch04/Fold.hs 1 : (2 : (3 : [])) 1 + (2 + (3 + 0 ))
At first glance,
foldr might seem
less useful than
foldl: what use is a
function that folds from the right? But consider the
Prelude's
filter function, which we last
encountered in the section called “Selecting pieces of input”. If we write
filter using explicit recursion, it will
look something like this.
-- file: ch04/Fold.hs filter :: (a -> Bool) -> [a] -> [a] filter p [] = [] filter p (x:xs) | p x = x : filter p xs | otherwise = filter p xs
Perhaps surprisingly, though, we can write
filter as a fold, using
foldr.
-- file: ch04/Fold.hs myFilter p xs = foldr step [] xs where step x ys | p x = x : ys | otherwise = ys
This is the sort of definition that could cause us a
headache, so let's examine it in a little depth. Like
foldl,
foldr takes a
function and a base case (what to do when the input list is
empty) as arguments. From reading the type of
filter, we know that our
myFilter function must return a list of
the same type as it consumes, so the base case should be a
list of this type, and the
step helper
function must return a list.
Since we know that
foldr calls
step on one element of the input list at
a time, with the accumulator as its second argument, what
step does must be quite simple. If the
predicate returns
True, it pushes that
element onto the accumulated list; otherwise, it leaves the
list untouched.
The class of functions that we can express using
foldr is called primitive
recursive. A surprisingly large number of list
manipulation functions are primitive recursive. For example,
here's
map written in terms of
foldr.
-- file: ch04/Fold.hs myMap :: (a -> b) -> [a] -> [b] myMap f xs = foldr step [] xs where step x ys = f x : ys
In fact, we can even write
foldl
using
foldr!
-- file: ch04/Fold.hs myFoldl :: (a -> b -> a) -> a -> [b] -> a myFoldl f z xs = foldr step id xs z where step x g a = g (f a x)
Returning to our earlier intuitive explanation
of what
foldr does, another useful way to
think about it is that it transforms its
input list. Its first two arguments are “what to do
with each head/tail element of the list”, and
“what to substitute for the end of the
list”.
The “identity” transformation with
foldr thus replaces the empty list with
itself, and applies the list constructor to each head/tail
pair:
-- file: ch04/Fold.hs identity :: [a] -> [a] identity xs = foldr (:) [] xs
It transforms a list into a copy of itself.
ghci>
identity [1,2,3][1,2,3]
If
foldr replaces the end
of a list with some other value, this gives us another way to
look at Haskell's list append function,
(++).
ghci>
[1,2,3] ++ [4,5,6][1,2,3,4,5,6]
All we have to do to append a list onto another is substitute that second list for the end of our first list.
-- file: ch04/Fold.hs append :: [a] -> [a] -> [a] append xs ys = foldr (:) ys xs
ghci>
append [1,2,3] [4,5,6][1,2,3,4,5,6]
Here, we replace each list constructor with another list constructor, but we replace the empty list with the list we want to append onto the end of our first list.
As our extended treatment of folds should
indicate, the
foldr function is nearly as
important a member of our list-programming toolbox as the more
basic list functions we saw in the section called “Working with lists”. It can consume and produce a list
incrementally, which makes it useful for writing lazy data
processing code.
To keep our initial discussion simple, we used
foldl throughout most of this section.
This is convenient for testing, but we will never use
foldl in practice.
The reason has to do with Haskell's non-strict evaluation.
If we apply
foldl (+) [1,2,3], it evaluates to
the expression
(((0 + 1) + 2) + 3). We can see
this occur if we revisit the way in which the function gets
expanded.
-- file: ch04/Fold.hs foldl (+) 0 (1:2:3:[]) == foldl (+) (0 + 1) (2:3:[]) == foldl (+) ((0 + 1) + 2) (3:[]) == foldl (+) (((0 + 1) + 2) + 3) [] == (((0 + 1) + 2) + 3)
The final expression will not be evaluated to
6 until its value is demanded. Before it is
evaluated, it must be stored as a thunk. Not surprisingly, a
thunk is more expensive to store than a single number, and the
more complex the thunked expression, the more space it needs.
For something cheap like arithmetic, thunking an expresion is
more computationally expensive than evaluating it immediately.
We thus end up paying both in space and in time.
When GHC is evaluating a thunked expression, it uses an internal stack to do so. Because a thunked expression could potentially be infinitely large, GHC places a fixed limit on the maximum size of this stack. Thanks to this limit, we can try a large thunked expression in ghci without needing to worry that it might consume all of memory.
ghci>
foldl (+) 0 [1..1000]500500
From looking at the expansion above, we can surmise that
this creates a thunk that consists of 1000 integers and 999
applications of
(+). That's a lot of
memory and effort to represent a single number! With a larger
expression, although the size is still modest, the results are
more dramatic.
ghci>
foldl (+) 0 [1..1000000]*** Exception: stack overflow
On small expressions,
foldl will work
correctly but slowly, due to the thunking overhead that it
incurs. We refer to this invisible thunking as a
space leak, because our code is operating
normally, but using far more memory than it should.
On larger expressions, code with a space leak will simply
fail, as above. A space leak with
foldl is a
classic roadblock for new Haskell programmers. Fortunately,
this is easy to avoid.
The
Data.List module defines a function named
foldl' that is similar to
foldl, but does not build up thunks. The
difference in behavior between the two is immediately
obvious.
ghci>
foldl (+) 0 [1..1000000]*** Exception: stack overflow
ghci>
:module +Data.List
ghci>
foldl' (+) 0 [1..1000000]500000500000
Due to the thunking behavior of
foldl, it is wise to avoid this function
in real programs: even if it doesn't fail outright, it will be
unnecessarily inefficient. Instead, import
Data.List and use
foldl'.
In many of the function definitions we've seen so far, we've written short helper functions.
-- file: ch04/Partial.hs isInAny needle haystack = any inSequence haystack where inSequence s = needle `isInfixOf` s
Haskell lets us write completely anonymous
functions, which we can use to avoid the need to give names to
our helper functions. Anonymous functions are often called
“lambda” functions, in a nod to their heritage in
the lambda calculus. We introduce an anonymous function with a
backslash character,
\, pronounced lambda[9]. This is followed by the function's
arguments (which can include patterns), then an arrow
-> to introduce the function's body.
Lambdas are most easily illustrated by example. Here's a
rewrite of
isInAny using an anonymous
function.
-- file: ch04/Partial.hs isInAny2 needle haystack = any (\s -> needle `isInfixOf` s) haystack
We've wrapped the lambda in parentheses here so that Haskell can tell where the function body ends.
Anonymous functions behave in every respect identically to functions that have names, but Haskell places a few important restrictions on how we can define them. Most importantly, while we can write a normal function using multiple clauses containing different patterns and guards, a lambda can only have a single clause in its definition.
The limitation to a single clause restricts how we can use patterns in the definition of a lambda. We'll usually write a normal function with several clauses to cover different pattern matching possibilities.
-- file: ch04/Lambda.hs safeHead (x:_) = Just x safeHead _ = Nothing
But as we can't write multiple clauses to define a lambda, we must be certain that any patterns we use will match.
-- file: ch04/Lambda.hs unsafeHead = \(x:_) -> x
This definition of
unsafeHead will
explode in our faces if we call it with a value on which pattern
matching fails.
ghci>
:type unsafeHeadunsafeHead :: [t] -> t
ghci>
unsafeHead [1]1
ghci>
unsafeHead []*** Exception: Lambda.hs:7:13-23: Non-exhaustive patterns in lambda
The definition typechecks, so it will compile, so the error will occur at runtime. The moral of this story is to be careful in how you use patterns when defining an anonymous function: make sure your patterns can't fail!
Another thing to notice about the
isInAny and
isInAny2
functions we showed above is that the first version, using a
helper function that has a name, is a little easier to read than
the version that plops an anonymous function into the middle.
The named helper function doesn't disrupt the
“flow” of the function in which it's used, and the
judiciously chosen name gives us a little bit of information
about what the function is expected to do.
In contrast, when we run across a lambda in the middle of a function body, we have to switch gears and read its definition fairly carefully to understand what it does. To help with readability and maintainability, then, we tend to avoid lambdas in many situations where we could use them to trim a few characters from a function definition. Very often, we'll use a partially applied function instead, resulting in clearer and more readable code than either a lambda or an explicit function. Don't know what a partially applied function is yet? Read on!
We don't intend these caveats to suggest that lambdas are useless, merely that we ought to be mindful of the potential pitfalls when we're thinking of using them. In later chapters, we will see that they are often invaluable as “glue”.
You.
But white space this partial application of the function: we're applying the function to only some of its arguments.
In the example above, in the section called section called above
Haskell's
tails function, in
the
Data.List module, generalises the
tail function we introduced earlier.
Instead of returning one “tail” of a list, it
returns all of them.
ghci>
:m +Data.List
ghci>
tail "foobar""oobar"
ghci>
tail (tail "foobar")"obar"
ghci>
tails "foobar"["foobar","oobar","obar","bar","ar","r",""]
Each of these strings is a suffix of
the initial string, so
tails produces a
list of all suffixes, plus an extra empty list at the
end. It always produces that extra empty list, even
when its input list is empty.
ghci>
tails [][[]]
What if we want a function that behaves like
tails, but which only
returns the non-empty suffixes? One possibility would be for us
to write our own version by hand. We'll use a new piece of
notation, the
@ symbol.
-- file: ch04/SuffixTree.hs suffixes :: [a] -> [[a]] suffixes xs@(_:xs') = xs : suffixes xs' suffixes _ = []
The pattern
xs@(_:xs') is called an
as-pattern, and it means “bind the
variable
xs to the value that matches the
right side of the
@ symbol”.
In our example, if the pattern after the
“@” matches,
xs will be bound to
the entire list that matched, and
xs' to all
but the head of the list (we used the wild card
_
pattern to indicate that we're not interested in the value of
the head of the list).
ghci>
tails "foo"["foo","oo","o",""]
ghci>
suffixes "foo"["foo","oo","o"]
The as-pattern makes our code more readable. To see how it helps, let us compare a definition that lacks an as-pattern.
-- file: ch04/SuffixTree.hs noAsPattern :: [a] -> [[a]] noAsPattern (x:xs) = (x:xs) : noAsPattern xs noAsPattern _ = []
Here, the list that we've deconstructed in the pattern match just gets put right back together in the body of the function.
As-patterns have a more practical use than simple
readability: they can help us to share data instead of copying
it. In our definition of
noAsPattern, when
we match
(x:xs), we construct a new copy of it in
the body of our function. This causes us to allocate a new
list node at run time. That may be cheap, but it isn't free.
In contrast, when we defined
suffixes, we
reused the value
xs that we matched with our
as-pattern. Since we reuse an existing value, we avoid a little
allocation.
It seems a shame to introduce a new function,
suffixes, that does almost the same thing
as the existing
tails function. Surely we
can do better?
Recall the
init function we
introduced in the section called “Working with lists”: it returns all but
the last element of a list.
-- file: ch04/SuffixTree.hs suffixes2 xs = init (tails xs)
This
suffixes2 function
behaves identically to
suffixes, but it's a
single line of code.
ghci>
suffixes2 "foo"["foo","oo","o"]
If we take a step back, we see the glimmer of a pattern here: we're applying a function, then applying another function to its result. Let's turn that pattern into a function definition.
-- file: ch04/SuffixTree.hs compose :: (b -> c) -> (a -> b) -> a -> c compose f g x = f (g x)
We now have a function,
compose, that we can use to
“glue” two other functions together.
-- file: ch04/SuffixTree.hs suffixes3 xs = compose init tails xs
Haskell's automatic currying lets us drop the
xs variable, so we can make our definition
even shorter.
-- file: ch04/SuffixTree.hs suffixes4 = compose init tails
Fortunately, we don't need to write our own
compose function. Plugging functions into
each other like this is so common that the Prelude provides
function composition via the
(.)
operator.
-- file: ch04/SuffixTree.hs suffixes5 = init . tails
The
(.) operator isn't a
special piece of language syntax; it's just a normal
operator.
ghci>
:type (.)(.) :: (b -> c) -> (a -> b) -> a -> c
ghci>
:type suffixessuffixes :: [a] -> [[a]]
ghci>
:type suffixes5suffixes5 :: [a] -> [[a]]
ghci>
suffixes5 "foo"["foo","oo","o"]
We can create new functions at any time by writing
chains of composed functions, stitched together with
(.), so long (of course) as the result type
of the function on the right of each
(.)
matches the type of parameter that the function on the left can
accept.
As an example, let's solve a simple puzzle: counting the number of words in a string that begin with a capital letter.
ghci>
:module +Data.Char
ghci>
let capCount = length . filter (isUpper . head) . words
ghci>
capCount "Hello there, Mom!"2
We can understand what this composed function does by
examining its pieces. The
(.) function is
right associative, so we will proceed from right to left.
ghci>
:type wordswords :: String -> [String]
The
words function has a result type of
[String], so whatever is on the left side of
(.) must accept a compatible
argument.
ghci>
:type isUpper . headisUpper . head :: [Char] -> Bool
This function returns
True if a word begins
with a capital letter (try it in ghci), so
filter
(isUpper . head) returns a list of Strings
containing only words that begin with capital letters.
ghci>
:type filter (isUpper . head)filter (isUpper . head) :: [[Char]] -> [[Char]]
Since this expression returns a list, all that remains is calculate the length of the list, which we do with another composition.
Here's another example, drawn from a real
application. We want to extract a list of macro names from a C
header file shipped with
libpcap, a popular network
packet filtering library. The header file contains a large
number definitions of the following form.
#define DLT_EN10MB 1 /* Ethernet (10Mb) */ #define DLT_EN3MB 2 /* Experimental Ethernet (3Mb) */ #define DLT_AX25 3 /* Amateur Radio AX.25 */
Our goal is to extract names such as
DLT_EN10MB
and
DLT_AX25.
-- file: ch04/dlts.hs import Data.List (isPrefixOf) dlts :: String -> [String] dlts = foldr step [] . lines
We treat an entire file as a string, split it up
with
lines, then apply
foldr step
[] to the resulting list of lines. The
step helper function operates on a single
line.
-- file: ch04/dlts.hs where step l ds | "#define DLT_" `isPrefixOf` l = secondWord l : ds | otherwise = ds secondWord = head . tail . words
If we match a macro definition with our guard expression, we cons the name of the macro onto the head of the list we're returning; otherwise, we leave the list untouched.
While the individual functions in the body of
secondWord are by now familiar to us, it
can take a little practice to piece together a chain of
compositions like this. Let's walk through the
procedure.
Once again, we proceed from right to left. The
first function is
words.
ghci>
:type wordswords :: String -> [String]
ghci>
words "#define DLT_CHAOS 5"["#define","DLT_CHAOS","5"]
We then apply
tail to the result of
words.
ghci>
:type tailtail :: [a] -> [a]
ghci>
tail ["#define","DLT_CHAOS","5"]["DLT_CHAOS","5"]
ghci>
:type tail . wordstail . words :: String -> [String]
ghci>
(tail . words) "#define DLT_CHAOS 5"["DLT_CHAOS","5"]
Finally, applying
head to the
result of
drop 1 . words will give us the name of
our macro.
ghci>
:type head . tail . wordshead . tail . words :: String -> String
ghci>
(head . tail . words) "#define DLT_CHAOS 5""DLT_CHAOS"
After warning against unsafe list functions in
the section called “Safely and sanely working with crashy functions”, here we are calling both
head and
tail, two
of those unsafe list functions. What gives?
In this case, we can assure ourselves by
inspection that we're safe from a runtime failure. The
pattern guard in the definition of
step
contains two words, so when we apply
words to any string that makes it past
the guard, we'll have a list of at least two elements,
"#define" and some macro beginning with
"DLT_".
This the kind of reasoning we ought to do to convince ourselves that our code won't explode when we call partial functions. Don't forget our earlier admonition: calling unsafe functions like this requires care, and can often make our code more fragile in subtle ways. If we for some reason modified the pattern guard to only contain one word, we could expose ourselves to the possibility of a crash, as the body of the function assumes that it will receive two words.
So far in this chapter, we've come across two tempting looking features of Haskell: tail recursion and anonymous functions. As nice as these are, we don't often want to use them.
Many list manipulation operations can be most
easily expressed using combinations of library functions such as
map,
take, and
filter. Without a doubt, it takes some
practice to get used to using these. In return for our initial
investment, we can write and read code more quickly, and with
fewer bugs.
The reason for this is simple. A tail recursive
function definition has the same problem as a loop in an
imperative language: it's completely general. It might perform
some filtering, some mapping, or who knows what else. We are
forced to look in detail at the entire definition of the it
behaves more regularly and predictably than a tail recursive
function. As a general rule, don't use a fold if you can
compose some library functions, but otherwise try to use a fold
in preference to a hand-rolled a tail recursive loop. don't need to
understand the function's definition when we're reading the code
that uses it; and a well chosen function name acts as a tiny
piece of local documentation.
The
foldl function that we discussed
earlier is not the only place where space leaks can arise in
Haskell code. We will use it to illustrate how non-strict
evaluation can sometimes be problematic, and how to solve the
difficulties that can arise.
We refer to an expression that is not evaluated lazily as
strict, so
foldl' is
a strict left fold. It bypasses Haskell's usual non-strict
evaluation through the use of a special function named
seq.
-- file: ch04/Fold.hs foldl' _ zero [] = zero foldl' step zero (x:xs) = let new = step zero x in new `seq` foldl' step new xs
This
seq function has a peculiar
type, hinting that it is not playing by the usual
rules.
ghci>
:type seqseq :: a -> t -> t
It operates as follows: when a
seq
expression is evaluated, it forces its first argument to be
evaluated, then returns its second argument. It doesn't
actually do anything with the first argument:
seq exists solely as a way to force that
value to be evaluated. Let's walk through a brief application
to see what happens.
-- file: ch04/Fold.hs foldl' (+) 1 (2:[])
-- file: ch04/Fold.hs let new = 1 + 2 in new `seq` foldl' (+) new []
The use of
seq forcibly evaluates
new to
3, and returns its
second argument.
-- file: ch04/Fold.hs foldl' (+) 3 []
We end up with the following result.
-- file: ch04/Fold.hs 3
Thanks to
seq, there are no thunks in
sight.
Without some direction, there is an element of mystery
to using
seq effectively.
Here are some useful rules for using it well.
To have any effect, a
seq
expression must be the first thing evaluated in an
expression.
To strictly evaluate several values, chain
applications of
seq together.
-- file: ch04/Fold.hs chained x y z = x `seq` y `seq` someFunc z
A common mistake is to try to use
seq
with two unrelated expressions.
-- file: ch04/Fold.hs badExpression step zero (x:xs) = seq (step zero x) (badExpression step (step zero x) xs)
Here, the apparent intention is to evaluate
step
zero x strictly. Since the expression is duplicated
in the body of the function, strictly evaluating the first
instance of it will have no effect on the second. The use of
let from the definition of
foldl' above
shows how to achieve this effect correctly.
When evaluating an expression,
seq
stops as soon as it reaches a constructor. For simple types
like numbers, this means that it will evaluate them
completely. Algebraic data types are a different story.
Consider the value
(1+2):(3+4):[]. If we apply
seq to this, it will evaluate the
(1+2) thunk. Since it will stop when it reaches
the first
(:) constructor, it will have no effect
on the second thunk. The same is true for tuples:
seq
((1+2),(3+4)) True will do nothing to the thunks
inside the pair, since it immediately hits the pair's
constructor.
If necessary, we can use normal functional programming techniques to work around these limitations.
-- file: ch04/Fold.hs strictPair (a,b) = a `seq` b `seq` (a,b) strictList (x:xs) = x `seq` x : strictList xs strictList [] = []
It is important to understand that
seq isn't free: it has to perform a check
at runtime to see if an expression has been evaluated. Use it
sparingly. For instance, while our
strictPair function evaluates the
contents of a pair up to the first constructor, it adds the
overheads of pattern matching, two applications of
seq, and the construction of a new tuple.
If we were to measure its performance in the inner loop of a
benchmark, we might find it to slow the program down.
Aside from its performance cost if overused,
seq is not a miracle cure-all for memory
consumption problems. Just because you
can evaluate something strictly doesn't
mean you should. Careless use of
seq may do nothing at all; move existing
space leaks around; or introduce new leaks.
The best guides to whether
seq is
necessary, and how well it is working, are performance
measurement and profiling, which we will cover in Chapter 25, Profiling and optimization. From a base of empirical
measurement, you will develop a reliable sense of when
seq is most useful.
|
http://book.realworldhaskell.org/read/functional-programming.html
|
CC-MAIN-2017-26
|
refinedweb
| 9,768
| 69.52
|
The repackaging worked.
In addition to a new deployment plan I needed to repackage the app that used to work on 1.0.
Any
updates to the classloader?
Thank you all for the help
Cheers!
Hernan
Sachin Patel wrote:
> Is the .war you attached the exact archive you're deploying? If so, as
> Jason mentioned, you problem is with your archive and how you jarred it
> up. The "HelloWorld" directory should not be included, and WEB-INF
> should be at the root of the archive.
>
> -sachin
>
> On May 30, 2006, at 7:34 PM, Hernan Cunico wrote:
>
>> I zipped the directory HelloWorld containing the WEB-INF and the jsp.
>> If I deploy it to G1.0 with the old dep plan it works, same thing in
>> G1.1 (dep plan updated) fails to deploy.
>>
>> This issue has to be something so simple that we don't see it, at
>> least I don't see it :)
>>
>> Cheers!
>> Hernan
>>
>> Jason Dillon wrote:
>>
>>> Is this the exact structure of the war? I'd expect WEB-INF to be
>>> top-level:
>>> HelloWorld.war
>>> HelloWorld\HelloWorld.jsp
>>> WEB-INF\web.xml
>>> --jason
>>> On 5/30/06, Hernan Cunico <hcunico@gmail.com> wrote:
>>>
>>>> it is there! I just double-checked the .war
>>>>
>>>> HelloWorld.war
>>>> HelloWorld\HelloWorld.jsp
>>>> HelloWorld\WEB-INF\web.xml
>>>>
>>>> maybe an issue extracting the war?
>>>>
>>>> Cheers!
>>>> Hernan
>>>>
>>>> Aaron Mulder wrote:
>>>> > Oh. You don't have a WEB-INF/web.xml in the WAR.
>>>> >
>>>> > Aaron
>>>> >
>>>> > On 5/30/06, Hernan Cunico <hcunico@gmail.com> wrote:
>>>> >
>>>> >> I'm using Geronimo/Tomcat. I just tested it with web-1.1 and
>>>> have the
>>>> >> same error.
>>>> >>
>>>> >> Cheers!
>>>> >> Hernan
>>>> >>
>>>> >> Aaron Mulder wrote:
>>>> >> > I haven't tried the Tomcat/Jetty namespaces. Are you using
>>>> >> > Geronimo/Tomcat not Geronimo/Jetty? Does it work if you use
the
>>>> >> > web-1.1 namespace?
>>>> >> >
>>>> >> > Thanks,
>>>> >> > Aaron
>>>> >> >
>>>> >> > On 5/30/06, Hernan Cunico <hcunico@gmail.com> wrote:
>>>> >> >
>>>> >> >> Hi All,
>>>> >> >> I am trying to deploy, should I say migrate?, an extremely
>>>> basic web
>>>> >> >> app (HelloWorld) from Geronimo
>>>> >> >> v1.0 to v1.1. I updated the deployment plan to reflect
the
>>>> latest
>>>> >> >> changes but the deployer tool
>>>> >> >> fails to deploy.
>>>> >> >>
>>>> >> >> Command I used:
>>>> >> >> java -jar deployer.jar --user system --password manager
deploy
>>>> >> >> \HelloWorld\HelloWorld.war
>>>> >> >> \HelloWorld\geronimo-web.xml
>>>> >> >>
>>>> >> >> Error received:
>>>> >> >> Error: Unable to distribute HelloWorld.war:=E:\HelloWorld\geronimo-web.xml,
>>>> >> >>
>>>> >> moduleFile=E:\geronimo-1.1\var\temp\geronimo-
>>>> deployer2691.tmpdir\HelloWorld.war)
>>>> >>
>>>> >> >>
>>>> >> >>
>>>> >> >> Deployment plan geronimo-web.xml:
>>>> >> >> <?xml version="1.0" encoding="UTF-8"?>
>>>> >> >> <web-app
>>>> >>
>>>> >> >> <dep:environment
>>>> >> >> xmlns:
>>>> >> >> <dep:moduleId>
>>>> >> >> <dep:groupId>geronimo</dep:groupId>
>>>> >> >> <dep:artifactId>HelloWorld</dep:artifactId>
>>>> >> >> <dep:version>1.1</dep:version>
>>>> >> >> <dep:type>war</dep:type>
>>>> >> >> </dep:moduleId>
>>>> >> >> </dep:environment>
>>>> >> >> <context-root>/hello</context-root>
>>>> >> >> </web-app>
>>>> >> >>
>>>> >> >> The .war contains the JSP and WEB-INF\web.xml which, just
in
>>>> case, I
>>>> >> >> am attaching too. The build I'm
>>>> >> >> using is from last Friday.
>>>> >> >>
>>>> >> >> Any idea what am I missing?
>>>> >> >>
>>>> >> >> Thanks in advance
>>>> >> >>
>>>> >> >> Cheers!
>>>> >> >> Hernan
>>>> >> >>
>>>> >> >>
>>>> >> >>
>>>> >> >
>>>> >>
>>>> >
>>>>
>
>
> -sachin
>
>
>
|
http://mail-archives.apache.org/mod_mbox/geronimo-dev/200605.mbox/%3C447CE5D1.9060501@gmail.com%3E
|
CC-MAIN-2014-23
|
refinedweb
| 488
| 54.59
|
I have custom authentication and user profiles solution where user profiles are stored in list. This list is directly accessible only to administrators. Users can register to site and modify their profiles through special pages that run profile operations under elevated privileges. Users have three versions of their avatar: 64x64, 32x32 and 16x16. These avatars are saved as user profile attachments when user uploads his or her avatar. Because avatars are used at almost every page in portal I wrote IHttpHandler that provides avatars based on user profile ID.
Here is shortened draft version of my code (I removed some complex guard checks that use custom extensions methods for SharePoint objects).
public class ProfileImageHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
var request = context.Request;
var response = context.Response;
var idString = request.QueryString["id"];
var sizeString = request.QueryString["size"];
var id = 0;
int.TryParse(idString, out id);
var siteId = SPContext.Current.Site.ID;
var sec = new SPSecurity.CodeToRunElevated(delegate()
{
using (var site = new SPSite(siteId))
{
using (var web = site.OpenWeb())
{
if (id == 0)
{
OutputDefaultImage(web, response);
response.End();
return;
}
var list = web.Lists["ProfileList"];
var item = list.GetItemById(id);
sizeString = sizeString + "x" + sizeString;
foreach (string fileName in item.Attachments)
if (!fileName.Contains(sizeString))
continue;
var fileUrl = item.Attachments.UrlPrefix + fileName;
var file = web.GetFile(fileUrl);
var stream = file.OpenBinaryStream();
var bytes = new byte[stream.Length];
stream.Read(bytes, 0, bytes.Length);
response.Clear();
response.ContentType = "image/png";
response.BinaryWrite(bytes);
stream.Dispose();
}
}
}
);
SPSecurity.RunWithElevatedPrivileges(sec);
private void OutputDefaultImage(SPWeb web, HttpResponse response)
var defaultFileUrl = "/Style Library/portal/images/user.gif";
var defaultFile = web.GetFile(defaultFileUrl);
var defaultFileStream = defaultFile.OpenBinaryStream();
var defaultBytes = new byte[defaultFileStream.Length];
defaultFileStream.Read(defaultBytes, 0, defaultBytes.Length);
response.Clear();
response.ContentType = "image/png";
response.BinaryWrite(defaultBytes);
defaultFileStream.Dispose();
}
The code here works as follows. It retrieves user profile by id and checks if profile has image with given width and height. Avatars in this system are squares so I need to know only size of one side. If user profile doesn’t have attachment that contains size x size (by example “32x32”) in its name then default profile image is returned.
Let’s suppose we have user profile (id = 176) and we want 32x32 size avatar for this profile. Also let’s assume there is userimagehandler.ashx file in the folder portalhandlers. We can ask 32x32 avatar by using the following request.
/_layouts/portalhandlers/userimagehandler.ashx?size=32&id=176
/_layouts/portalhandlers/userimagehandler.ashx?size=32&id=176
As URL for each avatar size is unique for each profile then it is also possible to cache avatars so there is no need to read them from content database per every request.
Pingback from SharePoint: Creating HttpHandler for user profile images | ASP Scribe
I would strongly consider adding some 304 plumbing so the images are cached in the browser...
weblogs.asp.net/.../304-your-images-from-a-database.aspx
Pingback from Links (7/23/2009) « Steve Pietrek – Everything SharePoint
Thank you for good suggestion, Je
Dziękujemy za publikację - Trackback z dotnetomaniak.pl
You are voted (great) - Trackback from WebDevVote.com
Top This Week ()()()() SharePoint's Branding Limitations, Part 1 SharePoint Magazine
Thank you for submitting this cool story - Trackback from Fairfeeds.com
Hi,
Thanks for your useful article!
I also use httphandler for displaying images in my program. One image can be displayed. But when there are multiple images, only one displays; the cross sign displays instead of others. However, after right clicking on the cross and choose display image, it becomes visible.
More details...
My program is a personel search web part and it gets personel images from db and displays on personel user control. The control uses HttpHandler for image source.
But as I have said, when multiple images are wanted to listed, there is the above problem.
Any idea?
Thanks.
Open the URL of image that is not shown in your browser and see what is the error you get. You may also check errors out from SharePoint logs.
Hi
I have a HTTPHandler where the "SPContext" is NOT available.
Any ideas or guidlines on how to get access to SPContext from HTTPHandler?
Thanks
Karina
Thanks for question, Karina!
Is your application usual ASP.NET web application or is it SharePoint application?
Hi! :-)
It is a SharePoint webPart.
(The Call to HTTPHandler are from a WebUserControl used in the Wep Part.)
Okay, can you show me the definition of your HTTP handler?
public class MyHandler : ???? <- what you have here?
|
http://weblogs.asp.net/gunnarpeipman/archive/2009/07/23/sharepoint-creating-httphandler-for-user-profile-images.aspx?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+gunnarpeipman+%28Gunnar+Peipman%27s+ASP.NET+blog%29
|
crawl-003
|
refinedweb
| 750
| 52.66
|
Connect a bot to Slack
APPLIES TO: SDK v4
This article shows how to add a Slack channel to a bot using one the following approaches:
- Create a Slack application using the Azure portal. It describes how to connect your bot to Slack using the Azure portal.
- Create a Slack application using the Slack adapter. It describes how to connect your bot to Slack using the adapter.
Create a Slack application using the Azure portal
Prerequisites
A bot deployed to Azure. Refer to Create a bot with the Bot Framework SDK and Deploy a basic bot.
Access to a Slack workspace with sufficient permissions to create and manage applications at. If you do not have access to a Slack environment you can create a workspace.
Create a Slack application.
Select Create App.
Add a new redirect URL
In the left pane, select OAuth & Permissions.
In the right pane, select Add a new Redirect URL.
In the input box, enter.
Select Add.
Select Save URLs.
Follow these steps to subscribe to six specific bot events. By subscribing to bot events, your app will be notified of user activities at the URL you specify.
In the left pane, select Event Subscriptions.
In the right pane, set Enable Events to On.
In Request URL, enter{YourBotHandle}, where
{YourBotHandle}is your bot handle, without the braces. This handle is the name you specified when deploying the bot to Azure. You can find it by going to the Azure portal.
In Subscribe to Bot Events, click Add Bot User Event.
In the list of events, select these six event types:
member_joined_channel
member_left_channel
message.channels
message.groups
message.im
message.mpim
Select Save Changes.
As you add events in Slack, it lists the scopes you need to request. The scopes you need will depend on the events you subscribe to and how you intend to respond to them. For Slack supported scopes, refer to Scopes and permissions. See also Understanding OAuth scopes for Bots.
Note
As of June 2020 Slack channel supports Slack V2 permission scopes which allow the bot to specify its capabilities and permissions in a more granular way. All newly configured Slack channels will use the V2 scopes. To switch your bot to the V2 scopes, delete and recreate the Slack channel configuration in the Azure portal Channels blade.
Enable sending messages to the bot by the users
In the left pane, select App Home.
In the right pane, in the Show Tabs section under the Messages Tab, check Allow users to send Slash commands and messages from the messages tab.
Add and configure interactive messages (optional)
- In the left pane, select Interactivity & Shortcuts.
- In the right pane, enter the Request URL.
- Select Save changes.
Configure your bot Slack channel
Two steps are rquired to configure your bot Slack channel. First you gather the Slack application credentials, then you use these credenatials to configure the Slcak channel in Azure.
Gather Slack app credentials
In the left pane, select Basic Information.
In the right pane, scroll to the App Credentials section. The Client ID, Client Secret, and Signing Secret required for configuring your Slack bot channel are displayed. Copy and store these credentials in a safe place.
Configure Slack channel in Azure
Select your Azure bot resource in the Azure portal.
In the left panel, select Channels,
In the right panel, select the Slack icon.
Paste the Slack app credentials you saved in the previous steps into the appropriate fields.
The Landing Page URL is optional. You may omit or change it.
Select Save. Follow the instructions to authorize your Slack app's access to your Development Slack Team.
On the Configure Slack page, confirm that the slider by the Save button is set to Enabled. Your bot is now configured to communicate with the users in Slack.
Create the steps below to get the replacement URL.
- Go to the Azure portal.
- Select your Azure bot resource.
- In the left pane, select Channels.
- In the right pane, right-click on the Slack channel name.
- In the drop-down menu, select Copy link.
- Paste this URL from your clipboard into the HTML provided for the Slack button.
Authorized users can click the Add to Slack button provided by this modified HTML to reach your bot on Slack.
Note
The link you pasted into the href value of the HTML contains scopes that can be refined as needed. See Scopes and permissions for the full list of available scopes.
Create a Slack application using the Slack adapter
As well as the channel available in the Azure Bot Service to connect your bot with Slack, you can also use the Slack adapter. In this article you will learn how to connect a bot to Slack using the adapter. This article will walk you through modifying the EchoBot sample to connect it to a Slack app.
Note
The instructions below cover the C# implementation of the Slack adapter. For instructions on using the JS adapter, part of the BotKit libraries, see the BotKit Slack documentation.
Adapter prerequisites
- The EchoBot C# sample code. You can use the sample slack adapter as an alternative to the modification of the echo bot sample, shown in the section Wiring up the Slack adapter in your bot.
- Access to a Slack workspace with sufficient permissions to create and manage applications at. If you do not have access to a Slack environment you can create a workspace for free.
Create a Slack application when using the adapter.
Gather required configuration settings for your bot
Once your app is created, collect the following information. You will need this to connect your bot to Slack.
In the left pane, select Basic Information.
In the right pane, scroll to the App Credentials section. The Verification Token, Client Secret, and Signing Secret required for configuring your Slack bot channel are displayed. Copy and store these credentials in a safe place.
Navigate to the Install App page under the Settings menu and follow the instructions to install your app into a Slack team. Once installed, copy the Bot User OAuth Access Token and, again, keep this for later to configure your bot settings.
Wiring up the Slack adapter in your bot
If you use the sample slack adapter, as an alternative to the modification of the echo bot sample, go directly to Complete configuration of your Slack app.
Install the Slack adapter NuGet package
Add the Microsoft.Bot.Builder.Adapters.Slack NuGet package. For more information on using NuGet, see Install and manage packages in Visual Studio
Create a Slack adapter class
Create a new class that inherits from the SlackAdapter class. This class will act as our adapter for the Slack channel and include error handling capabilities (similar to the BotFrameworkAdapterWithErrorHandler class already in the sample, used for handling other requests from Azure Bot Service).
public class SlackAdapterWithErrorHandler : SlackAdapter { public Slack Slack requests
We create a new controller which will handle requests from your slack app, on a new endpoint
api/slack instead of the default
api/messages used for requests from Azure Bot Service Channels. By adding an additional endpoint to your bot, you can accept requests from Bot Service channels, as well as from Slack, using the same bot.
[Route("api/slack")] [ApiController] public class SlackController : ControllerBase { private readonly SlackAdapter _adapter; private readonly IBot _bot; public SlackController(SlackAdapter adapter, IBot bot) { _adapter = adapter; _bot = bot; } [HttpPost] [HttpGet] public async Task PostAsync() { // Delegate the processing of the HTTP POST to the adapter. // The adapter will invoke the bot. await _adapter.ProcessAsync(Request, Response, _bot); } }
Add Slack app settings to your bot's configuration file
Add the 3 settings shown below to your appSettings.json file in your bot project, populating each one with the values gathered earlier when creating your Slack app.
"SlackVerificationToken": "", "SlackBotToken": "", "SlackClientSigningSecret": ""
Inject the Slack adapter In your bot startup.cs
Add the following line to the ConfigureServices method within your startup.cs file. This will register your Slack adapter and make it available for your new controller class. The configuration settings you added in the previous step will be automatically used by the adapter.
services.AddSingleton<SlackAdapter, SlackAdapterWithErrorHandler>();
Once added, your ConfigureServices method should Slack Adapter services.AddSingleton<SlackAdapter, SlackAdapterWithErrorHandler>(); // Create the bot as a transient. In this case the ASP Controller is expecting an IBot. services.AddTransient<IBot, EchoBot>(); }
Complete configuration of your Slack app
Obtain a URL for your bot
This section shows how to point your Slack app to the correct endpoint on your bot and how to subscribe the app to bot events to ensure your bot receives the related messages. To do this your bot must be running, so that Slack can verify the endpoint is valid. Also, for testing purposes, this section assumes that the bot is running locally on your machine and your Slack app communicates with it using ngrok.
Note
If you are not ready to deploy your bot to Azure, or wish to debug your bot when using the Slack command assumes your local bot is running on port 3978, otherwise change the port number to the correct value.
ngrok.exe http 3978 -host-header="localhost:3978"
Update your Slack app
Navigate back to the Slack API dashboard and select your app. You now need to configure 2 URLs for your app and subscribe to the appropriate events.
In the left pane, select OAuth & Permissions. In the right pane, enter the Redirect URL vlaue. It is your bot's URL, plus the
api/slackendpoint you specified in your newly created controller. For example,.
In the left pane, select Subscribe to Bot Events. In the right pane, enable events using the toggle at the top of the page. Then fill in the Request URL with the same URL you used in step 1.
Select Subsribe to bot events. Select Add Bot User Event. In the list of events, select these six event types:
member_joined_channel
member_left_channel
message.channels
message.groups
message.im
message.mpim
Select Save Changes.
Enable sending messages to the bot by the users
In the left pane, select App Home.
In the right pane, in the Show Tabs section under the Messages Tab, check Allow users to send Slash commands and messages from the messages tab.
Test your application in Slack
Log in the Slack work space where you installed your app (
http://<your work space>-group.slack.com/). You will see it listed under the Apps section in the left panel.
In the left panel, select your app.
In the right panel, write e message and send it to the application. If you used an echo bot, the application echoes back the message as shown in the figure below.
You can also test this feature using the sample bot for the Slack adapter by populating the appSettings.json file with the same values described in the steps above. This sample has additional steps described in the
README file to show examples of link sharing, receiving attachments, and sending interactive messages.
|
https://docs.microsoft.com/en-us/azure/bot-service/bot-service-channel-connect-slack?view=azure-bot-service-4.0
|
CC-MAIN-2021-43
|
refinedweb
| 1,828
| 65.12
|
Day of the Week
Dear DDJ,
Kim Larsen's article "Computing the Day of the Week" (DDJ, April 1995) is a good example of how a simple equation can sometimes replace tedious programming logic. This technique could be used in other applications to reduce code size and increase speed whenever a mathematical formula fits the problem better than a step-by-step algorithm. I especially appreciated Larsen's description of how this particular formula was developed.
Larsen made no mention of Zeller's Congruence. Zeller's Congruence is another formula for calculating the day of the week. It was published in 1887 by the German mathematician Zeller. Jeff Duntemann discussed Zeller's Congruence in issue #169 of DDJ, with some follow-up information in issues 170 and 171.
Like Larsen, Zeller reckoned January and February as the 13th and 14th months of the previous year. However, he then divided the year into two components: the century (C=Y/100) and the year within the century (Y mod 100). He probably did this to keep all the numbers small (they didn't have ten-digit calculators back then). After calculating C as Y/100 and adjusting Y to Y%100, Zeller's Congruence can be expressed as: A=(D+(M+1)*26/10+Y+Y/4--2*C+C/4)%7.
As with Larsen's formula, all divisions are integer divisions (rounding down). Note that the fraction 26/10 can be reduced to the equivalent 13/5. Zeller probably used 26/10 because it's very easy to divide by 10 when doing arithmetic by hand. One potential pitfall when implementing Zeller's Congruence is that the sum of the individual terms can sometimes be negative. For example, this occurs with the date 1 March 2000 (D=1, M=3, C=20, Y=0).
The formula should work even if the sum is negative, but some compilers give an unexpected result when a negative number is used with the modulo operator. This situation can be easily avoided by replacing the term --2*C with +5*C (to make all the terms positive). Since --2*C and +5*C differ by an exact multiple of 7, this change won't affect the final result modulo 7. These adjustments change the formula to: A=(D+(M+1)*13/5+Y+Y/4+5*C+C/4)%7.
Larsen's formula is virtually identical to Zeller's. Note that the value of Y in Larsen's formula is actually equal to 100*C+Y in Zeller's nomenclature. Making this substitution in Larsen's Y+Y/4--Y/100+Y/400 yields 100*C+Y+25*C+Y/4 --C+C/4. A little massaging will show that this differs from Zeller's Y+Y/4 --2*C+C/4 by 126*C. Since 126*C is a multiple of 7, this difference has no effect on the final result. Likewise, one can show that Larsen's 2*M+3*(M+1)/5 differs from Zeller's (M+1)*26/10 by a constant value of --2. This means that Zeller's Congruence will return 0 for Saturday and 6 for Friday, whereas Larsen's formula uses 0 for Monday and 6 for Sunday. Either formula can be adjusted to start on any day of the week by adding an appropriate constant offset before calculating the result modulo 7.
Larsen's detailed article gives valuable insight into the logic that Zeller must have used when devising his congruence. The description of the inner workings of Larsen's formula is much clearer than the explanations of Zeller's Congruence that I've seen elsewhere. Keep up the good work.
Rod Spade
Lancaster, Pennsylvania
Dear DDJ,
I enjoyed Kim S. Larsen's article because I have been playing with the subject too. I managed to stuff all computation into a single line of code (dayofweek1), which was then improved even further (dayofweek2) by a friend (Hendrik Jan Veenstra). The formulas presented in Example 1 use a table different from the one in the article for adjustment of the correct day.
Frank Bemelman
KNARF@NETLAND.NL
Dear DDJ,
After reading Kim Larsen's "Computing the Day of the Week," I thought you might be interested in the Day-of-the-Week C macro in Example 2. It returns from 0 (=Monday) to 6 (=Sunday). For reasonable input values, it works with 16-bit ints with no risk for overflow. And the y,m,d are real year, month, day values, not "adjusted" ones: January is m=1, February M=2, March M=3, and so on.
Paul Schlyter
Stockholm, Sweden
pausch@saaf.se
Dear DDJ,
The article "Computing the Day of the Week," by Kim S. Larsen, was a fine one. However, I'd like to add a few related observations.
Larsen's statement that "We switched to the current calendar system on Thursday, September 14, 1752" is true in a sense. But the switch was made in European Catholic countries much earlier (in 1582), and in Russia and Greece much later (around 1917)! The "October Revolution" was in November by Gregorian reckoning!
In UNIX, if you enter CAL 9 1752, you get a hybrid calendar; the first two days are Julian, and the rest of the month is Gregorian. The first week of that UNIX display looks like this: 1 2 14 15 16. A clever bit of programming, but be aware of what it means! One thing it means is that UNIX would be wrong in France, Russia, and many other places around the world!
When talking about any particular calendar (Julian, Gregorian, or other), it is helpful to think of it simply as an algorithm in its own right, independent of any concept of time--like a recipe for brownies. In this sense, a calendar does not change, nor does it have a beginning or an end. Only our application of it changes as time goes by.
In this way we should have no difficulty extrapolating any particular calendar algorithm to any year we please. Pope Gregory 13 insisted that his calendar (the one we use now) be phased relative to the Old Style Julian to match up in March 21 ad 325, so it makes sense to use it for reporting historical, as well as future dates from ad 1 until ad 3000 (when it loses accuracy) even if the people in the past didn't. (We can be pretty sure that Julius Caesar never had a calendar on his wall that said "50 bc:" Even so, we can quite reasonably say that he lived from 100--44 bc!)
Thus, even though the Gregorian calendar was not used in America prior to 1752, George Washington wisely reckoned his birthday in terms of it, as we continue to do today. He was born 20 years earlier in Westmoreland County, Virginia. Another thing: The 500th anniversary of Columbus's discovery of America was October 21, 1492 Gregorian--not the 12th. That, is if we can agree that "500 years" means 500 complete revolutions of the Earth about the Sun, without regard for what calendar Columbus might have been using at the time! At least the day of the week is the same; that original Columbus day being a Friday whether you talk Julian or Gregorian.
And when the astronomer says that his "Julian Day" (a different Julius!) relates back to January 1, 4713 bc, he doesn't tell us what calendar he's talking about! What's Latin for "Confusion reigns," anyway?
I also found it interesting to compare Larsen's algorithm with my own. In the October 1989 issue of PC Resource magazine, my short Basic program appeared containing this "Gregorian algorithm" for the day o'week: (Y+Y\4-- Y\100+Y\400+2.6*M+1.2+M)Mod 7. For January or February, use M=13 or 14 of the previous year. In my algorithm, I chose day 0 to be Sunday, not Monday, for a couple of reasons: First, that makes "2'sday" become "Tuesday;" an extremely useful mnemonic. Second, the astronomical symbol for the Sun is 0 (a circle).
With Microsoft GWBASIC 3.22 or other redirectable Basic on path, the next command, when invoked at the DOS prompt, will show the complete calendar for any month and ad year you type in the M=7:Y=1776:N=31 preamble. This command squawks if you try to use M=1 or M=2. Don't use any spaces not shown or it won't fit on the command line: ECHO M=7:Y=1776:N=31:Q=SQR(M--3):FOR J=1TO N:D=(Y+Y\4--Y\100+Y\400+2.6*M+1.2)MOD 7+J:LOCATE D\7+6,3*(D MOD 7)+3:?J:NEXT|GWBASIC.
Homer B. Tilton
Tucson, Arizona
Fortran Tools
Dear DDJ,
As leaders in the numerical computing industry, Cray Research appreciates the focus that your magazine brought to this important topic in the January 1995 DDJ "Tools that Count" issue. In the "Examining Room," Steven Baker reviewed several Fortran 90 compilers and test suites. As the producer of one of the test suites and compilers, we would like clarify a few points as they relate to our products.
Baker writes that "_the Cray, (and others)_compilers failed to recognize and report the obsolete features as required by the Fortran standard." There is a command-line option which will enable the generation of messages to note all nonstandard usage, including obsolete features. This option is off by default and would have to be specifically enabled to generate the report.
In Baker's "Other Considerations," it appears that the CraySoft compiler was dropped from consideration, leaving the implication that it does not come with a complete programming environment or supported extensions. In fact, the CraySoft Fortran 90 environment automatically optimizes for parallel processing and includes a parallel debugger, a source-code browser, a parallel performance analyzer, and other development tools; it supports Cray and VAX extensions.
In his Table 1, Baker publishes only the pass rates from selected portions of the various suites, which does not yield an accurate measure of the robustness and quality of the compilers being "evaluated." There was also apparently no analysis of specific failing tests. It is very likely that a single bug or a differing interpretation of the standard could cause multiple failures in a given test suite. Unfortunately, Mr. Baker's own caution about his analysis, that the "_results from these validation suites should be taken with a grain of salt," is not nearly as prominent.
Judy Smith
CraySoft Product Development
Eagan, Minnesota
Net Stuff
Dear DDJ
I think Jonathan Erickson's editorial "The Green, Green Cash of Gnomes" (DDJ, April 1995) was pretty cool, and I just wanted to let you guys know. I've subscribed to DDJ for a couple years now, I guess, and it's one of the few trade magazines I've kept. I've kept it because of honest editorials about the crap that goes on in the industry, as well as the useful technical information. Anyway, like most software engineers, I'm using online resources, particularly the Internet, more and more as part of my job. I cringe whenever I hear someone mention the words "regulation" and "Internet" in the same sentence. Erickson's editorial reminded me that if we sit back and let the government and the marketing bozos overrun the Net, we've only got ourselves to blame through our inaction. So anyway, keep telling it like it is, guys, and we'll keep reading.
Dale M. Davis
Sunnyvale, California
daldavis@spectrace.com
Mechanical Models
Dear DDJ,
Please allow me to poke two-cents' worth at Michael Swaine's "mechanical model" in his "Programming Paradigms" (DDJ, October 1994). Michael asserts: "There's precious little that we might consider the mind capable of doing that we can't convince ourselves that software can also do, in principle."
I'm afraid this is false. My counter-example is this: the invention of natural language. Programs that speak English do exist, but most could be improved. Programs that can learn to speak English are, so far as I know, still glued to the drawing board. Programs that can invent new languages as powerful as English do not exist.
Further, if such program did exist, what would be the guarantee that any human could learn the languages that it "spoke," or even recognize them as languages? If these things could be guaranteed, we would be inclined to ascribe the invention to the programmer(s), not the program.
I could push this argument a good deal further, but that will do for two cents. I hope I have said enough to convince a few people that the equation "mind=software" is a vague analogy which dissolves into large and unsolved problems if you look closely.
Thanks for the stimulus of a magazine that still manages to include technical, philosophical, and commercial information all at once.
I.K. Sayer
Smithton, Tasmania
Australia
Example 1: Day of the week.
#include <stdio.h> #endif /* This table starts on Sunday !!! */ char *name[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", }; void main(void) { int D,M,Y,A; D=3; M=3; Y=1995; printf("formula1, day=%s\n",name[dayofweek1(D, M, Y)]); printf("formula2, day=%s\n",name[dayofweek1(D, M, Y)]); } int dayofweek1(int d, int m, int y) { return(((d+((26*((m<3)?m+13:m+1))/10)+((125*(long)((m<3)?y-1:y))/100) -(((m<3)?y-1:y)/100)+(((m<3)?y-1:y)/400))-1)%7); } int dayofweek2(int d, int m, int y) { return((d+(int)((1040*(long)((m<3)?m+13:m+1))+ (597*(long)((m<3)?y-1:y))/400))%7); }
Example 2: Day-of-the-week C macro.
/* Day-Of-Week macro for international Monday-Sunday calendars */ #define dow(y,m,d) \ ( ( ( 3*(y) - (7*((y)+((m)+9)/12))/4 + (23*(m))/9 + (d) + 2 \ + (((y)-((m)<3))/100+1) * 3 / 4 - 16 ) % 7 ) )
|
http://www.drdobbs.com/letters/184409582
|
CC-MAIN-2015-27
|
refinedweb
| 2,352
| 61.56
|
Introduction to AI for Ionic developers
Artificial Intelligence is here and will gradually replace some jobs.
Thanks to the open-source community, there are great libraries that can kickstart our AI projects.
This tutorial is an introduction to AI usage in Ionic applications.
In the previous tutorials (here and there), we used the Dialogflow service to create an AI chatbot.
That was quite easy, however, we only focused on a tiny aspect of AI. This technology has an incommensurable scope for the ones that want to master it.
We will start today's tutorial with THE classical XOR example then create a new AI for an Ionic mobile application.
The codeless XOR
To put it simply, an AI is a baby with a very very very big processing power.
You teach it, it learns. If you teach it crap, it will do crap.
Remember HAL from "A Space Odyssey"?
In this tutorial, we are going to use the brain.js library to create our baby.
It's one of the best and simplest library. The project is at the moment unmaintained. If you want a maintained one, you can use Synaptic (we will use this one in the next AI tutorial), the syntax is quite similar so you won't be lost.
As usual we create the Ionic project and install the libraries:
ionic start ionic-ai-intro blank npm i --save brain
Moving on to the home.ts file:
import { Component } from "@angular/core"; declare var require; var brain = require("brain"); @Component({ selector: "page-home", templateUrl: "home.html" }) export class HomePage { net; constructor() { this.trainXOR(); } }
We first grab the brain library by using the require keyword.
A net property is then created for later use. In the constructor we call the trainXOR method, which starts like this:
trainXOR() { this.net = new brain.NeuralNetwork(); const data = [ { input: [0,0], output:[0]}, { input: [0,1], output:[1]}, { input: [1,0], output:[1]}, { input: [1,1], output:[0]} ]; ... }
A new NeuralNetwork is created. Neural Network, brain, that's kinda abstract right?
You can start by viewing a NeuralNetwork as a simple human head instead of a network.
Typically, we, human beings acquire information from some input and sometimes give back an output.
The input can be the eyes (vision), nose (smells), etc. The output can be the mouth (sound).
In our example, the input is an array that contains two elements and the output is an array that contains one element.
In this case we can attribute the input to what two eyes can see and the output to what the mouth has to answer.
The value in the arrays must be between 0 and 1.
If we wanted to use only one element in the input we could use the following system:
We will use those data and parameters to train the AI:
this.net.train(data, { errorThresh: 1, // error threshold to reach iterations: 2, // maximum training iterations log: true, // console.log() progress periodically logPeriod: 1, // number of iterations between logging learningRate: 0.1 // learning rate }); console.log(this.net.run([0, 0])); console.log(this.net.run([0, 1])); console.log(this.net.run([1, 0])); console.log(this.net.run([1, 1]));
Instead of starting with something that works, let's start with a sh*** AI. The AI that will result from this training will be gar****.
An AI training is stopped when a certain number of iterations is reached or once the AI consistently gives us the right answer.
This AI will be trained for only two iterations and the errorThresh property is set to 1 (which means 100%). If the AI makes a mistake or successfully give the right answer, it will stop training.
We now run some simulations:
As we can see, the AI is spitting nonsense.
Now let's give it some proper training:
this.net.train(data, { errorThresh: 0.005, // error threshold to reach iterations: 200000, // maximum training iterations log: true, // console.log() progress periodically logPeriod: 1000, // number of iterations between logging learningRate: 0.1 // learning rate });
The log field is set to show the advancement every 1000 iterations:
As the iterations go on, the AI makes less and less errors. We were going for 200000 iterations, however, it only required 14000 iterations to reach the 0.005 error threshold so it didn't go through the remaining iterations.
The results are correct and our AI is now smart enough to give the result of an XOR operation.
Note that we didn't write any code. Normally we would have to code an algorithm (ex: check if a === b, return 1 or 0, ...). All we did there was repeating to the AI the correct answer (just 14000 times).
We can now move to a more complex case.
The Ionic buttons god
AIs are more than XOR machines. They are generally trained to impact the application's flow.
Most of us don't have a robot to create applications:
So, we are going to create a program that will enable some buttons in our Ionic application according to some checkboxes.
Here are the checkboxes in the home.html file:
<ion-list> <ion-item> <ion-label> Up </ion-label> <ion-checkbox [(ngModel)]="up"></ion-checkbox> </ion-item> <ion-item> <ion-label> Middle </ion-label> <ion-checkbox [(ngModel)]="middle"></ion-checkbox> </ion-item> <ion-item> <ion-label> Down </ion-label> <ion-checkbox [(ngModel)]="down"></ion-checkbox> </ion-item> </ion-list>
And the rest of the template:
<button ion-button (click)="changeButtons(up, middle, down)"> Change buttons </button> <div * <button ion-button [disabled]="!value"></button> </div>
The ngFor will create some buttons. Those buttons will be enabled and disabled by the AI.
When the user will tap the "Change buttons" button, the up, middle and down value will go to our AI and it will decide which button requires activation.
The train method is a bit different:
train() { this.net = new brain.NeuralNetwork();]} ]; }
The input field represents the up, middle and down checkboxes.
The output field represents the buttons to activate or disable.
We make some changes at the beginning of our home.ts file:
export class HomePage { net; output = [true,true,true,true,true]; constructor() { this.train(); } ... }
By default the buttons will be activated and the train method will be called at start up.
We are close to the end, here is the changeButtons method:
changeButtons(up, middle, down) { const input = [down >>> 0 , middle >>> 0 , up >>> 0]; const output = this.net.run(input); this.output = this.formatOutput(output); }
We first convert the checkboxes values (true, false or undefined) to 0 or 1 so our network can understand the information.
An array of floats is then acquired from the AI network.
Those floats will be transformed to booleans thanks to the following method:
formatOutput(output): boolean[] { output.forEach(function(value, i) { output[i] = (Math.round(value) === 1); }); return output; }
Going through each value, they will be rounded to 0 or 1.
And Voila!
We have our Ionic application driven by our AI:
Conclusion
Learning AI programming can seem like an Herculean task, but it shouldn’t.
As usual, we, lucky developers have many great libraries that are ready to be used.
All we need is a generic AI library that can create a network, train it and produce a correct output.
There are many AI libraries out there and more will come in the future. Some of them targets specific problematics (image recognition, natural language), you can find more examples there.
|
https://www.javascripttuts.com/introduction-to-ai-for-ionic-developers/
|
CC-MAIN-2020-50
|
refinedweb
| 1,243
| 57.87
|
14 June 2010 12:19 [Source: ICIS news]
LONDON (ICIS news)--INEOS Bio has been awarded a £7.3m ($10.6m; €8.8m) grant towards £52m in construction costs for ?xml:namespace>
The grant, from the
The 24,000 tonnes/year plant would convert biodegradable household and commercial waste into biofuel and renewable electricity, INEOS Bio added.
“Using our technology, the waste that is collected from homes and offices… can be re-cycled into clean biofuel for cars and renewable electricity for homes and industry,” said Peter Williams, CEO of INEOS Bio.
INEOS Bio uses anaerobic fermentation to convert gases from biomass directly into ethanol and the grant would help bring its technology closer to commercialisation, it said.
The bioethanol plant could be operational by 2012, helping to create 350 construction jobs and over 40 permanent roles, according to INEOS Bio.
The facility would be expanded into a larger integrated biorefinery, to be operational by 2015, it said.
Full planning consent for the plant had been awarded by Stockton Council and so far no objections had been raised against the expanded biorefinery, the company added.
($1 = €0.83; €1 = £0.83)
For more on INEOS visit ICIS company intelligence
For more on ethanol
|
http://www.icis.com/Articles/2010/06/14/9367381/ineos-bio-wins-7.3m-grant-for-bioethanol-from-waste-plant.html
|
CC-MAIN-2015-11
|
refinedweb
| 203
| 51.99
|
The
baseline ping
Description
This ping is intended to provide metrics that are managed by the Glean SDK itself, and not explicitly set by the application or included in the application's
metrics.yaml file.
Note: As the
baselineping was specifically designed for mobile operating systems, it is not sent when using the Glean Python bindings.
Scheduling
The
baseline ping is automatically submitted with a
reason: foreground when the application is moved to the foreground. These baseline pings do not contain
duration.
The
baseline ping is automatically submitted with a
reason: background when the application is moved to the background.
Occasionally, the
baseline ping may fail to send when going to background (e.g. the process is killed quickly). In that case, it will be submitted at startup with a
reason: dirty_startup, if the previous session was not cleanly closed. This only happens from the second start onward.
See also the ping schedules and timing overview.
Contents
The baseline ping includes the following fields:
See also the ping schedules and timing overview for how the
duration metric relates to other sources of timing in the
baseline ping.
The
baseline ping also includes the common ping sections found in all pings.
Querying ping contents
A quick note about querying ping contents (i.e. for sql.telemetry.mozilla.org): Each metric in the baseline ping is organized by its metric type, and uses a namespace of
glean.baseline. For instance, in order to select
duration you would use
metrics.timespan['glean.baseline.duration']. If you were trying to select a String based metric such as
os, then you would use
metrics.string['glean.baseline.os']
Example baseline ping
{ "ping_info": { "experiments": { "third_party_library": { "branch": "enabled" } }, "seq": 0, "start_time": "2019-03-29T09:50-04:00", "end_time": "2019-03-29T09:53-04:00", "reason": "foreground" }, " }, "metrics": { "timespan": { "glean.baseline.duration": { "value": 52, "time_unit": "second" } } } }
|
https://mozilla.github.io/glean/book/user/pings/baseline.html
|
CC-MAIN-2020-40
|
refinedweb
| 308
| 55.64
|
WebDeveloper.com
>
Client-Side Development
>
JavaScript
> Checking for alphabet and numeric chars in a field
PDA
Click to See Complete Forum and Search -->
:
Checking for alphabet and numeric chars in a field
Ann
07-09-2003, 08:38 AM
Hi Guyz,
I am trying to write javascript code for making sure a field in my form has first 2 characters as alphabets(US) and the rest 8 are numerics.total has to be 10.if any of these r not satisfied,i shud throw up a alert box.i am checking for numerics now but dont know how to combine checking for alphabets n numerics in the same field....
here is my code for checking for numerics...please help me out...sid is my field name...
// only allow numbers to be entered
var checkOK = "0123456789";
var checkStr = document.forms[0].sid.value;
var allValid = true;
var allNum = "";
{
for (i = 0; i < checkStr.length; i++)
{
ch = checkStr.charAt(i);
for (j = 0; j < checkOK.length; j++)
if (ch == checkOK.charAt(j))
break;
if (j == checkOK.length)
{
allValid = false;
break;
}
if (ch != ",")
allNum += ch;
}
if (!allValid)
{
alert("Please enter only 8 numeric characters in the \"sid\" field.");
return (false);
}
Khalid Ali
07-09-2003, 08:44 AM
I think your best bet will be RegExp, soon some php/perl guru will guide you on this....
Ann
07-09-2003, 08:52 AM
Does that mean i cant do it in Javascript :confused:
Khalid Ali
07-09-2003, 08:56 AM
yes you will be able to do that in JavaScript,its only that trying to do it the way you are doing could be slower,regular expression is cleaner and efficient way of parsing strings...
Webskater
07-09-2003, 09:06 AM
You could do it easily enough as data is entered.
This code tells you what key was depressed.
var key = event.keyCode;
This code stops people from entering anything other than 0 to 9
//make sure keys are numeric
if (key<48 || key>57) event.returnValue=false;
This code stops people adding anything other than a-Z
var key = event.keyCode;
//make sure keys are alphabet
if (key<97 || key>122) event.returnValue=false;
So all you have to do is write a function that is called onkeypress, check the length of the field and apply whichever bit is required to force people to only put a-z or 0-9 in the appropriate places. If they try to type anything else - nothing happens - although you would presumably put an alert box up to tell them what they have done wrong.
Fang
07-09-2003, 09:24 AM
This function returns TRUE if it validates, FALSE if it doesn't.
function Validate(FieldValue) {
var objRegExp=/^[a-zA-Z]{2}[1-9]\d{8}$/;
return objRegExp.test(FieldValue);
}
Try one of these () for more on regular expressions.
pyro
07-09-2003, 10:25 AM
Originally posted by Fang
var objRegExp=/^[a-zA-Z]{2}[1-9]\d{8}$/;
Get rid of the [1-9]...
Ann
07-09-2003, 10:50 AM
I tried the onkeypress() function but i have to make sure my first 2 characters are U and S only and nothin else..followed by 8 digits of numeric only.i am unable to do that using the onkeypress code u suggested.IS there any other way or code i do it.I am new to javascript so dont know how to do complicated stuff yet.Please help.
Thanks for all the suggestions..
Ann
07-09-2003, 10:52 AM
I also shud throw an alert box if the user doesn't enter as required...
Ann
07-09-2003, 11:18 AM
This is another thing i tried..
But this does'nt seem to work either...
function Validate(sid)
{
var objRegExp=/^[US]{2}\d{8}$/;
return objRegExp.test(sid);
if (sid = false)
{
alert("Please make sure SID number starts with 'US' followed by 8 numbers");
}
}
Jeff Mott
07-09-2003, 11:29 AM
/^[US]{2}\d{8}$/I think everyone misunderstood and thought you wanted any two alphabetic characters. In any case, /^US\d{8}$/function Validate(sid)
{
var objRegExp=/^[US]{2}\d{8}$/;
return objRegExp.test(sid);
if (sid = false)
{
alert("Please make sure SID number starts with 'US' followed by 8 numbers");
}
}Because of your placement of the return statement, no other statements in that function will be evaluated. You need to close the function brace after the return then pass your variable to be tested to Validate(). Also note the inside of your if statement. One equal sign (=) means assignment and two equal signs (==) means test equality.function validate(sid)
{
return /^US\d{8}$/.test(sid);
}
if (!validate(document.your_text_box.value))
alert("Please make sure SID number starts with 'US' followed by 8 numbers");
Ann
07-09-2003, 12:01 PM
I am really sorry bugging you all like this but it still does'nt work..i used the following code and in my notes JS debugger it shows no error but when i actually open my browser and try to run the form it shows error on page...and no alert box gets thrown up when i enter letters in the numeric fields..
again,really sorry for this but i need to get this done and cant quite figure what i am doing wrong...
function validate(sid)
{
return /^US\d{8}$/.test(sid);
}
if (!validate(document.sid.value))
alert("Please make sure SID number starts with 'US' followed by 8 numbers");
Ann
07-09-2003, 02:37 PM
Thanks a lot Jeff and everyone...it works..
i was making some silly mistakes in the syntax of the code.
:D
webdeveloper.com
|
http://www.webdeveloper.com/forum/archive/index.php/t-12530.html
|
crawl-003
|
refinedweb
| 945
| 65.01
|
Explorations in overriding MATLAB functions
In a recent blog post, I demonstrated how to use the MATLAB 2012a Symbolic Toolbox to perform Variable precision QR decomposition in MATLAB. The result was a function called vpa_qr which did the necessary work.
>> a=vpa([2 1 3;-1 0 7; 0 -1 -1]); >> [Q R]=vpa_qr(a);
I’ve suppressed the output because it’s so large but it definitely works. When I triumphantly presented this function to the user who requested it he was almost completely happy. What he really wanted, however, was for this to work:
>> a=vpa([2 1 3;-1 0 7; 0 -1 -1]); >> [Q R]=qr(a);
In other words he wants to override the qr function such that it accepts variable precision types. MATLAB 2012a does not allow this:
>> a=vpa([2 1 3;-1 0 7; 0 -1 -1]); >> [Q R]=qr(a) Undefined function 'qr' for input arguments of type 'sym'.
I put something together that did the job for him but felt that it was unsatisfactory. So, I sent my code to The MathWorks and asked them if what I had done was sensible and if there were any better options. A MathWorks engineer called Hugo Carr sent me such a great, detailed reply that I asked if I could write it up as a blog post. Here is the result:
Approach 1: Define a new qr function, with a different name (such as vpa_qr). This is probably the safest and simplest option and was the method I used in the original blog post.
- Pros: The new function will not interfere with your MATLAB namespace
- Cons: MATLAB will only use this function if you explicitly define that you wish to use it in a given function. You would have to find all prior references to the qr algorithm and make a decision about which to use.
Approach 2: Define a new qr function and use the ‘isa’ function to catch instances of ‘sym’. This is the approach I took in the code I sent to The MathWorks.
function varargout = qr( varargin ) if nargin == 1 && isa( varargin{1}, 'sym' ) [varargout{1:nargout}] = vpa_qr( varargin{:} ); else [varargout{1:nargout}] = builtin( 'qr', varargin{:} ); end
- Pros: qr will always select the correct code when executed on sym objects
- Cons: This code only works for shadowing built-ins and will produce a warning reminding you of this fact. If you wish to extend this pattern for other class types, you’ll require a switch statement (or nested if-then-else block), which could lead to a complex comparison each time qr is invoked (and subsequent performance hit). Note that switch statements in conjunction with calls to ‘isa’ are usually indicators that an object oriented approach is a better way forward.
Approach 3: The MathWorks do not recommend that you modify your MATLAB install. However for completeness, it is possible to add a new ‘method’ to the sym class by dropping your function into the sym class folder. For MATLAB 2012a on Windows, this folder is at
C:\Program Files\MATLAB\R2012a\toolbox\symbolic\symbolic\@sym
For the sake of illustration, here is a simplified implementation. Call it qr.m
function result = qr( this ) result = feval(symengine,'linalg::factorQR', this); end
Pros: Functions saved to a class folder take precedence over built in functionality, which means that MATLAB will always use your qr method for sym objects.
Cons: If you share code which uses this functionality, it won’t run on someone’s computer unless they update their sym class folder with your qr code. Additionally, if a new method is added to a class it may shadow the behaviour of other MATLAB functionality and lead to unexpected behaviour in Symbolic Toolbox.
Approach 4: For more of an object-oriented approach it is possible to sub-class the sym class, and add a new qr method.
classdef mySym < sym methods function this = mySym(arg) this = this@sym(arg); end function result = qr( this ) result = feval(symengine,'linalg::factorQR', this); end end end
Pros: Your change can be shipped with your code and it will work on a client’s computer without having to change the sym class.
Cons: When calling superclass methods on your mySym objects (such as sin(mySym1)), the result will be returned as the superclass unless you explicitly redefine the method to return the subclass.
N.B. There is a lot of literature which discusses why inheritance (subclassing) to augment a class’s behaviour is a bad idea. For example, if Symbolic Toolbox developers decide to add their own qr method to the sym API, overriding that function with your own code could break the system. You would need to update your subclass every time the superclass is updated. This violates encapsulation, as the subclass implementation depends on the superclass. You can avoid problems like these by using composition instead of inheritance.
Approach 5: You can create a new sym class by using composition, but it takes a little longer than the other approaches. Essentially, this involves creating a wrapper which provides the functionality of the original class, as well as any new functions you are interested in.
classdef mySymComp properties SymProp end methods function this = mySymComp(symInput) this.SymProp = symInput; end function result = qr( this ) result = feval(symengine,'linalg::factorQR', this.SymProp); end end end
Note that in this example we did not add any of the original sym functions to the mySymComp class, however this can be done for as many as you like. For example, I might like to use the sin method from the original sym class, so I can just delegate to the methods of the sym object that I passed in during construction:
classdef mySymComp properties SymProp end methods function this = mySymComp(symInput) this.SymProp = symInput; end function result = qr( this ) result = feval(symengine,'linalg::factorQR', this.SymProp); end function G = sin(this) G = mySymComp(sin(this.SymProp)); end end end
Pros: The change is totally encapsulated, and cannot be broken save for a significant change to the sym api (for example, the MathWorks adding a qr method to sym would not break your code).
Cons: The wrapper can be time consuming to write, and the resulting object is not a ‘sym’, meaning that if you pass a mySymComp object ‘a’ into the following code:
isa(a, 'sym')
MATLAB will return ‘false’ by default.
Note that you can do your approach 3 without modifying the matlab installation, and I think that is the best approach. If you add the qr method to *any* @sym folder on the path it will get dispatched to when you call qr on an instance of sym. It can even be in your own working folder.
If you are concerned that sym may implement their own qr method then you can always look at the meta class information for the sym class (look at what you get with cls = ?sym in MATLAB) and look at its MethodList to see what it defines and you should be able to assert that you are not overriding sym’s native implementation.
@Andy
Andy – good idea. We had a similar thought. The ability to extend a class with methods in another directory is a feature of MATLAB’s classic OO system (struct-based), but is not supported in the modern OO system introduced in R2008a (with classdef files). Since syms are implemented with this newer object system, this technique won’t work.
|
http://www.walkingrandomly.com/?p=4776
|
CC-MAIN-2015-06
|
refinedweb
| 1,244
| 57.1
|
In my current setup I have two components:
- App component which is the main component and contains the method resetSetting which resets the state of the component
- Timer component gets mounted when a state in App is true. This component has a method called checkSession which sets the state of the Timer component.
My problem is that I (am supposed to) have one reset button within App with the id=“reset”. But it needs to run two different onClick functions based on whether the timer is running or not and the method checkSession is within another component and changes the state of the other component.
So now I’m a little stuck on how to handle the reset button… does anyone have any ideas?
The reset button as it is now:
renderReset () { if (this.state.timerOn === false) { return (<button id="reset" onClick ={this.resetSetting}>Reset</button>) }else{ return (<button id="reset" onClick ={this.checkSession}>Reset</button>) } }
Full code is on Codepen:
|
https://forum.freecodecamp.org/t/pomodoro-reset-button/258767
|
CC-MAIN-2022-21
|
refinedweb
| 161
| 63.09
|
Since I had to implement a screenshot for SDL (when using openGL),
and had to mess with it a bit to get it to work, I figured I’d
package up the code and post it here in case anyone else might
be able to use it.
Oh. um. This code is released for anyone to anything they want
with blah blah blah and don’t sue me if it destroys your life etc.
-------------- next part --------------
#include <stdlib.h>
#include “SDL.h” * w * h); if (pixels == NULL) { SDL_FreeSurface(temp); return -1; } glReadPixels(0, 0, screen->w, screen->h, GL_RGB, GL_UNSIGNED_BYTE, pixels); for (i=0; i<h; i++) memcpy(((char *) temp->pixels) + temp->pitch * i, pixels + 3*w * (h-i-1), w*3); free(pixels); SDL_SaveBMP(temp, filename); SDL_FreeSurface(temp); return 0;
}
|
https://discourse.libsdl.org/t/screenshot/3077
|
CC-MAIN-2022-40
|
refinedweb
| 131
| 74.32
|
> > --- Steve Loughran <stevel@apache.org> wrote:
> rule 1 of xml: nobody understands XML namespaces
> rule 2: anybody who says they do. still doesnt.
>
> so there are the following categories
>
> -ignorant of xmlns
> -vaguely aware, but doesnt understand
> -think they understand, but doesnt really
> -knows xmlns enough to know it doesnt make sense, and doesnt understand
Maybe I'm being naive Steve, but the rules for XML NS are *NOT* that complex.
It's fairly easy to know which NS an element or attribute belongs to,
and the parser tells you anyway.
> if you meet someone who thinks they do understand it, ask them if, in
> xml schema, the ##local namespace is in ##other, or not.
How namespaces are used in XSDs for validations is not really part of XML NS.
Here's my limited understanding of XML NS which is enough to know AFAIK:
1) attributes are in no namespace, unless they have an explicit
namespace prefix, which of course must have been declared and be in
scope.
2) elements with an explicit namespace prefix, which of course must
have been declared and be in scope, belong to that explicit namespace.
Sure, the prefix can be remapped to another namespace anywhere in the
document, but people rarely do that, and the parser keeps track of
that for you.
3) elements with no explicit namespace prefix either are not in a
namespace at all, or belong to the namespace mapped to the "default"
namespace in scope, i.e. the one declared with a xmlns="..."
declaration, as opposed to a xmlns:prefix="..." one.
Again, people rarely remap the "default" (missing) namespace prefix in
their documents to differing namespaces.
And that's IT. How can you say that it's THAT complicated ;-)
I consider it unfriendly to map a given NS prefix to more than one NS
in a given file, and to not declare all namespaces in the root
element, especially if there is a "default" namespace.
Stop spreading false information about namespaces Steve ;-))) --DD
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@ant.apache.org
For additional commands, e-mail: dev-help@ant.apache.org
|
http://mail-archives.apache.org/mod_mbox/ant-dev/200703.mbox/%3C255d8d690703231027r31327b58r42be6a8c7c309f7f@mail.gmail.com%3E
|
CC-MAIN-2014-15
|
refinedweb
| 352
| 60.04
|
tag: Kickstarter: Mycestro™, The Next Generation 3D Mouse 2013-05-07T09:56:53-04:00 tag: 2013-05-07T09:56:53-04:00 2013-05-07T14:26:11-04:00 Production Prototype Update 3 This post is for backers only. Please visit <a href="">Kickstarter.com</a> and log in to read. tag: 2013-05-06T11:21:11-04:00 2013-05-06T15:24:38-04:00 Production Prototype Update 2 This post is for backers only. Please visit <a href="">Kickstarter.com</a> and log in to read. tag: 2013-04-29T12:20:40-04:00 2013-05-01T16:09:10-04:00 Production Prototype Update 1 <div class="template" data-<img></div><div class="template" data-<img></div><p>Hi Everyone,</p><p>I know you are all waiting for an update. We are just about to hit a milestone with production prototypes and I have been waiting for the goodies to arrive before I posted. Everything is on track and a full update will be provided in just a couple of days. Please be patient, the fun stuff is about to begin. My apologies to those of you itching for an update. Once we get over this hump, I'm predicting updates will follow more often. </p><p>Nick</p> tag: 2013-03-29T15:04:59-04:00 2013-03-29T15:21:10-04:00 We are Funded!! <p>Dear Backers,</p><p>From all of us here at team Mycestro, we would like to thank all of our backers for the tremendous support.Without you we could never make this happen.We are on a roll moving forward and working hard to get Mycestro into your hands. </p> <p>We want to keep those pre-orders coming in so we now have the <b><a href="" target="_blank">Mycestro.com</a></b> site up and running.There you will be able to get more information on Mycestro and be able to pre-order for October or January delivery depending on the type you chose.So, please tell all your friends and family if that didn't get a chance to pledge on the Kickstarter site.</p> <p>Our goal is to make Mycestro change the way you interface to your PC, Laptop, tablet, IPTV and more.</p> <p>I would also like to say, in the spirit of Kickstarter, that there is another very cool product running a campaign, it's called <a href="" target="_blank">MiiPC</a>. I think Mycestro would be a great addition to that product and its Bluetooth 4.0 compatible.Anyway, I backed them. Nice Job Guys!</p><p>Sincerely</p><p>Nick Mastandrea</p><p>CTO, Innovative Developments LLC</p> tag: 2013-03-23T16:55:18-04:00 2013-03-24T01:03:23-04:00 Stretch Goal Reached <p><b>Dear Backers,</b></p> <p>We are very thankful to all of our backers.Because you believe in us – we want to show you how much we believe in you.We have decided to waive the $400k stretch goal limit and honor our backers with the commitments of the stretch goal regardless if we meet it or not.So… our management team had decided to support all of our backers with the rewards we committed to in the $400k stretch goal.</p> <p>Thank you again for all of your support and please tell everyone you know that we are reaching the end of our Kickstarter campaign and to pledge today.</p> <p>300% Funded, Wow!!</p><p>Sincerely</p><p>Nick Mastandrea</p><p>CTO, Innovative Developments LLC.</p> tag: 2013-03-11T10:52:09-04:00 2013-03-11T10:55:00-04:00 Stretch Goal Time! <p>First off I want to thank all of you for your tremendous support.We are all very excited to get Mycestro™ into your hands and are working diligently to make it happen.But now it's time.<?xml:namespace prefix = o</p><p>Here we go, Stretch Goal time. Yes I know you have been waiting for something to hit the Mycestro project so we worked on coming up with a stretch goal that is not only achievable but also adds value.Here's what we are offering:</p><p>A single Mycestro is great by itself, but what if you were able to use two at the same time? And, what if you were able to have the second Mycestro's battery support the other?This would mean extended battery life with a lot more functions. And, what if you had an application where you were able to the set functionality or commands for each function of multiple Mycestro's....?Well, that's what we think. Wait – there's more.What if you had the ability to upload different configuration to Mycestro, converting it from advanced functionality to your traditional Bluetooth mouse, no application necessary....? I thought so!</p><p><b>Here are the application bullets:</b></p><p>1. Create an application that can support multiple Mycestro's.We decided to create the application so that you will be able to support up to four Mycestro's at one time.The application will have the ability to assign a Mycestro to right hand, Primary (index finger), and right hand secondary (middle finger).The same goes for the left hand, so, will be able to assign left hand primary (index finger) and left hand secondary (index finger).</p><p>2. Make the application so the user can assign keyboard and mouse functions to each of Mycestro's functions.Example: left hand, left button could be set to <b>control</b> function key so when you use the middle button on the right hand you could rotate a 3D model or holding the left hand control key and rotate turns into pan/zoom. </p><p>3. Since we are going to be able to connect at least four Mycestro's to one PC or laptop thru a single dongle, why not have a <b>Collaboration Mode</b>? Now, we are going to try to get this in the application with time permitting, but, if we run out of time by the delivery date in October, we will have this feature shortly after. With Collaboration Mode you will be able to connect Mycestro's from other users, allowing those other users to take control of a mouse and cursor function.Only one controller at a time permitted. </p><p><b>Here are the hardware bullets:</b></p><p>1. Modify the PCB design to support two Mycestro's connected together thru a very short micro USB cable.We will come up with the cable and make it available to everyone as soon as I get pricing.I am imagining that it will not be that expensive. No worries though, we are going to add the code so you could still get the functional benefits of two Mycestro's without the interface cable, you just won't gain in the added benefit of extra battery life.</p><p>2. Add 128K of extra flash to Mycestro to support embedded applications and anything else we can think of.</p><p><b>Here are the Embedded Code bullets:</b></p><p>1. Add in the ability to update software on your Mycestro.We are going to focus on a wired connection first and then in the future try to incorporate a wireless updater.</p><p>2. Add the code to support multiple Mycestro's connected together thru a short USB cable. The battery on one Mycestro will back up the battery on the other Mycestro.Twice the battery life, twice the features. That's pretty cool!</p><p>3. Add the code to be able to use multiple Mycestro's thru a wireless connection.Here you get all the same functionality of having more than one Mycestro's on a single hand, but without the added benefit of extended battery life. </p><p><b>You may ask why would you need two Mycestro's on one hand.Imagine the possibilities! I'm excited about FPS games and a lot more.</b></p><p>Know, in order for us to meet these goals and provide you with the best possible wearable human interface device in the world, Mycestro, we will need to add resources and spin another set of prototypes.I am asking all of you to help us reach a stretch goal of $400,000.Since you are going to be able to use at least two Mycestro's on one hand we are adding another pledge amount for a combination two pack with a single dongle for the Kickstarter special pledge of $149.00 for the classic white version, or $189.00 for a color version.</p><p><b>Know for the </b><b><i>Pièce de résistance: </i>Left hand version of Mycestro.</b></p><p>I have been getting a lot of email for a left hand version of Mycestro.Yes, we are supporting the left hand version in our application so that should show our commitment to getting one out. With that I am happy, even ecstatic ,to announce I got the go-ahead to offer the left handed version. One thing though, we need to change the delivery date for the left hand version to Jan 2014.I know it seems like a long ways off but we need the time, just in case.The last thing I want to do is promise a goal that may be hard to reach. Of course, if it is possible to deliver left hand version sooner we will. So, there will be pledge amounts for left hand version in classic white and color at the same pledge amounts as the right hand.We are also going to offer a left and right hand combo which will include one dongle and one USB cable for charging.Remember, you will be able to set up each Mycestro as left hand primary and right hand primary, and set keyboard and mouse functionality individually on both. Very exciting stuff!</p><p><b>Added bonus Mycestro carrying pouch:</b></p><p>As an added bonus we are going to offer everyone, if we reach our goal, a handy travel pouch to store your Mycestro, cables and dongle.</p><p>Well that's It.I can't express more how thankful we are for your continued support.I know Mycestro is going to change the way you "Conduct Your World"</p><p>Sincerely</p><p>Nick Mastandrea</p><p>CTO, Innovative Developments LLC.</p> tag: 2013-02-22T10:43:46-05:00 2013-02-22T11:03:45-05:00 Goal reached! <p>Wow, the support for Mycestro™ has been tremendous, we reached our goal in a little over nine days.What can I say, through patience and perseverance and the tremendous response from you, the backers of Mycestro we are able to move on to the next part of the journey.</p> <p>This is a very exciting time for the Mycestro Team.Crossing the goal is like an adrenalin shot for all of us.I also want to say special thanks to the Mycestro Team for all their hard work. </p> <p>We have a lot of time left to make a hug impact, so be sure to tell your friends, relatives and neighbors about the chance to be an early supporter of the Mycestro.</p> <p>I look forward to great things to come, so stay tuned for the latest news and updates. Thanks again backers for making it happen.</p><p>Nick</p> tag: 2013-02-16T12:35:31-05:00 2013-02-16T15:41:55-05:00 Quarter of the way <p>I just wanted to say thanks to all the Mycestro™ backers around the world. Thanks to you we are now a quarter of the way to reaching our goal. </p> <p>Everyone who has pledged to receive a Mycestro in their choice of colors will be notified by email to select color preferences.</p><p>I've been getting request for interfacing to Linux operating systems. The team talk it over and we feel that their shouldn't be to much of an issue to support Mycestro running on Linux.</p><p>Oh, and "kudos to Kickstarter" it's really exciting not only for me but I'm sure for all that get an opportunity like this.</p><p>And be sure to tell your friends, relatives and neighbors about the chance to be an early supporter of the Mycestro – an idea that could change the way you "Conduct Your World"</p>
|
http://www.kickstarter.com/projects/mycestro/mycestrotm-the-next-generation-3d-mouse/posts.atom
|
CC-MAIN-2013-20
|
refinedweb
| 2,109
| 64.1
|
PRAGMA temp_store_directory
(1) By Slava G (slavago) on 2020-05-03 14:01:22 [link] [source]
I have java application with 10 threads, each thread works on different DB (each thread on one db). When I create connection to the DB, I pass to it
PRAGMA temp_store_directory with folder where db is located , so temp file will be placed there. Recently reading on that PRAGMA I found :.
But I don't really understand if this connection to the same DB or any connection within same process will be broken ? Also found that.
So, here it's confuses even more. And last is that deprecated in SQLite
This pragma is deprecated and exists for backwards compatibility only. New applications should avoid using this pragma. Older applications should discontinue use of this pragma at the earliest opportunity.
So, not sure how to work if that is deprecated, as I have 10 connections to 10 different DB and how I set temp folder for each connection separately ?
Thanks
(2) By Keith Medcalf (kmedcalf) on 2020-05-03 14:52:24 in reply to 1 [link] [source]
So, not sure how to work if that is deprecated, as I have 10 connections to 10 different DB and how I set temp folder for each connection separately?
Have ten processes with one connection per processes. The "temp directory" concept is a per-instance (of the computer) or per-process concept on every single Operating System ever devised so far.
Or you could write a new OS that maintains a temp folder per thread.
However, presently, no Operating System does this. Most of them have a single temp directory per process and its location is inherited from its parent process by default, although the parent process can "change" the diaper (temp store location) for its baby processes to pee in. SQLite3 allows you to override the current process diaper location, but only for the current process (and everything it contains) that is SQLite3 related.
But I don't really understand if this connection to the same DB or any connection within same process will be broken ? Also found that
Since there is one temp directory active PER PROCESS at one time, changing the TEMP STORE DIRECTORY affects all connections in that process from the time the change is made.tempdirectory global variable and that global variable is not protected by a mutex.
So, here it's confuses even more.
Seems pretty straight forward. The temp store directory is a process wide setting. It is not threadsafe. If you change the temp store directory while at the same time also using it in another thread, you will release the hounds of hell who will promptly eat your program and drag you down into the hellfires for all eternity.
It is simply being somewhat more technical to avoid offending those with delicate sensibilities or weak constitutions.
Putting all that aside, why in the multiverse do you think you need a separate temp directory for each connection? Is it a PHB thing?
(3) By Slava G (slavago) on 2020-05-03 15:03:48 in reply to 2 [link] [source]
Thanks Keith, I have 1 process, with 10 threads, PRAGMA temp directory passed upon creating connection. Each thread has it's own folder where DB is located. Connection itself is not shared between threads. So in this case temp folder is on connection on specific DB or it's globally for all connections for ALL DB's in the process ?
I'm not sure I got your comment about temp folder for OS and each thread.
Using different temp folder for each connection I wanted to solve any possible interfere between DB's as they all have same name.
Thanks
(4.1) By Keith Medcalf (kmedcalf) on 2020-05-03 15:32:18 edited from 4.0 in reply to 3 [link] [source]
There is only ONE temp store directory per process. So whatever you set last in the process is what will be used. (Note this does not change the actual temp store directory which is under control of the Operating System, but rather changes the location where the SQLite3 library will write its temp files -- it will not change where the rest of your program writes its temp files).
If there were interference between temp files then it would not be much of a temp file system. What experimental OS are you using that you cannot trust its' handling of temp files?
Note that I use an Experimental OS from Microsoft which has never been able to manage its temp files since MSDOS 1.0 though to and including the current release of Windows. Its problem however is not a failure to manage the temp file naming, but rather a failure of ability to discard the excrement. Consequently ever since about 1979 a "diaper pump" has been needed to keep the excrement in check lest the baby drown in its own excrement. For each version since MSDOS 1.0 the number of temp file locations that must be regularly pumped out (and the frequency of the pumpings required) has grown exponentially.
I would consider an application that creates yet another "bilge" in need of pumping when it could be using the already existing sewer system to be a big vote against ever allowing the use of such as application.
(5) By Slava G (slavago) on 2020-05-03 15:25:36 in reply to 4.0 [link] [source]
Thanks !!
I'm not using any experimental OS :) CentOS it is :) But, from it's not clear all temp files and transient indices files names convention, it's clear for WAL, Journals and so. But for other it's not that clear, and possible can cause interference between temp files if they're having same names. So this I wanted to avoid. Nothing special or exeperimental.
Slava
(6) By Keith Medcalf (kmedcalf) on 2020-05-03 18:35:10 in reply to 5 [link] [source]
Ah. I see the problem.
You are confusing files which may be temporarily part of the database
- Rollback journals
- Master journals
- Write-ahead Log (WAL) files
- Shared-memory files
and must live in very specific locations and must not be tampered with in any way if they exist (because they are an integral part of the database) with actual "temporary files" that are fleeting in nature and of no significance outside of their specific use at the moment, and which are automatically deleted (well, that is inaccurate, because they are temporary files so they may never actually be created):
- Statement journals
- TEMP databases
- Materializations of views and subqueries
- Transient indices
- Transient databases used by VACUUM
The "temp store directory" only affects the location where these fleeting files are written. This is because, for example, the default temp directory (/tmp perhaps) may only allow a few megabytes of space. This might preclude being able to vacuum a database containing more that a few hundred kilobytes of data, for example. Or perhaps prevent a query that needs a statement journal larger than available /tmp space from running.
Thus you can move the "temp store directory" to a bigger filesystem if need be.
True "temporary files" are just that, they are temporary. The operating system will clean them up (in theory). In *nix, a random file is basically opened and then deleted. The file exists as an inode with no name until the file is closed, at which point the inode is freed. Similarly on other OSes whatever mechanism is used to denote that the file is "temporary" are used to designate the file as being temporary so that when it is closed it ceases to exist. The Operating System generates random "tempfile names" for temporary use and the Operating System guarantees that the namespace is collision free.
So the only reason you would want to change the temp store directory is because you want it to be bigger, otherwise it does nothing at all and there is only one "temp store directory" per process linkage of the SQLite3 library.
(7) By Slava G (slavago) on 2020-05-03 18:42:35 in reply to 6 [link] [source]
Thanks Keith, Now it's clear. Indeed now the only reason to change temp dir is to larger partition. So, as that PRAGMA is deprecated, it's better use TMPDIR or so ? Or can I use PRAGMA in mycode, but only once before any connection is made ? I saw that JDBC drive can set temp folder, but it's uses PRAGMA as well, so what is better way programatically set that folder ?
(8) By Keith Medcalf (kmedcalf) on 2020-05-03 19:31:56 in reply to 7 [link] [source]
While the PRAGMA is deprecated, I doubt that DRH will be getting rid of it anytime soon. If you are going to use the PRAGMA, call it before you start any threads or open any connections.
However, I would prefer the usage of the TMPDIR or SQLITE_TMPDIR environment variables as they would seem to be the least likely to change in the future and this then becomes part of the setup of the application environment rather than a part of the application itself, and hence easier to document in case someone else needs to touch it in the future ... and I would use SQLITE_TMPDIR for the same reasons as it is more obvious that it has limited scope ...
(9) By Slava G (slavago) on 2020-05-03 19:34:33 in reply to 8 [source]
Great, Thanks !!
(10) By Slava G (slavago) on 2020-05-04 06:18:41 in reply to 9 [link] [source]
Last question - is there any option to get value of sqlite3_temp_directory ? for the log purposes.
Thanks.
(11) By Keith Medcalf (kmedcalf) on 2020-05-04 15:45:46 in reply to 10 [link] [source]
I presume you mean the directory being used for temp files, of which the sqlite3_temp_directory global is merely the highest priority override ... looking at the code for interfaces it would appear not.
The actual "temp location" in use does not actually appear to be stored anywhere in either the win or unix VFS but determined and used dynamically when required.
Maybe you can create a temp object (such as a database with an empty string as the name) and use one of the APIs on the connection handle to find the underlying OS filename (which would divulge the temp store location at that time), but even this I am not sure of.
(12) By Slava G (slavago) on 2020-05-06 08:01:20 in reply to 11 [link] [source]
Thanks Keith.
|
https://sqlite.org/forum/info/3e7f50c393925587
|
CC-MAIN-2022-21
|
refinedweb
| 1,772
| 59.43
|
Hi, there,
I got a question about STL that bothers me a lot.
I cannot even do this simple one,
#include <iostream>
void main()
{
cout << "Hello World" << endl ;
}
It gave me this:
Compiling...
1.cpp
E:\temp\1.cpp(5) : error C2065: 'cout' : undeclared identifier
E:\temp\1.cpp(5) : error C2297: '<<' : illegal, right operand has type 'char [12]'
E:\temp\1.cpp(5) : error C2065: 'endl' : undeclared identifier
Error executing cl.exe.
1.obj - 3 error(s), 0 warning(s)
I know it's problem with STL, but don't know what on earth is wrong. I have the library files for STL, such as LIBCP.LIB, LIBCPMT.LIB, MSVCPRT.LIB, LIBCPD.LIB, etc, in the directory of 'C:\Program Files\Microsoft Visual Studio\VC98\LIB' or 'C:\Program Files\Microsoft Visual Studio\VC98\MFC\LIB'.
Do I need to set anything up in VC++. Btw, I'm using MSVC++ 6.0.
Thanks a lot.
Joe
|
https://cboard.cprogramming.com/cplusplus-programming/30816-question-about-stl.html
|
CC-MAIN-2017-13
|
refinedweb
| 157
| 77.03
|
*
A friendly place for programming greenhorns!
Big Moose Saloon
Search
|
Java FAQ
|
Recent Topics
|
Flagged Topics
|
Hot Topics
|
Zero Replies
Register / Login
JavaRanch
»
Java Forums
»
Java
»
Beginning Java
Author
High Scores Table
Daniel McConville
Greenhorn
Joined: Jun 04, 2004
Posts: 1
posted
Jun 04, 2004 23:37:00
0
Hi there,
I am currently working on a project for College where I have to take a set of Drivers, Cars, and Managers and using previous results of races calculate a score using a points system.
So far I have just put all the data into arrays and done simple maths on it. Working out my total points for each 'team' has not been a problem. (Yay!)
I now have an array of 5 teams.
team[0] = 33
team[1] = 27
team[2] = 50
team[3] = 33
team[4] = 28
I need to sort this data into a 'Winners Prediction' based on scores. If I use Arrays.sort it just sorts the array into decending order and then I dont know which team got what orginal score.
I need to find some way of sorting the data from highest to lowest and knowing which team has placed, 1st 2nd 3rd 4th 5th.
Can anyone give me any tips or advice? Thankyou!
-Daniel
Michael Dunn
Ranch Hand
Joined: Jun 09, 2003
Posts: 4632
posted
Jun 05, 2004 02:35:00
0
This seems to work OK, but there's probably better ways
import java.util.*; class Testing { public Testing() { int[] team = {33,27,50,33,28}; ArrayList list = new ArrayList(); for(int x = 0; x < team.length; x++) list.add(new Result(x,team[x])); Comparator comp = new MyComparator(); Collections.sort(list,comp); Result temp; for(int x = 0; x < list.size(); x++) { temp = (Result)list.get(x); System.out.println("team["+temp.arrayElementNumber+"] = "+temp.score); } } public static void main(String[] args){new Testing();} } class Result { int arrayElementNumber; int score; public Result(int aen,int s) { arrayElementNumber = aen; score = s; } } class MyComparator implements Comparator { public int compare(Object o1, Object o2) { return new Integer(((Result)o1).score).compareTo(new Integer(((Result)o2).score)) * -1; } }
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
posted
Jun 06, 2004 15:59:00
0
I think you'll want something more than a simple array of scores. Once you have that array of scores sorted, how do you know which score goes with which team?
Would you be comfortable making a Team class? It might hold some team data for you:
public class Team { public String name = ""; public int score = 0; maybe driver, car, fields, etc. }
You could make an array (or some collection, hint hint) of Team objects and sort those by score. Then you could go through the sorted array and print name & score for each Team object.
If you want to go that direction, look into the JavaDoc APIs for Set to hold your objects. Is there a flavor of Set that would do the sorting for you? And see the Comparable interface to help you sort them. Feel free to take a stab at that, see how far you get, post some code for comment.
Hope that helps.: High Scores Table
Similar Threads
EL: Iterate over "sub" entities (Hibernate, Facelets)?
Passed SCJD 356/400
Pass SCJD, 361/400
Get Ready for Martin Fowler
Passed 370/400 (92.5%) !!
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
JForum
|
Paul Wheaton
|
http://www.coderanch.com/t/396586/java/java/High-Scores-Table
|
CC-MAIN-2014-41
|
refinedweb
| 577
| 71.44
|
06 July 2012 17:05 [Source: ICIS news]
WASHINGTON (ICIS)--The ?xml:namespace>
In its monthly employment report, the department said the chemicals sector added 900 employees in June to bring the sector’s total workforce back up to 797,900.
The chemicals industry had seen a modest employment downturn in May with the loss of about 600 positions.
In the plastics and rubber products industry, 1,100 workers were taken on in June, bringing that sector’s labour complement to 644,900.
That workforce gain more than offset the 900 job losses seen in the plastics and rubber sector in May.
In the broad employment report, June’s addition of 80,000 jobs was below economists’ modest expectations for a gain of 90,000.
Although better than May’s mediocre 69,000 jobs increase, June’s figure is still far below the 150,000 new jobs needed each month just to accommodate population growth.
The department said the nation’s unemployment rate held steady at 8.2% in June.
The country would have to generate 350,000 jobs each month for multiple quarters to make any headway in reducing the unemployment
|
http://www.icis.com/Articles/2012/07/06/9576247/us-chemicals-plastics-sectors-added-workers-in-june.html
|
CC-MAIN-2014-42
|
refinedweb
| 192
| 62.27
|
, script, and EL expressions in your template in order to generate parametrized text. Here is an example of using the system:Error rendering macro 'code': Invalid value specified for parameter 'lang'
import groovy.text.Template. The variable
session is one of some default bound keys. More details reveals the documentation of
groovy.servlet.ServletBinding.
Here is some sample code using servlet container. Just get the latest Jetty jar and put this excerpt in a main method, organize the imports and start! Note, that the servlet handler also knows how to serve
*.groovy files and supports dumping:
TODO Provide web.xml
The TemplateServlet just works the other way as the Groovlets
|
http://docs.codehaus.org/pages/viewpage.action?pageId=25056
|
CC-MAIN-2015-18
|
refinedweb
| 110
| 59.7
|
42
To read all comments associated with this story, please click here.
To read all comments associated with this story, please click here.
Member since:
2005-11-13
True. And not including code to debug and play .ogg, .au, .ape, .flac, .tta, and so on makes sense because each implementation is yet another place for bugs to creep in and more code to support.
And, unlike a computer, a car stereo head unit generally doesn't have issues with remotely exploitable security flaws exposing your valuable data and personal information, so my analogy is getting stretched thin.
My fault for being sloppy. I was referring to GUI apps rather than command line, character-based. But good link.
We could have 32 bit dynamically linked libraries, or DLLs, that app installations could place in system directories! No need to worry about namespace collisions or versioning, since we can trust the app developers to 'do the right thing.' I think we have a winner!
My first personal computer (disk-based) was a CP/M-80 system. Although I had source for most of the software on it, I can't think of any that I've ported to my current system or even the systems in-between. To cite one example, I don't really need the source code to the programmer's text editor I use -- I just need a viable alternative on the platform on which I will be working.
I suspect that's the case for many people. If the elimination of 32 bit app support on MacOS means that they can't play the Donkey Kong knock-off that they bought from some kid in Latvia in 2007, I'm okay with that.
|
http://www.osnews.com/permalink?653542
|
CC-MAIN-2018-09
|
refinedweb
| 285
| 72.36
|
Ember.js: The Perfect Framework for Web Applications
Free JavaScript Book!
Write powerful, clean and maintainable JavaScript.
RRP $11.95
Ember.js is an opinionated frontend JavaScript framework that has been getting a lot of interest lately. This article will introduce some key concepts of the framework while building a simple application with it, in order to show a basic example of what it is capable of producing.
Our example application is going to be a Dice Roller, including the ability to roll some dice and view a history of all dice rolls that have been performed to date. A fully working version of this application is available from Github
The Ember.js framework pulls together a lot of modern JavaScript concepts and technologies into one single bundle, including but not limited to:
- The use of the Babel transpiler tool, to support ES2016 throughout.
- Testing support at the Unit, Integration and Acceptance levels as standard, powered by Testem and QTest.
- Asset building using Broccoli.js.
- Support for live reloading, for shorter development cycle times.
- Templating using the Handlebars markup syntax.
- URL Routing first development to ensure that deep linking is fully supported throughout.
- Full data layer built around JSON API, but pluggable for whatever API access you need.
In order to work with Ember.js, it is assumed that you have an up-to-date installation of Node.js and npm. If not then these can be downloaded and installed from the Node.js website.
It should also be mentioned that Ember is purely a frontend framework. It has a number of ways of interacting with the backend of your choice, but this backend is not in any way handled by Ember itself.
Introducing ember-cli
A lot of the power of Ember.js comes from its command line interface (CLI). This tool – known as ember-cli – powers much of the development lifecycle of an Ember.js application, starting from creating the application, through adding functionality into it all the way to running the test suites and starting the actual project in development mode.
Almost everything that you do whilst developing an Ember.js application will involve this tool at some level, so it is important to understand how best to use it. We will be making use of it throughout this article.
The first thing we need to do is ensure that the Ember.js CLI is correctly installed and up-to-date. This is done by installing from npm, as follows:
$ npm install -g ember-cli
and we can check it was successfully installed by running the following command:
$ ember --version ember-cli: 2.15.0-beta.1 node: 8.2.1 os: darwin x64
Creating Your First Ember.js App
Once ember-cli is installed, you are ready to start creating your application. This is the first place we will be making use of the Ember.js CLI tool – it creates the entire application structure, setting everything up ready to run.
$ ember new dice-roller installing app create .editorconfig create .ember-cli create .eslintrc.js create .travis.yml create .watchmanconfig create README.md create app/app.js create app/components/.gitkeep. $
This has caused an entire application to be created which is ready to run. It has even set up Git as source control to track your work.
Note: If you wish, you can disable the Git integration and you can prefer Yarn over npm. The help for the tool describes this and much more.
Now, let’s see what it looks like. Starting the Ember application for development purposes is – once again – also done using ember-cli:
$ cd dice-roller $ ember serve Livereload server on 'instrument' is imported from external module 'ember-data/-debug' but never used Warning: ignoring input sourcemap for vendor/ember/ember.debug.js because ENOENT: no such file or directory, open '/Users/coxg/source/me/writing/repos/dice-roller/tmp/source_map_concat-input_base_path-2fXNPqjl.tmp/vendor/ember/ember.debug.map' Warning: ignoring input sourcemap for vendor/ember/ember-testing.js because ENOENT: no such file or directory, open '/Users/coxg/source/me/writing/repos/dice-roller/tmp/source_map_concat-input_base_path-Xwpjztar.tmp/vendor/ember/ember-testing.map' Build successful (5835ms) – Serving on Slowest Nodes (totalTime => 5% ) | Total (avg) ----------------------------------------------+--------------------- Babel (16) | 4625ms (289 ms) Rollup (1) | 445ms
We are now ready to go. The application is running on, and looks like this:
It is also running a LiveReload service which automatically watches for changes to the filesystem. This means that you can have an incredibly fast turnaround time when tweaking your site design.
Let’s try it?
The initial page already tells us what to do, so let’s go and change the main page and see what happens. We’re going to change the
app/templates/application.hbs file to look like the following.
This is my new application. {{outlet}}
Note: The
{{outlet}}tag is part of how Routing works in Ember. We will cover that later on.
The first thing to notice is the output from ember-cli, which should look as follows:
file changed templates/application.hbs Build successful (67ms) – Serving on Slowest Nodes (totalTime => 5% ) | Total (avg) ----------------------------------------------+--------------------- SourceMapConcat: Concat: App (1) | 9ms SourceMapConcat: Concat: Vendor /asset... (1) | 8ms SimpleConcatConcat: Concat: Vendor Sty... (1) | 4ms Funnel (7) | 4ms (0 ms)
This tells us that it has spotted that we changed the template and rebuilt and restarted everything. We’ve had zero involvement in that part of it.
Now let’s look at the browser. If you’ve got LiveReload installed and running you will not even have needed to refresh the browser for this to be picked up, otherwise, you will need to reload the current page.
Not very exciting, but this is with almost no effort on our part that we’ve achieved this.
In addition, we get a fully set up test suite ready to run. This is – unsurprisingly – run using the Ember tool as well, as follows:
$ ember test ⠸ Building'instrument' is imported from external module 'ember-data/-debug' but never used ⠴ BuildingWarning: ignoring input sourcemap for vendor/ember/ember.debug.js because ENOENT: no such file or directory, open '/Users/coxg/source/me/writing/repos/dice-roller/tmp/source_map_concat-input_base_path-S8aQFGaz.tmp/vendor/ember/ember.debug.map' ⠇ BuildingWarning: ignoring input sourcemap for vendor/ember/ember-testing.js because ENOENT: no such file or directory, open '/Users/coxg/source/me/writing/repos/dice-roller/tmp/source_map_concat-input_base_path-wO8OLEE2.tmp/vendor/ember/ember-testing.map' cleaning up... Built project successfully. Stored in "/Users/coxg/source/me/writing/repos/dice-roller/tmp/class-tests_dist-PUnMT5zL.tmp". ok 1 PhantomJS 2.1 - ESLint | app: app.js ok 2 PhantomJS 2.1 - ESLint | app: resolver.js ok 3 PhantomJS 2.1 - ESLint | app: router.js ok 4 PhantomJS 2.1 - ESLint | tests: helpers/destroy-app.js ok 5 PhantomJS 2.1 - ESLint | tests: helpers/module-for-acceptance.js ok 6 PhantomJS 2.1 - ESLint | tests: helpers/resolver.js ok 7 PhantomJS 2.1 - ESLint | tests: helpers/start-app.js ok 8 PhantomJS 2.1 - ESLint | tests: test-helper.js 1..8 # tests 8 # pass 8 # skip 0 # fail 0 # ok
Note that the output talks about PhantomJS. This is because there is full support for Integration tests that run in a browser, and by default, these run headless in the PhantomJS browser. There is full support for running them in other browsers if you wish, and when setting up continuous integration (CI) it is worth doing this to ensure that your application works correctly in all supported browsers.
How an Ember.js app is structured
Before we get to actually writing our application, let’s explore how it is structured on the filesystem. The
ember new command above will have created a whole directory structure on your computer, with lots of different parts. Understanding all of these is important to efficiently work with the tool and create amazing projects.
At the very top level you will notice the following files and directories:
- README.md – This is the standard readme file describing the application
- package.json – This is the standard npm configuration file describing your application. This is used primarily for the dependencies to be installed correctly.
- ember-cli-build.js – This is the configuration for the Ember CLI tool to power our build
- testem.js – This is the configuration for the test framework. This allows you to define, amongst other things, the browsers that should be used to run the tests in for different environments.
- app/ – This is the actual application logic. A lot happens in here that will be covered below.
- config/ – This is the configuration for the application
- config/targets.js – This is a list of browsers to support. This is used by Babel to ensure that the Javascript is transpiled in such a way that they will all work.
- config/environment.js – This is the main configuration for your application. Anything that is needed for the application, but that might vary from one environment to another, should be put in here.
- public/ – This is any static resources that you wish to include in your application. For example, images and fonts.
- vendor/ – This is where any frontend dependencies that are not managed by the build system go
- tests/ – This is where all of the tests go
- tests/unit – This is all of the unit tests for the application
- tests/integration – This is all of the integration tests for the application
Overall Page Structure (Including Third-Party Content)
Before we get too far ahead, let’s give our page some form of structure. In this case, we are going to add in the Materialize CSS framework to give it a better look and feel.
Adding in support for third-party content like this can be done in a number of ways:
- Linking directly to the content on an external service, like a CDN
- Using a package manager like npm or Bower to install it for us
- Including it directly in our application.
- Use of an Ember Addon if one is provided
Unfortunately, the addon for Materialize doesn’t yet work with the latest version of Ember.js so, instead, we are simply going to link to the CDN resources from our main page. In order to achieve this, we are going to update
app/index.html, which is the main page structure into which our application is rendered. We’re going to simply add the CDN links for jQuery, Google Icon Font, and Materialize.
<!-- Inside the Head section --> <link href="" rel="stylesheet"> <link rel="stylesheet" href=""> <!-- Inside the Body section --> <script type="text/javascript" src=""></script> <script src=""></script>
Now we can update the main page to show our core template. This is done by editing
app/templates/application.hbs to look like this:
<nav> <div class="nav-wrapper"> <a href="#" class="brand-logo"> <i class="material-icons">filter_6</i> Dice Roller </a> <ul id="nav-mobile" class="right hide-on-med-and-down"> </ul> </div> </nav> <div class="container"> {{outlet}} </div>
This gives us a Materialize Nav at the top of the screen, with a container containing that
{{outlet}} tag mentioned earlier.
This then looks like this when visited in your browser:
So what is this
outlet tag? Ember works based off of routes, where each route is considered a child of some other route. The top-most route is handled by Ember automatically, and renders the template
app/templates/application.hbs.
The
outlet tag specifies where Ember will render the next route in the current hierarchy – so the first level route is rendered into this tag in
application.hbs, the second level route is rendered into this tag in that first level template, and so on.
Creating a New Route
In an Ember.js application, every page that can be visited is accessed via a Route. There is a direct mapping between the URL that the browser opens and the route that the application renders.
The easiest way to see this is by example. Let’s add a new route to our application allowing the user to actually roll some dice. Once again, this is done using the ember-cli tool.
$ ember generate route roll installing route create app/routes/roll.js create app/templates/roll.hbs updating router add route roll installing route-test create tests/unit/routes/roll-test.js
What this one command has given us is:
- A handler for the route –
app/routes/roll.js
- A template for the route –
app/templates/roll.hbs
- A test for the route –
tests/unit/routes/roll-test.js
- Updated the router configuration to know about this new route –
app/router.js
Let’s see this in action. For now, we’re going to have a very simple page allowing us to roll a number of dice. To do so, update
app/templates/roll.hbs as follows:
<div class=> </div> {{outlet}}
Then visit and see the result:
Now we need to be able to get here. Ember makes this very simple to achieve by use of the
link-to tag. This takes (among other things) the name of the route that we are sending the user to and then renders markup to get the user there.
For our case, we will be updating
app/templates/application.hbs to contain the following:
<ul id="nav-mobile" class="right hide-on-med-and-down"> {{#link-to 'roll' tagName="li"}} <a href="roll">Roll Dice</a> {{/link-to}} </ul>
Which makes our header bar look as follows:
This new link then takes the user to the “/roll” route that we’ve just set up, exactly as desired.
Creating Modular Components
If you actually test the application so far you will notice one problem. Opening the home page and visiting the “/roll” link works, but the labels on the form don’t line up properly. This is because Materialize needs to trigger some JavaScript to sort things out, but the dynamic routing means that the page isn’t being reloaded. We will need to help out a bit here.
Enter components. Components are pieces of UI that have a full lifecycle and can be interacted with. They are also the way that you will create reusable UI elements if you need to do so – we will see this later.
For now, we are going to create a single component representing the Roll Dice form. As always, generating the component is done with our ember-cli tool, as follows:
$ ember generate component roll-dice installing component create app/components/roll-dice.js create app/templates/components/roll-dice.hbs installing component-test create tests/integration/components/roll-dice-test.js
This has given us:
- app/components/roll-dice.js – The code that powers the component
- app/templates/components/roll-dice.hbs – The template that controls how it will look
- tests/integration/components/roll-dice-test.js – A test to ensure the component works correctly
We’re going to move all of our markup into the component now – which will do nothing to the way the application works directly but makes it easy for us to do so in a bit.
Update
app/templates/components/roll-dice.hbs to read as>
And then update app/templates/roll.hbs as follows:
<div class="row"> {{roll-dice}} </div> {{outlet}}
The template for our component is exactly the markup that we previously had in our route, and our route is significantly simpler now. The
roll-dice tag is what tells Ember to render our component in the right place.
If we were to run this now we would see no functional difference at all, but our code is slightly more modular this way. We’re going to take advantage of the component to fix our rendering glitch and to add some functionality to our system.
The component lifecycle
Ember components have a defined lifecycle that they follow, with a number of hooks that can be triggered at different stages. We are going to make use of the
didRender hook which is called after the component is rendered – either for the first time or any subsequent times – to ask Materialize to update the labels on the text fields.
This is done by updating the code behind the component, found inside
app/components/roll-dice.js, to look like this:
/* global Materialize:false */ import Ember from 'ember'; export default Ember.Component.extend({ didRender() { Materialize.updateTextFields(); } });
Now, every time you visit the “/roll” route – whether it’s by deep linking to it or by using our header link – this code is run and Materialize will update the labels to flow correctly.
Data binding
We also want to be able to get data in and out of our UI via our component. This is remarkably easy to achieve but, surprisingly, the Ember guide doesn’t cover it, so it looks harder than it should be.
Every piece of data that we want to interact with exists on the Component class as it’s own field. We then use some helpers to render our input fields on our component that do the work of binding these input fields to the component variables, so that we can interact with them directly without ever needing to be concerned with the DOM activities.
In this case, we have three fields so we need to add the following three lines to
app/components/roll-dice.js, just inside the component definition:
rollName: '', numberOfDice: 1, numberOfSides: 6,
Then we update our template to render using the helpers instead of directly rendering HTML markup. To do this, replace the
<input> tags as follows:
<div class="row"> <div class="input-field col s12"> <!-- This replaces the <input> tag for "roll_name" --> {{inputName of Roll</label> </div> </div> <div class="row"> <div class="input-field col s6"> <!-- This replaces the <input> tag for "number_of_dice" --> {{inputNumber of Dice</label> </div> <div class="input-field col s6"> <!-- This replaces the <input> tag for "number_of_sides" --> {{inputNumber of Sides</label> </div> </div>
Note that the
value attribute has a slightly odd-looking syntax. This syntax can be used for any attribute on the tag, not only
value. There are three ways that this can be used:
- As a quoted string – the value is used as-is
- As an unquoted string – the value is populated from this piece of data on the component, but the component is never updated
- As
(mut <name>)– the value is populated from this piece of data on the component, and the component is mutated when the value changes in the browser
All of the above means that we can now access those three fields we defined in our component as if they were the values of our input boxes, and Ember ensures that everything works correctly like that.
Component actions
The next thing we want to do is interact with the component. Specifically, it would be good to handle when our “Roll Dice” button is clicked. Ember handles this with Actions – which are pieces of code in your component that can be hooked into your template. Actions are simply defined as functions in our component class, inside a special field called
actions, which implement our desired functionality.
For now, we are simply going to tell the user what they want to do, but not actually do anything – that comes next. This will use an On Submit action on the form itself, which means that it gets triggered if they click on the button or they press enter in one of the fields.
Our actions code block inside of
app/components/roll-dice.hbs is going to look like this:
actions: { triggerRoll() { alert(`Rolling ${this.numberOfDice}D${this.numberOfSides} as "${this.rollName}"`); return false; } }
We return
false to prevent event bubbling. This is fairly standard behavior in HTML applications and is essential in this case to stop the form submission from reloading the page.
You will note that we refer to our fields that we previously defined for accessing the input fields. There is no DOM access at all here – it’s all just interacting with JavaScript variables.
Now we just need to wire this up. In our template, we need to tell the form tag that it needs to trigger this action when the
onsubmit event is triggered. This is just adding a single attribute to the form tag using an Ember helper to wire it up to our action. This looks as follows inside
app/templates/components/roll-dice.hbs:
<form class="col s12" onsubmit={{action 'triggerRoll'}}>
We can now click on the button, having filled out our form, and get a alert popup telling us what we’ve done.
Managing Data Between Client and Server
The next thing we want to do is actually roll some dice. This is going to involve some communication with the server – since the server is responsible for rolling the dice and remembering the results.
Our desired flow here is:
- Users specifies the dice they wish to roll
- User presses the “Roll Dice” button
- Browser sends the details to the server
- Server rolls the dice, remembers the result, and sends the results back to the client
- Browser displays the results of rolling the dice
Sounds simple enough. And, of course, with Ember it really is.
Ember handles this using an inbuilt concept of a Store populated with Models. The Store is the single source of knowledge throughout the entire application, and each Model is a single piece of information in the store. Models all know how to persist themselves to the backend, and the Store knows how to create and access Models.
Passing Control from Components to Routes
Throughout our application, it is important to keep the encapsulation correct. Routes (and controllers, which we haven’t covered) have access to the store. Components do not.
This is because the route represents a specific piece of functionality in your application, whereas the component represents a small piece of UI. In order to work with this, the component has the ability to send a signal up the hierarchy that some action has happened – in a very similar way that our DOM components could signal to our component that something has happened.
Firstly then, let’s move our logic for displaying the alert box into the route instead of the component. In order to do this, we need to change the following areas of code:
In the logic behind our route –
app/routes/roll.js – we need to add the following block to register the action that we are going to perform.
actions: { saveRoll: function(rollName, numberOfDice, numberOfSides) { alert(`Rolling ${numberOfDice}D${numberOfSides} as "${rollName}"`); } }
In the logic behind our component –
app/components/roll-dice.js – we need to trigger an action on our component when we ourselves are triggered. This is done using the
sendAction mechanism inside our preexisting action handler.
triggerRoll() { this.sendAction('roll', this.rollName, this.numberOfDice, this.numberOfSides); return false; }
And finally, we need to wire the action up. This is done in the template for the route –
app/templates/roll.hbs – by changing the way that our component is rendered:
{{roll-dice roll="saveRoll" }}
This tells the component that the property
roll is linked to the action
saveRoll inside our route. This name
roll is then used inside our component to indicate to the caller that a dice roll has been done. This name makes sense to our component – because it knows that it is requesting a dice roll to be performed, but doesn’t care how the other code does so or what it will do with the information.
Again, running this will cause no functional difference in our application, but just means that the pieces are all in the right place.
Persisting to the Store
Before we are able to persist data into our store, we need to define a model to represent it. This is done by using our trusty ember-cli tool again to create the structure and then populating it.
To create the model class we execute:
$ ember generate model roll installing model create app/models/roll.js installing model-test create tests/unit/models/roll-test.js
Then we tell our model about the attributes it needs to understand. This is done by modifying
app/models/roll.js to look like the following:
import DS from 'ember-data'; export default DS.Model.extend({ rollName: DS.attr('string'), numberOfDice: DS.attr('number'), numberOfSides: DS.attr('number'), result: DS.attr('number') });
The
DS.attr calls define a new attribute of the specified type – called a Transform in Ember. The default options here are “string”, “number”, “date” and “boolean”, though you can define your own if necessary.
Now we can actually use this to create or roll. This is done by accessing the store from our action we now have in
app/routes/roll.js:
saveRoll: function(rollName, numberOfDice, numberOfSides) { let result = 0; for (let i = 0; i < numberOfDice; ++i) { result += 1 + (parseInt(Math.random() * numberOfSides)); } const store = this.get('store'); // This requests that the store give us an instance of our "roll" model with the given data const roll = store.createRecord('roll', { rollName, numberOfDice, numberOfSides, result }); // This tells our model to save itself to our backend roll.save(); }
If we try this out, we will now see that pressing our Roll Dice button causes a network call to be made to our server. This fails, because our server isn’t yet expecting it, but it’s progress.
We’re not focusing on the backend here, so we’re going to concern ourselves with this. If you need to develop an Ember application without a backend at all then there are options – such as the ember-localstorage-adapter that will work entirely within the browser. Alternatively, you simply need to write the appropriate server and ensure that the server and client are hosted correctly and it will all work.
Now that we’ve got some data into our store, we need to get it back out again. At the same time, we’re going to write an index route – the one that is used when you access the home page.
Ember implicitly has a route called
index that is used to render the initial page of the application. If the files for this route do not exist then no error is raised but, instead, nothing is rendered. We are going to use this route to render all of the historical rolls from our store.
Because the index route already implicitly exists, there is no need to use the ember-cli tool – we can directly create the files and it is already wired up.
Our route handler will go into
app/routes/index.js and will look as follows:
import Ember from 'ember'; export default Ember.Route.extend({ model() { return this.get('store').findAll('roll'); } });
Here, our route has direct access to the store and can use the
findAll method to load every roll that has been persisted. We then provide these to the template by use of the
model method.
Our template will then go into
app/templates/index.hbs as follows:
<table> <thead> <tr> <th>Name</th> <th>Dice Rolled</th> <th>Result</th> </tr> </thead> <tbody> {{#each model as |roll|}} <tr> <td>{{roll.rollName}}</td> <td>{{roll.numberOfDice}}D{{roll.numberOfSides}}</td> <td>{{roll.result}}</td> </tr> {{/each}} </tbody> </table> {{outlet}}
This can access the model from the route directly, and then iterates over it to produce the table rows. This will then look as follows:
Summary
At this point, after relatively little work, we have developed an application that will allow us to roll dice and see a history of all rolls. This includes data binding from our form, persisting data into a store, and reading it back out, templating support to display all of the pages, and full URL routing throughout. This application can be developed from scratch in under an hour.
Using Ember can greatly improve the efficiency with which you develop your frontend. Unlike libraries such as React, Ember gives you the entire suite of functionality necessary to build a fully functional application without needing any extra tools. The addition of the
ember-cli and the out-of-the-box setup then takes this to the next level, making the process incredibly simple and painless from beginning to end. Coupled with the community support there is almost nothing that can’t be achieved.
Unfortunately, it can be difficult to slot Ember into an existing project. It works best when.
Get practical advice to start your career in programming!
Master complex transitions, transformations and animations in CSS!
|
https://www.sitepoint.com/ember-js-perfect-framework-web-applications/?utm_source=frontendfocus&utm_medium=email
|
CC-MAIN-2021-10
|
refinedweb
| 4,751
| 64.41
|
Dear All,
Does anybody know how to count lines within specific area say inside of a rectangle and the lines have specific angle say 45deg, also possible highlight the valid lines with color?
Thanks
Find the number of lines inside a specific area
OpenMV related project discussion.
2 posts • Page 1 of 1
Re: Find the number of lines inside a specific area
Here you go, you have to tune if for your application:
Code: Select all
# Counting vertical lines example script. # # Adjust the threshold value to max it so only really strong lines appear... A higher threshold for stronger lines. # Adjust the theta_margin value to control the merging of lines with similar angles. # Adjsut the rho_margin value to control the mergining of lines that are physically nearby. # Note that you may detect two lines on either side of some object. To filter this out... make the rho margin higher. import sensor, image sensor.reset() sensor.set_pixformat(sensor.GRAYSCALE) sensor.set_framesize(sensor.VGA) sensor.set_windowing((640, 80)) sensor.skip_frames(time = 2000) def line_filter(line): # Undo negative rho... t = line.theta() if (line.rho() >= 0) else (line.theta() + 180) # If the line is vertical it should have a theta close to 0/360 return ((t < 10) or (t > 350)) # You'll want to play with these settings here... while(True): img = sensor.snapshot() lines = list(filter(line_filter, img.find_lines(x_stride=1, y_stride=1, threshold = 1000, theta_margin = 20, rho_margin = 10))) # You'll want to play with these settings here... for line in lines: img.draw_line(line.line(), color=127) print("Lines Seen %d" % len(lines))
Nyamekye,
2 posts • Page 1 of 1
Return to “Project Discussion”
Who is online
Users browsing this forum: No registered users and 1 guest
|
http://forums.openmv.io/viewtopic.php?f=5&p=2958&sid=8bd0908da58f4c27347550088fb2e0a3
|
CC-MAIN-2018-05
|
refinedweb
| 287
| 67.65
|
Opened 7 years ago
Closed 4 years ago
Last modified 4 years ago
#13586 closed Cleanup/optimization (fixed)
Improvements in Signals.m2m_changed documentation
Description
I think it should be explicitly mentioned in the doc that the sender must be the through table when the signal is connected:
m2m_changed.connect(yourfunction, sender=Model.m2mfield.through)
Otherwise, it's a bit difficult, I had to read tests to understand this. Thoughts?
Change History (16)
comment:1 Changed 7 years ago by
comment:2 Changed 7 years ago by
comment:3 Changed 7 years ago by
OK, now that I re-read it, it seems obvious. My bad.
Thanks for the time you spent on this and sorry for the noise.
comment:4 Changed 6 years ago by
I have just stumbled across the same problem. I saw my failure, after I have gone through django/tests/modeltests/m2m_signals/models.py
IMHO it's a good idea to insert a code example with m2m_changed.connect() to the docs.
comment:5 Changed 6 years ago by
I agree with jedie. Good example:
def toppings_changed(sender, **kwargs): # Do something m2m_changed.connect(profile_city_changed, sender=Pizza.toppings.through)
I think the documentation could also be explicit that checking for what has changed is not possible at this time (until #6707 is addressed) and that people are advised to make their own through model and override the save method there if they want to know what is changing.
comment:6 Changed 6 years ago by
Oops, meant:
m2m_changed.connect(toppings_changed, sender=Pizza.toppings.through)
comment:7 Changed 6 years ago by
Adding that code sample would help, as well as more specifics, such as:
- "sender" expects to be assigned the class Type of the class whose signals you want to receive.
- When you reference it in code, "<code><class_reference>.<ManyToManyField_name>.through</code>" (example: "Pizza.toppings.through" in the example above) actually returns a class Type instance.
- You can access the <code><ManyToManyField name></code> reference (example: "Pizza.toppings" in the code above) through a reference to its containing class, not just through an instance of that class (this might be obvious in python, but I don't think you can assume everyone would grasp this).
- the class that contains the "through" must either have been imported into the current file or defined there.
- it would be polite to document somewhere the exact characteristics of the default m2m "through" class. I looked today and could not find that anywhere in the documentation.
- It would be good also to document how the M2M save in the admin works (clearing all, then re-adding, and so never firing the remove signals). I would never have thought it worked that way, and it took me a few hours of debugging to figure it out since I couldn't find the details on that documented anywhere. Most will be using these hooks to get around problems they can't address in post-save overriding in the admin. The documentation should ground this example in the admin, so that one knows where the three pre-post pairs of signals occur there, and it should note that in the current implementation of the admin, where most of these signals will occur for the majority of users, one of those signals never gets fired. So, you might need to implement a remove handler, but it won't get called if you manage M2M in the admin, so if there are actions you need to do on remove, well, tough luck, or process them all at clear, then undo some of them on re-add.
comment:8 Changed 6 years ago by
And apologies for the bad formatting. In the above, the <code> tags should be removed.
comment:9 Changed 6 years ago by
An improved example certainly couldn't hurt. Perhaps adding some more obvious language about
through is possible (I'd have to see a patch).
However, most of what jonathanmorgan suggests is covered elsewhere in the signals documentation (sender being the class you wish to receive signals from), or is inherent in Python (re: importing or defining the model you wish to reference). The last two items may be valid (I haven't looked for existing docs for either), but they're separate issues and don't belong in this ticket. If you want to open separate tickets for them you may.
I'll mark the ticket as accepted but strike the milestone until someone provides a patch that offers concrete improvement.
comment:10 Changed 6 years ago by
Hello,
I would be happy to work up a patch. What format does a documentation patch take (I looked on the page about how to contribute and couldn't find instructions - if there is a page, please just point me to it, and I apologize for not finding it myself)? I will also make separate tickets for the last two items.
On your comments:
- I did not see anywhere in the signals doc for the m2m_changed signal an explanation of the "<class>.<field>.through" class and how it relates to a model class and creating a ManyToManyField relation. The documentation on this signal says you have to give the class you wish to receive signals from. It does not specify that this class it not the Model class that contains the ManyToManyField, but is the "through" class for a given ManyToManyField, and that a given Model class can have more than one, and that you can configure an m2m_changed signal handler to listen to any or all of them, but that you must configure it for each field, and can't just have it listen to all many-to-many fields on a given model class.
- on things being inherent to python - That might be the case, but I know I personally regularly program in ruby and rails, PHP, Java, perl, and ColdFusion in addition to Python and django, and I think you should aim for thoroughness in examples in discrete areas of documentation, so a given piece of your documentation is as easy to use as possible for the widest range of people with as little jumping around needed for troubleshooting. In looking at python doc, there are two different ways classes can be implemented in python, an old and new way, and I couldn't find anywhere an explicit statement of which django uses. If you had that somewhere - "all django classes are python Type instances, not old-style python classes." That would probably be sufficient, but I couldn't find a straightforward statement of that anywhere in the doc.
This is great software, and I'd like to help make it more accessible to new adopters.
Thanks,
Jonathan
comment:11 Changed 6 years ago by
@jonathanmorgan -- There are two pieces of documentation on writing documentation patches:
-
-
To answer the question more directly, the docs are all contained within the Django repository so it's easy to start editing and submitting patches, the docs are constructed using ReST and Sphinx (so there's some amount of markup to understand), and patches should be supplied as diffs against trunk. Take a look at any of the docs tickets that have a patch if you want examples.
I saw your other ticket, and agree that documenting both subjects are separate but related tasks. Thanks for opening that.
Regarding things inherent to Python, I agree about making the docs as easy as possible for newcomers, but there's a line at which we're no longer explaining Django, we're explaining Python--and that's not the goal. But to be specific to this case, if you want to sneak in a line in these docs that says something like "Don't forget to import the class you wish to receive signals from unless it's defined in the same file." then that's the beauty of being the person who writes the patch ;-)
comment:12 Changed 6 years ago by
comment:13 Changed 5 years ago by
Change UI/UX from NULL to False.
comment:14 Changed 5 years ago by
Change Easy pickings from NULL to False.
Quoting the docs: "sender: The intermediate model class describing the ManyToManyField. This class is automatically created when a many-to-many field is defined; you can access it using the through attribute on the many-to-many field.".
So, to my reading, it is explicitly mentioned. If you want to suggest an alternate wording, please reopen with a patch that contains draft text.
|
https://code.djangoproject.com/ticket/13586
|
CC-MAIN-2017-09
|
refinedweb
| 1,416
| 65.56
|
C being prompt for us to input
Let’s open it in IDA and see what we get!
First, we need to look for the main function. This is simple because we can start at the entry point and look for 3 push calls followed by a function call. 96.69% of the time, this function is main, and in this case, it is sub_411AE0.
Pretty straightforward function! Main is calling CreateThread, and this thread is going to execute the code at StartAddress.
Let’s dive into this function! First, we see that this function makes a called to sub_407850. If you look into this function, you will see a call to IsDebuggerPresent. We can tell that this function is going to check if the code is being ran in a debugger. If it is, it might terminate or something.
Following this, we see a bunch of GetModuleHandleA, but we don’t see any call to the modules being returned. Therefore, I just ignored it when looking at it!
This is the interesting part of the code. Earlier, we saw that the result of sub_407850 is stored in eax as 1 if we are using a debugger, and then this value in eax is stored inside esi.
Here, we are testing if esi is 0 or not. If it is not, we branch to loc_410921. If you execute the code through IDA, you will see this. It seems like we want to avoid branching to this section.
Also, from earlier when we ran it, it seems like the code branch to loc_1207C9 to bring all of those dialogs. We might want to avoid this branch too. There are a few checks that we need to bypass.
Seems like it’s calling GetSystemTime and read the system time into the buffer stored at esi. This buffer will be a struct of SYSTEMTIME. From there, we can assume that [esi] = wYear, [esi + 2] = wMonth, and [esi + 6] = wDay. The code is checking if the year is 0x7D0 which is 2000, and month and day are 1.
We can simply use OllyDBG to patch this executable and solve it!
First, we need to change the debugger check into a bunch of 0x90 (NOPS) so we ignore this jump completely.
test esi, esi jnz loc_120921
Second, we need to change the date to the current time on the system. Currently, it is 07/06/2020 in my machine, so let’s change the checks to that. Here is how I patch the executable.
After extract the newly patched executable, we can run it and the flag is given!!
2. Roulette
I did not solve this challenge during the time of the CTF, but I came back and worked on it!
This is the prompt.
This challenge seems to have a roulette theme, but beside that, nothing much can be get from the prompt. When we run the executable, nothing shows up, which lets us know that we have to use a debugger for it. Let’s throw it into IDA!
First, it seems like we checking if argc is 2 or not, which means the executable takes in a command line parameter, and according to the prompt, it’s taking in the flag.
If the flag is given, we will branch to the right. sub_BB3180 is a special fast-call function that is used to obsfucate the function calling, making static analysis harder. However, after steping through the code, I notice that this returns a function address into eax depending on the value of edx and ecx.
First, it’s calling sub_BB32D0. This function makes a series of calls using the obsfucating method above, but generally, it looks something like this. The calls are GetModuleFileNameA, GetLastError, and CreateFileA. Basically, it’s checking the executable’s existence! We don’t need to worry much about this.
Next, it’s calling GetModuleHandle with a null parameter, which will returns the handle to the current executable.
Then, it makes a call to sub_BB33A0. This function took me a while to process, and here’s the code in BinaryNinja.
004033b4 int32_t __saved_ebp 004033b4 int32_t* ebp_1 = &__saved_ebp 004033be int32_t eax_1 = *data_406004 ^ &__saved_ebp 004033d7 unimplemented {punpcklbw xmm0, xmm0} 004033de unimplemented {punpcklwd xmm0, xmm0} 004033e7 int32_t var_20 004033e7 int32_t var_54 = &var_20 004033e8 unimplemented {pshufd xmm0, xmm0, 0x0} 004033f9 if (sub_403180(0x6ddb9555, 0x60afc95d)(file_handle) != 0) // getFileSize(file_handle) 00403401 int32_t curr_file_size = var_20 00403419 int32_t heap_handle = sub_403180(0x6ddb9555, 0x36c007a2)(4, curr_file_size) // GetProcessHeap // rtlAllocateHeap(heap_handle, HEAP_GENERATE_EXCEPTIONS, file_size) 0040342b void* heap_pointer = sub_403180(0x1edab0ed, 0x3be94c5a)(heap_handle) // if heap_pointer != null and ReadFile(file_handle, heap_pointer, curr_file_size, ...) // Read file into heap 00403454 if (heap_pointer != 0 && sub_403180(0x6ddb9555, 0x84d15061)(file_handle, heap_pointer, curr_file_size, 0, 0) != 0) 0040345c int32_t PE_header_offset = *(heap_pointer + 0x3c) // 0x3c of the file = offset to PE header // size_of_header - code base? 00403466 void* esi_3 = *(PE_header_offset + heap_pointer + 0x54) - *(PE_header_offset + heap_pointer + 0x2c) 0040346a *(PE_header_offset + heap_pointer + 0x28) = what_is_this // move arg2 into PE entry point. NOTE: WHAT IS ARG2?? 0040347b sub_401010(0x405130) // vfprintf(FILE * stream, const char * format, va_list arg ); 0040348a int32_t ecx_1 = 3 0040348f void* eax_11 = esi_3 + what_is_this + 0x20 + heap_pointer 00403491 int32_t temp0_1 00403491 do 00403491 eax_11 = eax_11 + 0x40 00403498 unimplemented {pxor xmm0, xmm1} 0040349c *(eax_11 + 0xffffffa0) = *(eax_11 + 0xffffffa0) 004034a4 unimplemented {pxor xmm0, xmm1} 004034a8 *(eax_11 + 0xffffffb0) = *(eax_11 + 0xffffffb0) 004034b0 unimplemented {pxor xmm0, xmm1} 004034b4 *(eax_11 + 0xffffffc0) = *(eax_11 + 0xffffffc0) 004034bc unimplemented {pxor xmm0, xmm1} 004034c0 *(eax_11 + 0xffffffd0) = *(eax_11 + 0xffffffd0) 004034c4 temp0_1 = ecx_1 004034c4 ecx_1 = ecx_1 - 1 004034c4 while (temp0_1 != 1) 004034df int32_t eax_13 = sub_403180(0x6ddb9555, 0x36c007a2)(4, 0x104) // getProcessHeap() 004034f1 int32_t temp_file_name = sub_403180(0x1edab0ed, 0x3be94c5a)(eax_13) // rltAllocateHeap // GetTempFileName("routlette", ) 0040351b if (temp_file_name != 0 && sub_403180(0x6ddb9555, 0xea86aa5d)(0x405148, 0x40513c, 0, temp_file_name) != 0) {"roulette"} // CreateFile() 00403542 int32_t temp_file_handle = sub_403180(0x6ddb9555, 0x687d20fa)(temp_file_name, 0xc0000000, 3, 0, 4, 0, 0) // if temp_file_handle != INVALID_FILE_HANDLE and WriteFile(temp_file_handle, heap_pointer, curr_file_size) != 0 0040357b if (temp_file_handle != 0xffffffff && sub_403180(0x6ddb9555, 0xf1d207d0)(temp_file_handle, heap_pointer, curr_file_size, 0, 0) != 0) 00403576 sub_403180(0x6ddb9555, 0xfdb928e7)(temp_file_handle) // CloseHandle(temp_file_handle) 00403591 int32_t process_heap_handle = sub_403180(0x6ddb9555, 0x36c007a2)(0, heap_pointer) // GetProcessHeap() 0040359e sub_403180(0x6ddb9555, 0x4b184b05)(process_heap_handle) // HeapFree(proces_heap_handle) 004035b9 return sub_4037cb(eax_1 ^ &__saved_ebp, ebp_1, arg3, var_54) 004035bc exit(status: 1) 004035bc noreturn
Let’s break it down. First, using the file handle, it calls GetFileSize to get the size of this executable. Then, it calls GetProcessHeap and RtlAllocateHeap to allocate a buffer of the size we just got.
It will attempt to read the entire file into this heap buffer, and change the entry point of this executable in the buffer into some value. Next, it will xor the block of size 0x120 bytes with the flag[40] character. Afterward, it calls GetTempFileName and CreateFileA to create a temporary file, and calls WriteFile to write the executable inside the buffer into this temp file.
Overall, we can see what they are doing. They change the entrypoint to a block of code, encrypt the block with the 41th character of our flag. Next, we see main calls the function sub_BB35D0 to check the flag.
This function is huge, so I’m not gonna show it. Basically, it’s creating a string “./temp_file our_flag” (depending on what the name of the temporary file and our flag is), calls CreateProcess to execute this temporary file with our flag as the command line argument.
Then, it will calls WaitForSingleObjectEx to wait for this process to end and calls GetExitCodeProcess. This exit code must be 0 in order for everything to works, and this means that our temporary file must execute and exit normally.
This is a problem because the block of code at the entry point was xor-ed with our flag’s character, so it won’t be making much sense, and will not exit properly by executing invalid code. We must make the xor-ed code result valid code.
Through PEid, we can see that the entry point of this temp file is 0x2FE0, and we must make the code at this entry point work. The simplest method is to make the first byte at this point 0x55, which is
push ebp. This instruction is the typical starting instruction or any function, so let’s try that.
The first byte at 0x2FE0 of the original code is 0x38, and we need to xor it with something to make it 0x55. Since XOR is reversible, we can calculate this by xor-ing the original code and the result together.
0x38 ^ 0x55 = 0x6d, and in ASCII, 0x6d is the character ‘m’.
Let’s try making our flag ‘mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm’, which is 50 ‘m’. We only care about flag[40], and the rest does not matter. Let’s run it and see what we get for the temporary code.
It looks perfect like a legit function!! Let’s see what it’s executing here. First, it’s calling GetCommandLineA to retrieve the flag from the command line argument. Next, it calls the function sub_4B32D0 to do the existence checking like the parent executable. sub_4B33A0 is the same function to generate the temp file as above.
One thing special is that instead of using flag[40] to perform bitwise XOR, it’s using 0x13 on line 0x300E
movzx ecx, byte ptr [edi+13h]. It seems like this number will change everytime we generate a new file. This makes sense because it seems like we need to fixed our flag ‘mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm’ at one index at a time, with the first time being 40 and this time being 0x13.
This might recursively calls for a lot of time, and we can perform our XOR calculation to change our flag the same way.
We know that the index of every file is at an index of 0x3011 - 0x2FE0 + 1 or 0x32 constant, and this should be easy. We can write a simple python script to recursively do this.
from __future__ import print_function import sys import os.path import pefile import glob, os, os.path from shutil import copyfile, move from threading import Thread import subprocess from time import sleep current_flag = [] # fill flag up with 50 'm's curr_flag = "m" * 50 for i in range(50): current_flag.append(curr_flag[i]) # capture temp file and write it into file "file_name" def copy_tmp_file(file_name): done = False while not done: for temp_file in glob.glob("*.tmp"): file_size = os.path.getsize(temp_file) if file_size > 200: copyfile(temp_file, file_name) done = True break # return entry point of executable def find_entry_point_section(pe_file, entry_point): for section in pe_file.sections: if section.contains_rva(entry_point): return section return None def get_index_of_flag(file_path): current_index = 0 pe_file = pefile.PE(file_path, fast_load=True) # Acquire entrypoint for PE entry_point = pe_file.OPTIONAL_HEADER.AddressOfEntryPoint code_section = find_entry_point_section(pe_file, entry_point) if not code_section: return # Get bytes at the section code_at_start = code_section.get_data(entry_point, 0x32) # Get last opcode (it contains the index) current_index = code_at_start[-1:] current_index = int.from_bytes(current_index, "little") - 1 print('Index:', current_index) pe_file.close() return current_index def get_first_opcode(file_path): current_opcode = 0 pe = pefile.PE(file_path, fast_load=True) # Acquire entrypoint for PE eop = pe.OPTIONAL_HEADER.AddressOfEntryPoint code_section = find_entry_point_section(pe, eop) if not code_section: return # get first byte at entry point code_at_start = code_section.get_data(eop, 1) # Get first opcode bad_opcode = code_at_start[0] print('Opcode:', hex(bad_opcode)) pe.close() return bad_opcode def main(): capture_file_thread = Thread(target=copy_tmp_file, args=("current.exe", )) capture_file_thread.start() subprocess.call(["d", ''.join(current_flag)], executable="roulette.exe", stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) sleep(0.5) try: while True: # Get index of current exe current_index = get_index_of_flag("current.exe") # Capture tmp file when it's being generated and copy it to "temporary.exe" capture_file_thread = Thread(target=copy_tmp_file, args=("temporary.exe", )) # we will use temporary.exe to read what is the opcode of the next one capture_file_thread.start() # Call current exe file, at this point, temporary.exe = new temp file subprocess.call(["d", ''.join(current_flag)], executable="current.exe") # Acquire first opcode from start function bad_opcode = get_first_opcode("temporary.exe") os.remove("temporary.exe") sleep(0.5) # Calculate character to get proper `push ebp` or 0x55 # opcode should be 0x55 in the end good_opcode = chr(bad_opcode ^ 0x55 ^ ord(current_flag[current_index])) print('Replace flag[' + current_index + '] with ' + good_opcode) current_flag[current_index] = good_opcode print('Flag: ' + ''.join(current_flag)) # copy new temp file into _current.exe, then call current.exe, capture the temp file and move the previous temp file into # this current temp file capture_file_thread = Thread(target=copy_tmp_file, args=("_current.exe", )) capture_file_thread.start() subprocess.call(["d", ''.join(current_flag)], executable="current.exe") move("_current.exe", "current.exe") sleep(0.5) except Exception: # once we get no more file to read, we finish our flag. exit(print('Final Flag: ' + ''.join(current_flag))) if __name__ == '__main__': main()
After running the python script for a while, we will see something like this! The correct flag is cscml2020{p3_i5_my_f4v0rit3_r0ul3tt3_f0rm4t}.
Huge shoutout to 1byte for helping me figuring out how to write the script to check the files recursively!!
|
https://chuongdong.com/reverse%20engineering/2020/07/05/CSCML2020-RE/
|
CC-MAIN-2021-25
|
refinedweb
| 2,094
| 56.86
|
Created on 2015-05-14 11:58 by ronaldoussoren, last changed 2015-05-16 17:38 by eric.snow. This issue is now closed.
The script below creates a basic PEP 420 style package with a single module in it ('package.sub') and tries to import that module
With 3.5 the script runs without problems and prints 42 (as expected).
With a 3.5 (fresh checkout as of 2015-05-14) I get an SystemError:
$ python3.5 demo.py
Traceback (most recent call last):
File "demo.py", line 10, in <module>
import package.mod
File "<frozen importlib._bootstrap>", line 958, in _find_and_load
File "<frozen importlib._bootstrap>", line 947, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 657, in _load_unlocked
File "<frozen importlib._bootstrap>", line 575, in module_from_spec
File "<frozen importlib._bootstrap>", line 519, in _init_module_attrs
SystemError: Parent module '' not loaded, cannot perform relative import
#######
import os
os.mkdir('path1')
os.mkdir('path1/package')
with open('path1/package/mod.py', 'w') as fp:
fp.write('print(42)\n')
import site
site.addsitedir('path1')
import package.mod
I presume you meant that it works with 3.4?
The problem is right where the traceback says. Apparently there is a gap in the namespace package tests that I slipped through with my recent work to split out path-based import. I'll work up a patch.
Hmm, look like the test suite masks the issue due to the fact that importlib gets imported before running the applicable tests in test_namespace_pkgs.py. This causes _frozen_importlib.__package__ to get set properly, thus masking the problem.
The problem is the use of relative imports in importlib._bootstrap. The solution is to accomplish this in a different way.
Here's a fix. If I don't hear from anyone right away I'll push it in a few hours (or tomorrow morning).
New changeset 46b2c99121f5 by Eric Snow in branch 'default':
Issue #24192: Fix namespace package imports.
I can confirm that this fixes the problem I was having, both for the sample code I posted and for the real codebase I extracted this from.
Thanks.
Great! The buildbots are happy too. :)
|
https://bugs.python.org/issue24192
|
CC-MAIN-2018-30
|
refinedweb
| 354
| 70.5
|
Opened 4 years ago
Closed 4 years ago
#16126 closed Cleanup/optimization (fixed)
please add information on rendering DELETE checkbox manually for formset
Description
<form method="post" action=""> {{ formset.management_form }} {% for form in formset %} {{ form.id }} <ul> <li>{{ form.name }}</li> <li>{{ form.age }}</li> <li>{{ form.DELETE }}</li> <!-- ** Something like this ** --> </ul> {% endfor %} </form>
Attachments (3)
Change History (12)
comment:1 Changed 4 years ago by aaugustin
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Accepted
- Type changed from Uncategorized to Cleanup/optimization
comment:2 Changed 4 years ago by Aleksandra Sendecka <asendecka@…>
- Owner changed from nobody to ethlinn
- UI/UX unset
Changed 4 years ago by Aleksandra Sendecka <asendecka@…>
comment:3 Changed 4 years ago by anonymous
I would also add a check for can_delete something like
{% if formset.can_delete %} {{ form.DELETE }} {% endif %}
And maybe, if it isn't out of scope add the same docs for can_order and form.ORDER
comment:4 Changed 4 years ago by rasca
Oups, that was me :)
Changed 4 years ago by Aleksandra Sendecka <asendecka@…>
patch with "if" and with information about can_order
comment:5 Changed 4 years ago by rasca
Checking in more detail, I think this should be in and in . And maybe and example in each?
And in can_delete can link to formsets/#can-delete.
What do you think?
comment:6 Changed 4 years ago by Aleksandra Sendecka <asendecka@…>
There is one more place where it fits well:
Changed 4 years ago by Aleksandra Sendecka <asendecka@…>
changes moved to formset to "Using a formset in views and templates" section. Link from previous location added in "See also"
comment:7 Changed 4 years ago by oinopion
- Triage Stage changed from Accepted to Ready for checkin
comment:8 Changed 4 years ago by oinopion
- Keywords dceu2011 added
comment:9 Changed 4 years ago by jezdez
- Resolution set to fixed
- Status changed from new to closed
rendering manually can_delete parameter in template
|
https://code.djangoproject.com/ticket/16126
|
CC-MAIN-2015-22
|
refinedweb
| 328
| 56.18
|
NetHackWiki:Community Portal/Archive4
This page contains old sections from NetHackWiki:Community Portal. If you want to carry on talking about these topics, post a new section on the current Community Portal page. This page is intended to be a static archive.
Contents
- 1 Cultural references
- 2 NetHack sources on NetHackWiki and Special:Random
- 3 Monsters which are also starting races
- 4 The problem with MR
- 5 Modifying NetHack
- 6 Weapon damages and min-max values, use template?
- 7 Monster (Pet) equipment - info box template?
- 8 Theme change
- 9 Engraving and Elbereth
- 10 Disambiguation Template:for2
- 11 Long reply above
- 12 Interhack
- 13 Article Number Count
- 14 Addicted to NetHackWiki?
- 15 Calling for help for the Civilization IV wiki
- 16 Modifying wikia default templates
- 17 Handling variants
- 18 Wikia Spotlight
- 19 Recent changes patrol
- 20 Variant specific information
- 21 Is NetHack Alive?
- 22 Slashem Namespace
- 23 Template for Encyclopedia
- 24 New skin
- 25 Monster pronunciation
- 26 New "Wikia" aka "Oasis" skin: Problems, legal restrictions, and tweaks
Cultural references
Is there any kind list (like in en-wiki [1]) or something else here for cultural references in NetHack? I haven't found one myself, and it would really help me with the Finnish counterpart in Wikipedia.
[2] - Wikiproject NetHack in Finnish Wikipedia
[3] - My usersite in Finnish Wikipedia
- No, I don't think we have an equivalent list. But just browse the articles, they've got links to single Wikipedia articles for more background of their topics. --ZeroOne 23:08, 14 March 2007 (UTC)
- Thank you for information.
- I just wanted to mention that the closest list we have on NetHackWiki right now is in the article for hallucinatory monster, which lists all the monsters you will see if you're hallucinating (and often these monsters are direct references to pop culture). NetHack encyclopedia should really mention some of the cultural references (or at least the literature the encyclopedia quotes from). I've added the link you provided into the NetHackWiki entry for the in-game encyclopedia. Thank you. :) —Shijun 20:31, 9 August 2008 (UTC)
NetHack sources on NetHackWiki and Special:Random
IMO, Special:Random is not very useful for most users, because there's so many source code articles, and those simply aren't interesting for the majority of people.
I talked with some admins on the #wikia irc channel, and asked if there's a way to prevent the random page-link from showing the source code articles. Answer: move the pages to another namespace. The end result was that there's now a new namespace on wikia: Source
I suggest we move all the source code to the Source -namespace. --Paxed 17:13, 23 March 2007 (UTC)
- There are, of course, a lot of source code pages. Your idea is a good one, but we should get a bot to do the moves, to complete the task in a reasonable time and avoid flooding the Recent Changes list. --Ray Chason 22:14, 9 May 2007 (UTC)
- I made a bot-readable list of source code articles to help give this idea some impetus :-) [4] It doesn't include everything from Category:Source code, just those matching /.*\.[ch]$/ (which I think is what we want?) Let me know on User talk:GreyKnight if you want something different. --User:GreyKnight(as anon) (PS: will be back on IRC sometime soon, see y'all there!)
Then the problem was to find someone with a bot that would move the pages. I discussed this with Paxed in the #nethack channel. I managed to configure a pywikipediabot to use User:Kernigh bot. I tested the bot by moving User:Kernigh/sandbox to User:Kernigh/sandcastle. Then Paxed converted GreyKnight's list into a shell script of python movepages.py -from:"x" -to:"y"; sleep 30 commands [5]. Before I run these commands, I need Wikia staff to give a bot flag to User:Kernigh bot to hide the huge number of moves from recent changes.
I now propose that User:Kernigh bot receive a bot flag, run the commands, thus moving the source code pages into the Source: namespace. Is this okay, or does someone not want this to happen? --Kernigh 21:26, 24 February 2008 (UTC)
- Sounds good to me. Now when I want to learn about something random in NetHack, all I have to do is hit alt-shift-x :) Fredil Yupigo 21:55, 24 February 2008 (UTC)
- I'm obviously all for this. --Paxed 07:14, 25 February 2008 (UTC)
- So when is this mass move going to happen? Fredil Yupigo 01:39, 2 March 2008 (UTC)
I requested the bot flag (through Special:Contact, with a reference to this section of the community portal) and received the bot flag. A few hours ago, User:Kernigh bot began to move pages. The bot sleeps 30 seconds between moves. So far, the bot seems to work correctly. --Kernigh 00:39, 4 March 2008 (UTC)
- There's also slashem sources on NetHackWiki, those should be moved too... here's a S'em 0.0.7E7F2 move script: [6] --paxed 15:57, 4 March 2008 (UTC)
Paxed, your script has extra lines between the .h and .c moves. --Kernigh 16:22, 4 March 2008 (UTC)
Okay, I will have User:Kernigh bot run the script, probably at Friday 7 March. --Kernigh 15:13, 5 March 2008 (UTC)
Special:Random still seems to choose pages in the Source-namespace. Apparently only staff can set what namespaces Special:Random chooses from (by marking them content or not-content), and if we decide to exclude Source, then it also means Source-pages will not count towards article count. I think we should ask the staff to exclude Source from Special:Random. --paxed 17:08, 24 April 2009 (UTC)
- No objection from me. While there are a few source files with rich annotations, most of them don't deserve to be counted as real articles anyway. It will be nice to have a useful random-page feature. -- Killian 12:52, 25 April 2009 (UTC)
Source-namespace has now been excluded, thanks to Uberfuzzy --paxed 06:54, 30 April 2009 (UTC)
Monsters which are also starting races
My concern is that these are handled inconsistently. Most notably the standard dwarf (monster) h is missing altogether. I am hoping someone responsible can decide upon a suitable convention and apply it across NetHackWiki.
The dwarf (monster) todo page I created provides the relevant links. I apologise for the fact I couldn't fix it myself.--PeterGFin 14:27, 17 June 2007 (UTC)
- I've taken a look at this. Basically, all starting races have deeply ambiguous meanings, embracing all of the following:
- A race (obviously)
- A class (or part class) of monsters
- A monster attribute (M2_HUMAN etc.) used to determine cannibalism and own-race sacrifice
- A monster, sometimes used mainly for corpses, sometimes not.
- The meaning required is determined by context, and often assumed implicitly, although this can be misleading; for example, does the phrase "human or elf" include Kops? The answer is, it depends on whether you are looking at the monster class, or the monster attributes. So @ ignore all Elbereth - they are human or elf, Kops only respect Elbereth when you stand on it - they have the human monster attribute. But "human or elf", meaning @ is usually linked as "[[human]] or [[elf]]", and none of the meanings at either page encapsulated what @ is (until I recently changed "Human", but you're still out of luck at "Elf".)
- In my opinion, this means that human, elf, dwarf, gnome and orc should all be disambiguation pages delineating these various meanings and pointing enquirers in the right direction. In addition, we need a proper page for each monster class - that is, monsters who share the same symbol. Internally, NetHack uses this symbol to determine behaviour in certain cases. Classes such as human or elf, wraith and orc (includes goblin and hobgoblin) currently have no such page. All these example classes are used internally to determine game behaviour at some point.
- Human comes closest currently to how I see things should be handled, although a page for @ human or elf does not currently exist (@ is essentially a disambiguation page).
- --Rogerb-on-NAO 22:41, 18 June 2008 (UTC)
The problem with MR
For the MR topic, it records only the MR of the player and not of the monster. I have no idea what base MR does for monster (well, some ideas, but not enough). Someone ought to add something about that. RegalStar 18:49, 6 January 2008 (UTC)
- I saw this too and added Magic resistance (monster), and put it in Template:Otheruses at the top of Magic resistance recently. Hope it's useful.
- --Rogerb-on-NAO 15:46, 7 June 2008 (UTC)
Modifying NetHack
Can someone make a small guide? There's only one guide I can find, , but it doesn't tell you how make a new class. Also, I need to know how to use makedefs. I try to run it, but it flashes for a second saying it has invalid arguments (0). It doesn't even say how to use it. (FYI, my source and tools are installed in C:\nh343\ and C:\MinGW\)
By-the-way, here's the code I'm using:
Roles.c, under the bit about ranger:
/* START: BETA: Detective */ { {"Detective", 0}, { {"Detective", 0}, {"Detective", 0}, {"Detective", 0}, {"Detective", 0}, {"Detective", 0}, {"Detective", 0}, {"Detective", 0}, {"Detective", 0}, {"Detective", 0} }, "God", "God", "God", /* God */ "Det", "someplace 1", "someplace 2", PM_RANGER, NON_PM, PM_BOMB_DOG, PM_ORION, PM_HUNTER, PM_SCORPIUS, PM_FOREST_CENTAUR, PM_SCORPION, S_CENTAUR, S_SPIDER, ART_LONGBOW_OF_DIANA, MH_HUMAN|MH_ELF|MH_GNOME|MH_ORC | ROLE_MALE|ROLE_FEMALE | ROLE_NEUTRAL|ROLE_CHAOTIC, /* Str Int Wis Dex Con Cha */ { 13, 13, 13, 9, 13, 7 }, { 30, 10, 10, 20, 20, 10 }, /* Init Lower Higher */ { 13, 0, 0, 6, 1, 0 }, /* Hit points */ { 1, 0, 0, 1, 0, 1 },12, /* Energy */ 10, 9, 2, 1, 10, A_INT, SPE_INVISIBILITY, -4 }, /* END: BETA: Detective */
Roles.c, above the knight and samurai's hello thing:
case PM_DETECTIVE: return ("Here's the thing"); /* -- A. Monk */
Monst.c, under the large dog code:
/* START: BETA: BOMB DOG */ MON("bomb dog", S_DOG, LVL(6, 15, 4, 0, 0), (G_GENO|1), A(ATTK(AT_BITE, AD_PHYS, 2, 4), NO_ATTK, NO_ATTK, NO_ATTK, NO_ATTK, NO_ATTK), SIZ(800, 250, 0, MS_BARK, MZ_MEDIUM), 0, 0, M1_ANIMAL|M1_NOHANDS|M1_CARNIVORE, M2_STRONG|M2_DOMESTIC, M3_INFRAVISIBLE, HI_DOMESTIC), /* END: BETA: BOMB DOG */
Monst.c, under the ranger code:
/* END: BETA: Detective */ MON("detective", S_HUMAN, LVL(10, 12, 10, 2, -3), G_NOGEN, A(ATTK(AT_WEAP, AD_PHYS, 1, 4), NO_ATTK, NO_ATTK, NO_ATTK, NO_ATTK, NO_ATTK), SIZ(WT_HUMAN, 400, 0, MS_HUMANOID, MZ_HUMAN), 0, 0, M1_HUMANOID|M1_OMNIVORE, M2_NOPOLY|M2_HUMAN|M2_STRONG|M2_COLLECT, M3_INFRAVISIBLE, HI_DOMESTIC), /* END: BETA: Detective */
How would I make it so a class has a revolver (the archilogiest had one, or am I just thinking that Indy had one, so Archy must have one? XD) and wipes (which I'd have to program in myself).
Also, are there any really interesting points in the code? Like, I'd like to keep the game from deleting your save when you die.
TBF02 06:26, 23 February 2008 (UTC)
I've played as Archeologist a few times, and to my knowledge there is no revolver, but there is a bull whip. if you dont want the save deleted, copy it to a different folder before reopening it.— Preceding unsigned comment added by NerdLord (talk • contribs)
- If you want firearms, then SLASH'EM is for you. Be aware that "SLASH'EM wants you dead." And please don't come claiming an ascension if you've save scummed.--Ray Chason 22:17, 7 May 2008 (UTC)
A revolver and wipes couldn't be too hard to hack. Just give your detective a modified wand of magic missile and towel.
Weapon damages and min-max values, use template?
I saw someone added the minimum and maximum damages that Vorpal Blade and Battle-axe could do to their artifact/weapon template. I decided to write a template that could calculate those automagically given the d notation: See User:Paxed/Template:dice. Opinions, do we want to use it? (I'm obviously all for it) --paxed 15:19, 6 March 2008 (UTC)
- paxed, that's a really cool template! I would love to see that used in the various monster infoboxes. I think this should be an official NetHackWiki template! :) —Shijun 01:45, 9 August 2008 (UTC)
Monster (Pet) equipment - info box template?
I'm new to contributing: I'm not sure exactly how the info punched into the monster box on the right comes out the way it does. Take the entry for Djinni: the box at the right has an "other attributes" section that lists in bullet points that a Djinni has a head, arms, and a torso, that it can pick up weapons, etc., but in the edit section it just has some values set.
What I'd like to see is very specific information about exactly what equipment a monster can equip, especially after it has been tamed. For example, I had a pet Djinni, and it could wear a shield and gloves as well, and I believe it was equipping a cloak, but it wouldn't take any armor. I would have thought something that can wear a cloak could wear body armor. Without a wand of probing, I couldn't tell if it had something cursed on or if it simply couldn't equip it.
It'd be nice to see some consistent section on what equipment a monster will use as a pet, something like:
Centaur Can equip: Weapon Shield Helmet Gloves Amulet of Lifesaving Can use: Unicorn Horn Potion of Gain Level
Would it be possible to have the exact information on what a pet can equip converted from those values entered in the template - are these values/flags consistent, do they apply across the board? Or does every monster have it's own equipment rules?
If the latter is true, and it would be too complicated to work into the template, can anyone point to the best resource where I can find specifics on what a pet will wear and use? I'm thinking about adding an "As a Pet" section at the bottom of monster articles as I fool around with Polymorph traps. Floatingeye 04:15, 20 March 2008 (UTC)
- The monster template is at Template:Monster. But the thing you're looking at is actually an inner template, Template:Attributes. The things in that template are lifted straight from the source code. Source:Monflag.h contains all the flags. Take a look at the djinni: Monst.c#line2782. The flag "humanoid" says that your djinni has all the usual human bits, so it is a mystery why he wouldn't wear armor.
- Templates are tricky, so if you want to improve them, I suggest trying to talk to Shijun or Paxed, since they've worked on them recently. #nethack on IRC is probably a good way to find people.
- -Mniot 05:42, 20 March 2008 (UTC)
- Floatingeye, I think your djinni couldn't wear the armor because it didn't take off the cloak first (you always need to take off the cloak first before you can wear armor; obviously the monster AI isn't advanced enough to figure this out).
- And yes, I agree with Mniot... templates are tricky (and sometimes I have trouble coding them). There could definitely be more user-friendly documentation about templates though. ;)
Theme change
What the heck happened to the theme? How do I get the old look back? -- Killian 15:43, 10 April 2008 (UTC)
- User:Kirkburn changed it. Did he talk with the sysops/whatever of NetHackWiki about it first?! --paxed 16:52, 10 April 2008 (UTC)
- I'll use Special:Contact to complain about this, maybe others should do so too... --paxed 18:00, 10 April 2008 (UTC)
- He didn't contact me at any rate. I could change it back, if there's a clear consensus for doing so. Anyway, if you're logged in, you'll see a small button marked MORE next to your name at the top right. Click that, and select "My preferences". (This link should also work.) Click the Skin tab on the resulting screen, and you can change the theme. The old look is "MonoBook" and you'll find it toward the bottom.--Ray Chason 18:20, 10 April 2008 (UTC)
- I've changed the default theme back to Slate. As the discussion should have been: is there anyone who would like to see us switch to Monaco? Eidolos 20:55, 10 April 2008 (UTC)
- I've deleted the offending setting altogether, so now the user's Skin setting will be respected whether or not s/he checks the "allow admins to override" setting. I've confirmed we're still back to MonoBook when not logged in. I've also set my own setting to Monaco Sapphire -- I rather like the new skin but the Slate theme strikes me as overly stark. Sapphire at least has similar colors to the MonoBook skin. I might try experimenting with CSS, to get a Monaco that looks reasonably close to MonoBook -- it has some features that I think are neat. Having a "Problem reports list" on my sidebar will make that feature a bit more useful.--Ray Chason 21:46, 10 April 2008 (UTC)
See Talk:Main Page#Monaco skin for more. Kirkburn (talk) 18:28, 10 April 2008 (UTC)
Ray, thank you for looking into it. Sapphire could be a better fit - I went for slate due to the relatively neutral tones. Remember users can choose their own skins, this would mainly be a change for what anonymous users see - monaco has a lot of improvements for "viewers" along with editors. Kirkburn (talk) 17:19, 11 April 2008 (UTC)
Anyone following this topic may be interested in reading If you prefer the old theme. —Shijun 08:07, 10 August 2008 (UTC)
Engraving and Elbereth
Almost the entire article Engraving is repeated almost verbatim in Elbereth.
The danger of this is that editors update only one page, and the info in both gets out of sync. This has happened in this case.
Clearly these should be merged; I would just go ahead with this, but I don't want to make major changes to a featured page without some discussion.
There are a few points of view I can think of here:
- 1. Although in principle you can engrave anything, in practice little else is ever engraved than Elbereth or 'x' when illiterate. (There is some argument for engraving other things when identifying wands that might be teleportation). Thus Engraving should be merged into Elbereth and Engraving become a redirect to Elbereth. This would leave the Elbereth page largely untouched.
- 2. Large sections of the Elbereth page are really about the detailed mechanics of Engraving. All these details belong there and should be moved. The Elbereth page can simply point there as necessary.
- 3. Engraving and Elbereth are important topics that deserve their own, unpolluted pages. However, strategy decisions during play are important. An Elbereth strategy page or section should be created that discusses the interactions and how they affect play.
No doubt there are other possible viewpoints/solutions that I haven't thought of.
Things are somewhat complicated by the fact that, although it is a featured article, Elbereth does not seem to follow the Style Guide particularly well; in particular, it merges fact and comment throughout.
Personally I favour option 3, separating the comment in the current Elbereth page into a strategy section.
What do others think?
--Rogerb-on-NAO 16:04, 7 June 2008 (UTC)
- Since it's been a month now with no responses I'll take it I should just go ahead and do whatever I think best. I'll do just that whenever I get round to it. --Rogerb-on-NAO 22:53, 10 July 2008 (UTC)
Disambiguation Template:for2
On Gender, I had need to disambiguate 3 links for the page itself and 2 redirects; neither Template:for nor Template:otheruses could do this. I created Template:For2 as a general purpose tool, after wikipedia:Template:for2 (documented at wikipedia:Wikipedia:Hatnotes#For (other topic)).
--Rogerb-on-NAO 23:10, 16 June 2008 (UTC)
Long reply above
Just in case you missed it, I put in a sizeable reply to Monsters which are also starting races above.
--Rogerb-on-NAO 22:50, 18 June 2008 (UTC)
Interhack
Interhack an earlier attempt at multiplayer nethack. The project was put on hold in 2001 due to time constraints. While the latest version was 1.0.5 - it could barely be called complete. In order to maintain the turn-based aspect of Nethack, the developers came up with the idea of "sureal-time". In the original algorithm, monsters were "tied" to a particular player on the level. When that player moved, those monsters also moved. Unfortunately the developers still resorted to real time movement when players were in close proximity.
Of course "sureal-time" in 2008 would work something like this:
* Monsters are tied to the nearest player and move in conjunction with that player. * Objects have an "age" - as a player travels around a level, objects age. As objects get older, they disappear etc. This prevents the following scenario: Player A and B are in the same room. A is in dire need of healing. B runs off and gets a potion and returns with the bottle. * When a monster is attacked by a player they are not tied to, they can "react" to the other attacker.
The key problem with multiplayer was not a turn-based algorithm that would work. Multiple players introduce the need for new data structures, and effectively a complete re-write of Nethack code. Interhack was written in C++ as this was an ideal language for a world based on objects. And re-writing the code is no small task.
...
Shouldn't this wiki mention Interhack? The multiplayer nethack, I mean. I know the project got abandoned, but it still had a stable 1.0.5 release in 2001. — Preceding unsigned comment added by 84.121.141.24 (talk • contribs)
- As it was a NetHack variant, I should think so. Now all we need is for someone to take it upon themselves to add it (looks at the anonymous OP) --Rogerb-on-NAO 19:24, 13 July 2008 (UTC)
- Interhack continues to be developed and is currently in an Alpha verion: — Preceding unsigned comment added by 114.129.168.15 (talk • contribs) 2009-09-19
Article Number Count
For some reason, the number suddenly jumped from what I distinctly remember to be 1750 to around 3400. Any explanation? Fredil Yupigo 23:22, 27 September 2008 (UTC)
- The Charmed Wikia, which I also frequent and sometimes write for, doesn't seem to have experienced a similar jump. What distinguishes NetHackWiki, however, is the large number of articles in the Source code namespace. The prior article count included only articles in the main namespace that were not redirects. I suspect that either the new article count is including non-main-namespace articles, or it is including the redirects left behind from when the source code archives lived in the main namespace.--Ray Chason 17:46, 28 September 2008 (UTC)
Addicted to NetHackWiki?
I think I've read all the articles, excepting the source code... when I press random article 100 times, there isn't one I haven't read... o.O Fredil Yupigo 21:26, 10 October 2008 (UTC)
Calling for help for the Civilization IV wiki
Hello people. This post does not really relate to NetHack, but I thought I'd ask for your help anyway. I recently got the Civilization IV game and subsequently (today) became an administrator of the Civ4 Wiki at Wikia. I recon NetHack and Civilization are both games of patience and long-term planning, so I think some other NetHackers might also be Civ-enthusiasts. In case anyone is willing to help, join the wiki and find something to do. For one, all but one articles about individual units are missing. You may use the Keshik page as an example and start filling data for the other units ([8] is a good source). Or create articles about resources or amend the articles about technologies. Or you may just wish me luck doing all that by myself. ;) --ZeroOne 00:09, 13 November 2008 (UTC)
Modifying wikia default templates
We should modify at least MediaWiki:Newarticletext and MediaWiki:Edittools so they contain more NetHackWiki-related help and templates. (I put in some suggestions on the talk pages of those two templates). --paxed 16:41, 17 November 2008 (UTC)
Handling variants
I'm taking an interest in ZAPM following the /dev/null tournament, and have added a stub entry describing the most apparent similarities and differences. I am looking for some advice on how to manage some of the big changes - e.g. BUC is now "buggy, debugged, optimized" but is this worthy of separate pages? A redirect seems like a cop out to me. Also, there is little information (and no readily-accessible source) that I can easily dig in to, so I don't even know what NetHack version it is based off! I'll do my best, but before I go an pollute the namespace, I thought I'd seek a little advice. -- Kalon 00:29, 30 December 2008 (UTC)
- I think that for now everything ZAPM-related should be kept on the single ZAPM-page, if the page does not grow to be too large. In my opinion we should only create more new articles to only the most well established variants, namely SLASH'EM and maybe SporkHack, too. There's still plenty of room for improvement in both of those categories. —ZeroOne (talk / @) 01:39, 30 December 2008 (UTC)
Wikia Spotlight
I was thinking that it would be nice to get this wiki a spotlight with w:Wikia:Spotlights: "Wikia Spotlights are images that appear on each Wikia page that link to other Wikia sites." For that, the following conditions should be met:
-.
We have the {{welcome}} template that I have been using. Would you other guys and gals start using this too?
- The wiki should use the Monaco skin as the default.
I'm quite fond of the old MonoBook style we have, but what do you think? Have you overridden this choice and are you using the Monaco skin?
- The wiki should have at least 100 content pages, not counting stubs.
This is definitely fullfilled.
- The wiki should have a logo.
Yup, done.
- The main page of the wiki should have at least one picture, and clear links to the most important content.
No pics, but they are not really applicable to NetHack anyway... We do have clear links.
- The wiki should have a clear category structure to help readers navigate around the site. Every content page should be in a category.
I think we do have a clear category structure. Some pages might still need categorizing.
All the points above say that the wiki should do those, but it does not say that they must be fulfilled to get the spotlight. Thoughts? —ZeroOne (talk / @) 20:55, 12 February 2009 (UTC)
- I think the kind of pics that should be on NetHackWiki is screenshots. We don't really have a whole lot of them and I think they'll make some of the articles more clear. Unfortunately, I don't have free time to make some, but we could make getting screenshots a project here on NetHackWiki.
- Oh, and I haven't noticed the welcome template. I'll use it when I get some free time. :) —Shijun 21:48, 12 February 2009 (UTC)
- I just found out that the Spotlight has been installed and can be seen in other wikis:
Recent changes patrol
I asked for the Wikia staff to enable the Recent changes patrol feature, which they did. This helps us fight vandalism, as now every unchecked edit appears with a red "!" next to it. When you click the diff-link, there's a "Mark as patrolled" link which then removes the exclamation mark, thus signalling the other users that the edit was legitimate. Any comments? —ZeroOne (talk / @) 08:00, 27 February 2009 (UTC)
Variant specific information
Lately I've been source diving a lot in different variants of NetHack and would like to enter some of the knowledge into NetHackWiki. Especially that concerning how the variants have tackled some shortcomings of NetHack (e.g. pudding farming or boring Gehennom).
Now it is clear to me that large texts (like Lethes Gehennom) should be incorporated into the page of its variant or maybe even get their own article.
But smaller changes like how a variant tries to prevent pudding farming should probably go into a new section. How should that section be called? Variant behaviour? Variant modification?
And should a new category be added to the article? Like Variant information? --bhaak 09:15, 15 April 2009 (UTC)
- I asked around for roughly the same sort of guidance, and there isn't anything hard-and-fast, rules-wise. As a personal guide, I think that for notes within an existing page that don't have the content to warrant articles of their own, a section titled after the variant is sufficient - there are plenty of sections relating to SLASH'EM in other articles, for example. If you are covering a whole variant, a summary page with differences may be warranted - see my own (abortive) example at ZAPM. Just my 2zm, but it keeps the wiki looking "nice". Yuck, hate that word. -- Kalon 22:57, 15 April 2009 (UTC)
- You may have already found it, but we already do have an article about the Gehennom of the Lethe patch. Anyway, I'd start by writing a general article about the variant first. There, I'd describe the new features briefly and then I'd use the {{main}} template to link to the main articles, which would cover the topic in more detail. But that's just how I'd do it. Kalon has done great job with the ZAPM article. So far it all fits nicely into one page — breaking it into multiple pages would just hinder the readability. Of course, he has also reserved links into articles such as software engineer, where the subject can be discussed in greater detail. Now I'm just repeating what Kalon just said but for new sections, see how the Gehennom article treats SLASH'EM. If you were to add an explanation of, say, the Gehennom of Sporkhack, you should probably put the Sporkhack header and the SLASH'EM header under a Variants header. —ZeroOne (talk / @) 08:11, 16 April 2009 (UTC)
Is NetHack Alive?
Are a lot of people still playing the game and/or visiting Nethack? What is visit rate and edit rate on here? In particular, do questions get answered in a few days or less or is the community mostly dead? — Preceding unsigned comment added by 66.30.202.87 (talk • contribs) on 2009-05-19
- You can look here if you want to see the visit and edit rates on NetHackWiki. And yes, questions here do usually get answered within a few days. Look at this response for example. ;)
- I'm not sure if a lot of people are still playing the game. It depends on what you mean by "a lot". I hope someone else can answer this question. —Shijun 06:00, 20 May 2009 (UTC)
- The /dev/null/nethack tournament 2008 had 22,812 completed games played by 1,305 players, NAO has usually more than 400 games a day, the sourceforge statistics page shows more than 150,000 hits per month for nethack.org and more than 10,000 downloads per month.
- For the community, you should also look at RGRN and #nethack on freenode. I guess that's where most of the action is. This community portal is used much less than IRC or Usenet.
- NetHack sure isn't dead, but it isn't WoW either. Depends on your definition if this qualifies as "a lot". And as soon as I release my übervariant of NetHack, WoW might notice that the tides have turned ;-D —bhaak 07:41, 20 May 2009 (UTC)
- Even the devteam, though it has not uttered a line of code since 2004, does update their online bug list. But I personally think development of Nethack in part dead, in part superseded by Slashem. -Tjr 12:59, 20 May 2009 (UTC)
Thank you all for you responses. I am certainly not looking for WoW and have joined NetHackWiki and will contribute what I can to the community (though I have a lot to learn about formatting wikis). I have wanted to try SLASH'EM and checked out NetHackWiki's knowledge base a few months ago and found information on SLASH'EM sorely lacking... but this seems to have been remedied now so I'll try Vulture's Claw. Do you guys look down on people trying the fancy new interfaces? Anyway, nice to meet you all and thank again. DemonDoll 14:49, 20 May 2009 (UTC)
- I really like Vulture's, but I play tiles because I want to know the inventory letter and object description at a glance. -Tjr 15:06, 20 May 2009 (UTC)
Slashem Namespace
As Slashem pages proliferate, we will reach a point where roughly 1/3 of all pages either have a Slashem section or a "pagename (SLASH'EM)" counterpart. I think Slashem should have its own namespace instead for cleanlyness, and there should be a template such that Slashem pages #include the vanilla page by default. Let's reach a consensus. What do you think? -Tjr 15:14, 20 May 2009 (UTC)
- I love the idea but don't know what this "namespace" business is. Is there some way to toggle whether you want to see SLASH'EM or not so that it displays either the vanilla page or SLASH page? However, if that were done, the vanilla and SLASH pages might go out of sync in terms of information so perhaps better yet would be some universal toggle like that shows or hides a "In SLASH'EM:" section at the bottom of the articles that have them. Better yet (and this might be what you mean by namespace), a WikiSLASH encyclopedia. If so, I'm all for it. DemonDoll 17:03, 20 May 2009 (UTC)
Template for Encyclopedia
Perhaps we should make a template {{NethackEncyclopediaFormatting|content}} that fully formats the Nethack Encyclopedia paragraphs. I think the encyclopedia might look better black on light blue, in a script font (e. g. Apple Chancery), and with a box around it (e. g. similar to Wikipedia's {{divbox|green||<center>Content</center>}}) instead of the current typewriter font. Also, a template would/should automatically make sure appearance is consistent across pages while providing a single set of controls to fine-tune. Any opionion? Who could make such a template? -Tjr 03:55, December 31, 2009 (UTC)
- I had a somewhat similar idea, except the template would hold the content in addition to the formatting (which is a bit ambitious, I have to admit, and why I never got around to making the template). A formatting template is a better idea and easier to implement. I should be able to make it in the next few days or so. Though may I ask for a shorter name such as "Encyclopedia"? —Shijun 06:55, December 31, 2009 (UTC)
New skin
I've used the monaco skin to create a NetHackWiki styled skin - just copy and paste User:Zapwire/monaco.css to special:MyPage/monaco.css, clear cache, enjoy. Suggestions are welcome. --Zapwire (talk/blog/edits) 13:43, January 26, 2010 (UTC)
Monster pronunciation
Some people have difficultly saying monster names. Maybe we could include pronunciations for things? --Zapwire (talk/blog/edits) 16:47, February 1, 2010 (UTC)
- What exactly do you have in mind? .mp3 files spoken by the DevTeam? By native speakers? A transcription in IPA alphabet? (Who understands IPA anyway?) -Tjr 17:27, February 28, 2010 (UTC)
New "Wikia" aka "Oasis" skin: Problems, legal restrictions, and tweaks
What the proposed move means in practise
New address:
- More Nethack content on your screen.
- Less clutter, ads, and javascript.
- Faster loading time.
- Wikipedia-style skin.
- Hosted on the same server as NAO.
- Keep your old account, password, and edits
- Just log in with your wikia credentials if you have already edited here
- No unified login across wikia for new editors
- Almost all Wikia features keep working
- Rich text editor works, but not social network stuff, facebook, blogs.
- Ghost town at the old site, and Wikia will try to split the community
- Most incoming links already point to. That redirects here for now.
- Once Google ranks us above the old place, it will dry up. Expect 1-3 months.
- Respect for you, the Nethack community.
- Prediction: Wikia will become more and more abusive in the future.
Summary of the problems
WoWWiki discusses problems we also have. Especially bad is the wasted screen space. Wiki functionality navigation and social-network-ization come second.
What we can't do
From the staff blog:
-. ...
Ideas and solutions
Wikia has a very poor track record of fixing things, so we are on our own. Paxed has already clawed back a lot of wasted space and changed the unreadable color for text.
- Image attribution: a solution iff permitted
- A new logo: I think our logo should be less tall, wider, should read "Nethack" instead of "Wikia", and it should have a similar graphical theme as the old one to help brand recognition. Perhaps parts could be made clickable to hack in a make-shift navbar.
- Wasted vertical space at the top.: We aren't allowed to hide the crap. Somehow rearrange widgets beside each other?
- MediaWiki:Wiki-navigation needs to be updated. See our options, [9].
- Navigation sucks: Lots of cases, e. g. try viewing the article whose talk page you are editing. Basically, the only way to get around is to type in the URL. Can we site-wide customize "my tools"?
- Eyestrain From the cited WoWWiki page:".
- See below for Wikia's side of the eyestrain argument.
Moving away from Wikia
"Should WoWWiki leave Wikia" is definitely worth a read. Moving is perhaps not yet justified for us. Wikia would keep the old content; at best, we'd get a split in the userbase, and a shadow wiki left behind.. I'm sure Wikia will not make any concessions if we threaten. If we're lucky, we can get a copy-paste reply (though much the larger WoWWiki got some screen space). Tjr 22:20, October 28, 2010 (UTC)
- That could be handled in two ways: a) Site-wide notification that the nethack wiki has moved, or b) Just mirror the data from the nethack wiki, and resynch every N days or whatever.
- I talked with dtype, and as far as he's concerned, we could run a mediawiki on the alt.org server (and mirror the nethack wiki content there or whatever). The only problem is that I've never set up mediawiki, and I doubt I have the time to do that too... --paxed 18:04, October 30, 2010 (UTC)
- Friendly admin of the d20 NPCs wiki, here. I recently migrated away from Wikia with the Dungeons and Dragons wiki, and this is one of the only wikis on Wikia I still visit, and I think this content is perfect for the wiki environment, and am saddened by Wikia's insistence on moving towards a more "social networking" model. I am very familiar with MediaWiki as a wiki engine, and would be glad to help get this wiki set up with a new home, if it helps break away from Wikia. --MidnightLightning☇(talk) 04:27, November 6, 2010 (UTC)
- If help is needed, I also have a bit of MediaWiki experience I could contribute. (I'm User:Ilmari Karonen at mediawiki.org.) --Ilmari Karonen 19:37, November 6, 2010 (UTC)
- A pragmatic solution for the visual pain is to install the add-on Stylish and using this stylesheet for NetHackWiki. That doesn't fix the underlying problems but your eyes will thank you nevertheless. --bhaak 17:22, October 31, 2010 (UTC)
- Seems like this would be a lot of work, but this would be worth it in the end. Wikia has gone downhill fast in the past couple of years, with the slow page loadtimes, annoying adds, and wonky user interface changes. I would love to have a simple, clean, and fast wiki back for nethack :) I would also volunteer to help if needed. Spazm 22:17, November 6, 2010 (UTC)
Similar discussions in other wikis: Grand Theft Auto, WoWWiki, Anti-Wikia_Alliance, Slashdot about preventing Wikia from using the wiki contents, Dungeons&Dragons, outcome Tjr 17:50, November 6, 2010 (UTC)
Outcome of the vote
NetHackWiki is moving away from Wikia. will point to the new wiki as soon as possible. It currently redirects here, so you can already update your bookmarks. (For Perl fans, s/nethack.wikia.com/nethackwiki.com/ is enough.)
Moving forward
Quoting staff member Sarah Manley on w:c:simpsons:Forum:Moving_Forward:
- ... and we want to be clear that all wikiSimpsons community members are welcome to stay and participate both here and on the other wiki site. What is not welcome though is to purposely vandalize the wiki or disrupt the rest of the community, preventing them from participating here. Any user who engages in vandalizing the wiki or harassing other users here will lose admin rights, or be blocked if necessary. ... All wiki wide messages meant to push the community away from participating here will be removed. If active admins decide to leave and the remaining community decides to remove their rights and give them to others, please let me know on my talk page.
And staff member Sannse:
- ... all admins on this wiki are welcome to have their rights back, if they are willing to use them for the good of this wiki. That includes not setting notices that are basically an advert for their competitive site.
This means the move messages will eventually be deleted as "vandalism". (They are by no means wiki-wide.)Tjr 16:30, November 10, 2010 (UTC)
- Sorry to see you moving on guys, and that we didn't see the comments here before now -- I'd have liked to have had a chance to try persuade you to stay, but there are just too many wikis for us to see it all!
- On the notices: what we are asking is that you do not link to your fork on the main page of this wiki, instead, please point to this discussion or another page that explains the situation. Linking to the fork on this page (or whichever you point to) is just fine. We are also asking that you make clear that this wiki will still be here, so that anyone who wants to stay or adopt it in the future understands that they can do so. We are generally leaving notices in place for about 2 weeks, then removing them to allow the wiki a chance to revive.
- One correction on the above -- just because the allegation annoys me so. We did not delete messages for mentioning eye strain, or for any other criticism (other than extreme abusiveness and threats). The allegation quoted above was from an upset contributor who was making up a lot of stuff at the time -- including those "several ophthalmologists" who he claimed told him that having a right side-rail was causing eye problems. That said, there were reports from people finding the text a strain to read at first, so we tweaked the text colour, size and spacing. That seems to have helped.
- It's always very sad to see a community moving away from Wikia, but we respect your right to fork of course. I wish you well with your project in the future. -- Sannse<staff /> (help forum | blog) 23:06, November 12, 2010 (UTC)
- Done. The links on the Main Page have been removed, the annoncement now states people may choose to stay here, and the opthtalmologist citation now has a pointer to your rebuttal. For the record: the annoncement is only on a minority of all pages because Wikia have asked for that on some other wiki. Tjr 14:20, November 13, 2010 (UTC)
- @Sannse: I'm fine with you removing the move notice from the main page if that's what you want, but I'd like to ask if you could leave it on the other pages it has been placed on and wait for actual contributors to remove it from there. I've edited the text of the template to make it clear that anyone may do so if they wish. The way I see it, the template is not just (or even mainly) an advertisement, but rather serves to warn readers that the content is no longer actively maintained. It would seem a disservice to remove it if nobody's actually stepping forward to take over that maintenance role. --Ilmari Karonen 22:41, November 14, 2010 (UTC)
- The point is that no one is going to do that, with those notices in place. The right to fork goes two ways, and this wiki should have every chance to be adopted and revived if that's its future. You wouldn't have accepted a notice like that on articles left by a departing user six months ago, and the same should apply now -- whether it's one person moving on or the whole of the currely active community. I accept that you are moving on, I hope that you will accept that you can't do that and control the wiki you are leaving. -- Sannse<staff /> (help forum | blog) 04:51, November 17, 2010 (UTC)
- I have no interest in controlling this wiki (and I think that's true for most of the former community, even if I can only speak for myself), but I'd also rather not see people coming here left completely ignorant of what's happened and why the wiki is suddenly so quiet. Would making the notice say something like "This wiki has been abandoned. If you want to claim it for yourself, contact the Wikia staff. The previous administrators have moved over to nethackwiki.com." sound acceptable to you? Or would you happen to have a better suggestion yourself? --Ilmari Karonen 08:20, November 18, 2010 (UTC)
- I think that regular visitors and editors will have seen the messages by now (I've left it a few extra days to allow more time for that). And I'm not asking for no mention anywhere of the split. But a permanent message on all pages is excessive and not going to allow this wiki to recover. I'm OK with a notice saying that this wiki needs new admins, but that should be here on the Community Portal and other appropriate places, not on all articles -- Sannse<staff /> (help forum | blog) 06:31, November 23, 2010 (UTC)
- One week ago you said you would leave them for two weeks. --Tjr 19:56, November 23, 2010 (UTC)
- I meant that we generally leave main page notices for about 2 weeks, but I see my wording was ambiguous, sorry about that. I'll leave them in place for the rest of the two weeks, and look again after that -- Sannse<staff /> (help forum | blog) 05:48, November 24, 2010 (UTC)
Or a little longer... I get distracted easily ;) I'll change the template now. I'll also remove the text from the template page: "Wikia does not want us to add a banner via CSS that moves the content area down on all pages. One other wiki wasn't even allowed to link to their new site on the main page, but others were." - it's not quite accurate and doesn't fit without the current template content. I'll remove the similar notice from the main page, but leave the newsbox as-is. thanks -- Sannse<staff /> (help forum | blog) 23:37, December 3, 2010 (UTC)
|
https://nethackwiki.com/wiki/NetHackWiki:Community_Portal/Archive4
|
CC-MAIN-2020-34
|
refinedweb
| 8,057
| 70.84
|
Get know how to create mocks and spies in even more compact way with Spock 1.1
Introduction
Spock heavily leverages operator overloading (and Groovy magic) to provide very compact and highly readable specifications (tests) which wouldn’t be able to achieve in Java. This is very clearly visible among others in the whole mocking framework. However, preparing my Spock training I found a place for further improvements in a way how mocks and spies are created.
The Groovy way
Probably the most common way to create mocks (and spies) among devoted Groovy & Grails users is:
def dao = Mock(Dao)
The type inference in IDE works fine (there is type aware code completion). Nonetheless, this syntax is usually less readable for Java newcomers (people using Spock to tests production code written in Java) and in general for people preferring strong typing (including me).
The Java way
The same mock creation in the Java way would look as above:
Dao dao = Mock(Dao)
The first impression about this code snipped is – very verbose. Well, it is a Java way – why should we expect anything more ;).
The shorter Java way
As I already mentioned Spock leverages Groovy magic and the following construction works perfectly fine:
Dao dao = Mock()
Under the hood Spock uses a type used in the left side of an assignment to determine a type for which a mock should be created. Nominally everything is ok. Unfortunately there is one awkward limitation:
IDE complains about unsafe type assignment and without getting deeper into the logic used in Spock it is justified. Luckily the situation is not hopeless.
The shorter Java way – Spock 1.1
Preparing practical exercises for my Spock training some time ago gave me an excuse to get into the details of implementation and after a few minutes I was able to improve the code to make it work cleanly in IDE (after a few years of living with that limitation!).
Dao dao = Mock()
No warning in IDE anymore.
Summary
Multiple times in my career I experienced a well known truth that preparing a presentation is very educational also for the presenter. In a case of a new 3-day long training it is even more noticeable – attendees have much more time to ask you uncomfortable question :). Not for the first time my preparations resulted in a new feature or an enhancement in some popular libraries or frameworks.
The last code snippet requires Spock in version 1.1 (which as a time of writing is available as the release candidate 3 – 1.1-rc-3 to not trigger a warning in IDE. There is a lot of new features in Spock 1.1 – why wouldn’t you give it a try? :)
Picture credits: GDJ from openclipart.org
[…] More compact mock creation syntax in Spock 1.1 describes the new (and shorter) mock creation syntax of Spock Framework 1.1. […]
[…] More compact mock creation syntax in Spock 1.1 […]
[…] >> More compact mock creation syntax in Spock 1.1 [solidsoft.com] […]
|
https://solidsoft.wordpress.com/2016/11/28/more-compact-mock-creation-syntax-in-spock-1-1/
|
CC-MAIN-2018-17
|
refinedweb
| 501
| 62.38
|
requirement
Modular exponentiation algorithm , Through the verification of the server .
visit**.207.12.156:9012/step_04 The server will give you 10 A question , Each question contains three numbers (a,b,c), Please give me
a^b%c Value . The return value is written to the field ans,10 Use a comma for each number , separate , Submitted to the**.207.12.156:9012/step_04
Tips : Note that commas must be English commas .
{"is_success": true, "questions": "[[1336, 9084, 350830992845], [450394869827, 717234262, 9791], [2136, 938408201856, 612752924963], [6026, 754904536976, 5916], [787296602, 305437915, 661501280], [864745305, 6963, 484799723855], [4165, 110707859589, 102613824], [398189032, 723455558974, 794842765789], [974657695, 138141973218, 760159826372], [9034, 7765, 437523243]]"}
Python Program realization
import requests as re
import time
def fastModular(x): # Fast power implementation
"""x[0] = base """
"""x[1] = power"""
"""x[2] = modulus"""
result = 1
while(x[1] > 0):
if(x[1] & 1): # Bit operations speed up the judgment of parity
result = result * x[0] % x[2]
x[1] = int(x[1]/2)
x[0] = x[0] * x[0] % x[2]
return result answer = ''
getHtml = re.get("**.207.12.156:9012/step_04/") start = time.process_time() # Operation timestamp
for i in eval(getHtml.json()['questions']): # Will have '[]' The string of symbols is converted into a list
answer += str(fastModular(i)) + ','
end = time.process_time() # Operation timestamp param = {'ans':answer[:-1]}
print(f"Runing time is { end- start} sec")
getHtml = re.get("**.207.12.156:9012/step_04/",params=param)
print(getHtml.text) >>>
runing time is 0.0 s
{"is_success": true, "message": "please visit**.207.12.156:9012/context/eb63fffd85c01a0a5d8f3cadea18cf56"}
>>>
Run directly to get the next link answer !!
How can we calculate A^B mod C quickly if B is a power of 2 ?
Using modular multiplication rules:
i.e. A^2 mod C = (A * A) mod C = ((A mod C) * (A mod C)) mod C
a^b % c = (a % c)^b % c
(a * b * c) % d = {(a % d) * (c % d) * (b % d)} % d
a^5 % c = (a % c)^5 % c = {(a % c) * (a % c) * (a % c) * (a % c) * (a % c)} % c
One algorithm is to use
{(a % c) * (a % c) * (a % c) * (a % c) * (a % c)} % c, Using the normal power method , Iterate variables in .
result = result * a % c This will iterate 5 Time , That is to say Power operation time complexity .
notes : Iterative operations
{(result % c) * (a % c)} % c == result * a % c
Another is to use the relationship between base and power , Divide the power by 2, Square times the base . This number remains the same . Plus the use of lemma will be much more convenient .log(power) Time complexity of .
4^20 mod 11 = 1099511627776 % 11 =1
= 16^10 mod 11 = (16 mod 11)^10 = 5 ^ 10 mod 11
= 25 ^ 5 mod 11 = (25 mod 11)^5 = 3 ^ 5 mod 11
9 ^ 2.5 = 9 ^ 2 * 9^(1/2) = 9 ^ 2 * 3 mod 11
The above one needs square 3 change 9 Reopen 2 Power 9 change 3, Get the results . After simplification, we find that this method can be reduced to , When the power becomes odd , Let's subtract one from the odd number , Divide by two , Base squared , And multiply by the base Calculate . The result is the same . It's easier to think so . It is also convenient for program implementation
3 ^ 5 mod 11 = 9 ^ 2 * 3 mod 11 ( 5-1=4 ,4/2=2 )
= (9 mod 11)^2 mod 11 = 2 ^ 2 *3 mod 11
= 4 ^ 1 * 3 mod 11 = (4 mod 11)^1 * 3 mod 11 = 7^1 * 3 mod 11
= 49^0 *7 *3 mod 11 =21 % 11
=1
Odd minus one The part divided into even powers will eventually reach 0 Time , The result is 1. The power of the first power is the key factor to determine the result .
Fast power modules of large numbers Python More articles on Implementation
- codeforces magic five -- Fast power module
Topic link : First, calculate the value in a period , Save in ans Inside , Is the usual fast power module m practice . Then you have to calculate a formula , Such as the k ...
- Fast power module n operation
Exponentiation in modular operation , such as 5^596 mod 1234, Of course , Direct use of the cycle of violence is also possible , See a fast modular exponentiation algorithm in the book The general idea is ,a^b mod n , First the b Convert to binary , Then start at the top ( Highest one ...
- URAL 1141. RSA Attack( Euler theorem + Extended Euclid + Fast power module )
Topic link The question : Here you are. n,e,c, And know me ≡ c (mod n), and n = p*q,pq All are prime numbers . Ideas : This question really matches the title , It's a RSA Algorithm , At present, the most important encryption algorithm on earth .RSA count ...
- hdu 2462( Euler theorem + High precision and fast power module )
The Luckiest number Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Othe ...
- 2014 The first of many schools I topic || HDU 4869 Turn the pokers( Fermat's small Theorem + Fast power module )
Topic link The question : m card , It can be translated n Time , Every time I turn xi card , Ask how many forms you can get in the end . Ideas :0 Defined as the opposite ,1 Defined as positive ,( At first it was anti ), For each flop , We define two boundaries lb,rb, Represents each time 1 least ...
- hdu 1852( Fast power module + The formula for taking modulus when there is division )
Beijing 2008 Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/65535 K (Java/Others)Tota ...
- 2019 Nanchang invitational tournament C. Angry FFF Party Fast exponentiation of large number matrices + Classification of discussion
Topic link The question : Defined function : $$F(n)=\left\{\begin{aligned}1, \quad n=1,2 \\F(n- ...
- [ primary ]sdut2605 A^X mod P Shandong Province, the fourth ACM Provincial competition ( The meter , Fast power module idea , Hash )
This article from the : The question : f(x) = K, x = 1 f(x) = (a*f(x-1) + b)%m , x > 1 Find out ( A^(f(1) ...
- Fast power module m Algorithm
Here are three numbers ,a,b,m seek a^b%m Value . If b Too big , Using the ordinary fast power will timeout . So will b=2^0*b0+2^1*b+b1...... then , You know how to do it by using the knowledge of junior middle school . continue , Code up . #inc ...
- hdu 4602 Fast power module of recursive relation matrix
Partition Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total S ...
Random recommendation
- Study with me python, Basic concepts (life is short ,we need python)
author :tobecrazy Source : Welcome to reprint , Reprint please indicate the source .thank you! Basic concepts : Constant : Constant names are all uppercase , Such as PI Variable : ...
- Network | UDP checksum
1. The checksum ICMP,IP,UDP,TCP It's all in the header checksum( Inspection and ) Field .IP The check sum in the header checks only the header :ICMP.IGMP.TCP and UDP Checksums in headers check headers and data . UDP and TCP ...
- 【Selenium】1. Introduce Selenium
This article is for study and communication , No commercial use , No profit . It's all my own translation to urge me to study . Poor translation , Forgive me . originate : ...
- android Life cycle of
1. Running state : When an activity is at the top of the stack , At this time, the activity is active , The system is unwilling to recycle active , Will affect the user experience . 2. Pause state : When an activity is no longer at the top of the stack , But still visible , This is the pause state . On hold ...
- 【 Basics 】Asp.Net operation Cookie summary
One . What is? Cookie? Cookie Is a small amount of data stored in the text file of the client file system or in the memory of the client browser dialog . It's mainly used to track data settings , for example : When we want to visit a website page , When a user requests a web page , Applications may ...
- [ Reprint ] Dubbo Architecture design details
Reprinted from Dubbo yes Alibaba Open source distributed service framework , Its biggest characteristic is to construct in a hierarchical way , In this way, the layers can be decoupled ...
- node.js Advanced topics
< h3>notes_ control flow //forloopi.js var fs = require('fs'); var files = ['a.txt', 'b.txt', 'c.txt']; ...
- php in heredoc And nowdoc How to use
One .heredoc Structure and usage Heredoc Structure is like a double quote string without double quotes , That is to say in heredoc A single quotation mark in a structure does not need to be escaped . The variables in its structure will be replaced , But in heredoc The structure contains complex ...
- MySQL series --1. Install, uninstall and user rights management
MySQL install 1.Ubuntu18 Lower installation MySQL sudo apt-get install mysql-server MySQL The version is 5.7.25 2. Sign in MySQL use mysql-serve ...
- Linux-- Master slave copy
One . mysql+centos7 mariadb mariadb It's actually with mysql It's the same , It's just that centos7 It's called mariadb, Mainly because mysql After being acquired by Oracle , There may be a risk of closing the source ...
|
https://en.pythonmana.com/2021/08/20210823010651136j.html
|
CC-MAIN-2022-27
|
refinedweb
| 1,521
| 61.16
|
Created on 2010-06-18 10:20 by mark.dickinson, last changed 2010-09-07 04:47 by rhettinger. This issue is now closed.
Not a serious bug, but worth noting:
The result of randrange(n) is not even close to uniform for large n. Witness the obvious skew in the following (this takes a minute or two to run, so you might want to reduce the range argument):
Python 3.2a0 (py3k:81980, Jun 14 2010, 11:23:36)
[GCC 4.2.1 (SUSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from random import randrange
>>> from collections import Counter
>>> Counter(randrange(6755399441055744) % 3 for _ in range(100000000))
Counter({1: 37508130, 0: 33323818, 2: 29168052})
(The actual probabilities here are, as you might guess from the above numbers: {0: 1/3, 1: 3/8, 2: 7/24}.)
The cause: for n < 2**53, randrange(n) is effectively computed as int(random() * n). For small n, there's a tiny bias involved, but this is still an effective method. However, as n increases towards 2**53, the bias increases significantly. (For n >= 2**53, the random module uses a different strategy that *does* produce uniformly distributed results.)
A solution would be to lower the cutoff point where randrange() switches from using int(random() * n) to using the _randbelow method.
Note: the number 6755399441055744 is special: it's 0.75 * 2**53, and was deliberately chosen so that the non-uniformity is easily exhibited by looking at residues modulo 3. For other numbers of this size, the non-uniformity is just as bad, but demonstrating the non-uniformity clearly would have taken a little more work.
Here's an example patch that removes any bias from randrange(n) (except for bias resulting from the imperfectness of the core MT generator). I added a small private method to Modules/_randommodule.c to aid the computation.
This only fixes one instance of int(random() * n) in the Lib/random.py source; the other instances should be modified accordingly.
With this patch, randrange is a touch faster than before (20-30% speedup) for small arguments.
Is this worth pursuing?
The nonuniformity of randrange has a knock-on effect in other random module functions. For example, take a sample of 100 elements from range(6004799503160661), and take the smallest element from that sample. Then the exact distribution of that smallest element is somewhat complicated, but you'd expect it to be even with probability very close to 50%. But it turns out that it's roughly twice as likely to be even as to be odd.
>>> from random import sample
>>> from collections import Counter
>>> population = range(6004799503160661)
>>> Counter(min(sample(population, 100)) % 2 for _ in range(100000))
Counter({0: 66810, 1: 33190})
Here's a more careful Python-only patch that fixes the bias in randrange and randint (but not in shuffle, choice or sample). It should work well both for Mersenne Twister and for subclasses of Random that use a poorer PRNG with badly-behaved low-order bits.
Will take a look at this in the next few days.
Am tempted to just either provide a recipe
or provide a new method. That way sequences generated
by earlier python's are still reproducible.
I would prefer to see correct algorithm in stdlib and a recipe for how to reproduce old sequences for the users who care.
FWIW, we spent ten years maintaining the ability to reproduce sequences. It has become an implicit promise.
I'll take a look at the patch in the next few days.
Hmm. I hadn't considered the reproducibility problem.
Does the module aim for reproducibility across all platforms *and* all versions of Python? Or just one of those?
For small n, I think the patched version of randrange(n) produces the same sequence as before with very high probability, but not with certainty. Since that sounds like a recipe for hard-to-find bugs, it might be better to deliberately perturb the outputs somehow so that the sequence is obviously different from before, rather than subtly different.
'Random', without qualification, is commonly taken to mean 'with uniform distribution'. Otherwise it has no specific meaning and could well be a synonym for 'arbitrary' or 'haphazard'.
The behavior reported is buggy and in my opinion should be fixed if possible. I have done simulation research in the past and do not consider them minor. If I had results that depended on these functions, I might want to rerun with the fixed versions to make sure the end results were not affected. I would certainly want the fixed behavior for any future work.
I do not see any promise of reproducibility of sequences from version to version. I do not really see the point as one can rerun with the old Python version or copy the older random.py.
The old versions could be kept with with an 'old_' prefix and documented in a separate subsection that starts with "Do not use these buggy old versions of x and y in new code. They are only present for those who want to reproduce old sequences." But I wonder how many people would use them.
FWIW, here are two approaches to getting an equi-distributed version of int(n*random()) where 0 < n <= 2**53. The first mirrors the approach currently in the code. The second approach makes fewer calls to random().
def rnd1(n):
assert 0 < n <= 2**53
N = 1 << (n-1).bit_length()
r = int(N * random())
while r >= n:
r = int(N * random())
return r
def rnd2(n, N=1<<53):
assert 0 < n <= N
NN = N - (N % n) + 0.0 # largest multiple of n <= N
r = N * random() # a float with an integral value
while r >= NN:
r = N * random()
return int(r) % n
Either of these looks good to me.
If the last line of the second is changed from "return int(r) % n" to "return int(r) // (N // n)" then it'll use the high-order bits of random() instead of the low-order bits. This doesn't matter for MT, but might matter for subclasses of Random using a different underlying generator.
This wouldn't be the first time reproduceability is dropped, since reading from the docs:
.”
Also:
> FWIW, we spent ten years maintaining the ability to reproduce
> sequences. It has become an implicit promise.
IMO it should either be documented explicitly, or be taken less dearly. There's not much value in an "implicit promise" that's only known by a select few.
(besides, as Terry said, I think most people are more concerned by the quality of the random distribution than by the reproduceability of sequences)
I guess, Antoine wanted to point out this:
"Changed in version 2.3: MersenneTwister replaced Wichmann-Hill as the
default generator."
But as the paragraph points out Python did provide non default WichmanHill
class for generating repeatable sequences with older python.
My brief reading on this topic, does suggest that 'repeatability' is
an important requirement for any PRNG.
BTW, the Wichmann-Hill code is gone in py3k, so that doc paragraph needs removing or updating.
Thanks guys, I've got it from here.
Some considerations for the PRNG are:
* equidistribution (for quality)
* repeatability from the same seed (even in multithreaded environments)
* quality and simplicity of API (for usability)
* speed (it matters whether a Monte Carlo simulation takes 5 minutes or 30 minutes).
I'm looking at several ideas:
* updating the new randrange() to use rnd2() algorithm shown above (for equidistribution).
* possibly providing a C version of rnd2() and using it in randrange() for speed and for thread-safety.
* possibly updating shuffle() and choice() to use rnd2().
* moving the existing randrange() to randrange_quick() -- uses int(n * random) for speed and for reproducibility of previously created sequences. Alternatively, adding a recipe to the docs for recreating old sequences and not cluttering the code with backwards compatibility cruft.
Am raising the priority to normal because I think some effort needs to be made to address equidistribution in 3.2. Will take some time to come-up with a good patch that balances quality, simplicity, speed, thread-safety, and reproducibility.
May also consult with Tim Peters who has previously voiced concerns about stripping bits off of multiple calls to random() because the MT proofs make no guarantees about quality in those cases. I don't think this is an issue in practice, but in theory when we start tossing out some of the calls to random(), we're also throwing away the guarantees of a long periodic, 623 dimensions, uniformity, and equidistribution.
> Some considerations for the PRNG are:
> * equidistribution (for quality)
> * repeatability from the same seed (even in multithreaded environments)
I believe a reasonable (com)promise would be to guarantee repeatability
accross a given set of bugfix releases (for example, accross all 2.6.x
releases). We shouldn't necessarily commit to repeatability accross
feature releases, especially if it conflicts with desireable
opportunities for improvement.
> * possibly providing a C version of rnd2()
If recoding in C is acceptable, I think there may be better ( = simpler and faster) ways than doing a direct translation of rnd2.
For example, for small k, the following algorithm for randrange(k) suffices:
- take a single 32-bit deviate (generated using genrand_int32)
- multiply by k (a 32-by-32 to 64-bit widening multiply) and return
the high 32-bits of the result, provided that the bottom half
of the product is <= 2**32 - k (almost always true, for small k).
- consume extra random words as necessary in the case that the bottom
half of the product is > 2**32 - k.
I can provide code (with that 3rd step fully expanded) if you're interested in this approach.
This is likely to be significantly faster than a direct translation of rnd32, since in the common case it requires only: one 32-bit deviate from MT, one integer multiplication, one subtraction, and one comparison. By comparison, rnd2 uses (at least) two 32-bit deviates and massages them into a float, before doing arithmetic with that float.
Though it's possible (even probable) that any speed gain would be insignificant in comparison to the rest of the Python machinery involved in a single randrange call.
Just to illustrate, here's a patch that adds a method Random._smallrandbelow, based on the algorithm I described above.
Antoine, there does need to be repeatablity; there's no question about that. The open question for me is how to offer that repeatability in the cleanest manner.
People use random.seed() for reproducible tests. They need it to have their studies become independently validatable, etc. Some people are pickling the state of the RNG and need to restart where they left off, etc.
Mark, thanks for the alternative formulation. I'll take a look when I get a chance.
I've got it from here.
randint.py: another algorithm to generate a random integer in a range. It uses only operations on unsigned integers (no evil floatting point number). It calls tick() multiple times to generate enough entropy. It has an uniform distribution (if the input generator has an uniform distribution).
tick() is simply the output of the Mersenne Twister generator. The algorithm can be optimized (especially the part computing ndigits and scale).
> Antoine, there does need to be repeatablity; there's no question about
> that.
Well, that doesn't address my proposal of making it repeatable accross
bugfix releases only. There doesn't seem to be a strong use case for
perpetual repeatability.
If some people really need perpetual repeatability, I don't understand
how they can rely on Python anyway, since we don't make any such promise
explicitly (or do they somehow manage to read in your mind?). So,
realistically, they should already be using their custom-written
deterministic generators.
Distribution with my algorithm:
...
from collections import Counter
print Counter(_randint(6755399441055744) % 3 for _ in xrange(100000000))
=> Counter({0L: 33342985, 2L: 33335781, 1L: 33321234})
Distribution: {0: 0.33342985000000003, 2: 0.33335780999999998, 1: 0.33321234}
A couple of points:
(1) In addition to documenting the extent of the repeatability, it would be good to have tests to prevent changes that inadvertently change the sequence of randrange values.
(2) For large arguments, cross-platform reproducibility is already a bit fragile. For example, the _randbelow function depends on the system _log function---see the line
k = int(1.00001 + _log(n-1, 2.0))
Now that we have the bit_length method available, it might be better to use that.
Put in a fix with r84576. May come back to it to see if it can or should be optimized with C. For now, this gets the job done.
|
https://bugs.python.org/issue9025
|
CC-MAIN-2021-10
|
refinedweb
| 2,121
| 63.7
|
Write a C# program that requests the width (x) and height (y) of a rectangle and calculate the perimeter, area and diagonal.
4
6
Perimeter: 20
Area: 24
Diagonal: 7.21110255092798
using System;
public class DoubleValue
{
public static void Main(string[] args)
{
double a = Convert.ToDouble(Console.ReadLine());
double b = Convert.ToDouble(Console.ReadLine());
double perimeter = a * 2 + b * 2;
double area = a * b;
double diagonal = Math.Sqrt(a * a + b * b);
Console.WriteLine("Perimeter: {0}", perimeter);
Console.WriteLine("Area: {0}", area);
Console.WriteLine("Diagonal: {0}", diagonal);
}
}
Practice C# anywhere with the free app for Android devices.
Learn C# at your own pace, the exercises are ordered by difficulty.
Own and third party cookies to improve our services. If you go on surfing, we will consider you accepting its use.
|
https://www.exercisescsharp.com/data-types-a/double-value/
|
CC-MAIN-2022-05
|
refinedweb
| 130
| 53.37
|
What is the problem with this table editor code?814246 Aug 13, 2012 6:29 AM
im using JButton as TableCellEditor component. When I clicked on button nuthing happens.
Tell me where im wrong?
Tell me where im wrong?
public class Abc extends AbstractCellEditor implements TableCellEditor{ private JButton btnSearch ; private BCD ref; private JTable table; public DraggedTextSearchEditor(BCD o,JTable tab){ this.ref = o; this.table = tab; btnSearch = new JButton(); btnSearch.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ref.search(); } }); } @Override public Component getTableCellEditorComponent(JTable table,Object value ,boolean isSelected,int row,int col) { return btnSearch; } public Object getCellEditorValue(){ return btnSearch; } // public Object getCellEditorValue(){ // return null; // } }
This content has been marked as final. Show 4 replies
1. Re: What is the problem with this table editor code?morgalr Aug 14, 2012 2:52 PM (in response to 814246)What have you tried to trace this problem?
try putting a System.out.println("what ever...") in your actionPerformed method to see if it's firing for you.
2. Re: What is the problem with this table editor code?814246 Aug 16, 2012 5:53 AM (in response to morgalr)no actionperformed() is not calling on click. its not doing anything.
3. Re: What is the problem with this table editor code?morgalr Aug 21, 2012 3:40 PM (in response to 814246)You're trying to be too tricky: dynamically linking to an Action Listener. When you compile the object ref = null and later you assign it to your dragged object--Nope, not going to work in the way you think it does. At the time of compile your ref object is null.
4. Re: What is the problem with this table editor code?walterln Aug 22, 2012 11:18 AM (in response to 814246)See
|
https://community.oracle.com/message/10532984
|
CC-MAIN-2017-47
|
refinedweb
| 297
| 60.31
|
FOR THE SECOND LAB IN COMPUTER SCIENCE 124, you will write a few short programs using Visual J++. You'll also learn how to create a Visual J++ project from scratch and learn more about Visual J++ in general.
As far as programming goes in this lab, you'll use variables, assignment statements, if statements, and while statements. You'll also use a few basic "console" commands. The full story about these program elements can be found in Chapter 2 of the text. However, most of what you need to know to do the lab is reviewed in this lab worksheet or has been covered in class.
The exercises at the end of the lab are due in class on the Monday following the lab. Remember that you can work with a lab partner and turn in a single lab report if you want. You can also turn in an individual report.
In general, you will begin every project for this course by copying a starter folder from the cpsc124 folder that can be accessed on PCCommon, on the campus network. However, it is also possible to create a Visual J++ project from scratch. In this part of the lab, you will create a stand-along console application from scratch.
In the Gulick lab, to start up Microsoft Developer Studio directly, click to the Start button. From there go to Programs and then to CourseWare. In the CourseWare submenu, click on DevStudio. This will launch the Microsoft Developer Studio.
Since you have not opened an existing project, you have to begin by creating a project. To do this, choose New from the File menu. The New command opens a dialog box that you can use to create an extraordinarily large number of things. You want to create a Java project:
After you set up the dialog as illustrated, click on the OK button to create the project. If you use the name "ApplicationStarter" for your project, as illustrated, you will find that a new project folder named ApplicationStarter has been created in your M drive.
The next step is to add Java source code files to your project. You can add existing files to the project, and you can create new files. To create a new Java source code file, use the New command again. You will get the same dialog box, but this time it should have the File tab selected:
If you set up the dialog as illustrated and click on the OK button, a new file named "MyProgram.java" will be created in the project folder. (You could, of course, use a different name.) The file will be opened and ready for you to type. You should type the Java source code for your program into this file. As a simple example, enter the following program. If you are reading this worksheet in a Web browser, you can save yourself the typing by using copy-and-paste to copy the program from the browser to Developer Studio. Note that the name of the class, MyProgram, should be the same as the name of the java file that contains the class:
public class MyProgram { // A simple program that multiplies two numbers input by // the user and displays the answer. public static void main(String[] args) { Console console = new Console(); double x,y; // numbers input by user double ans; // answer computed by program console.put("Enter your first number: "); x = console.getlnDouble(); console.put("Enter your second number: "); y = console.getlnDouble(); ans = x * y; console.putln(); console.putln("The product of your numbers is " + ans); console.close(); } // end of main() } // end of class MyProgram
Once you've typed the program in, you can try to run it. However, you will get at least one error: The Console class is undefined. Remember that the Console class is not a standard part of Java. If you want to use it, you must add two files to your project: Console.java, which defines the Console class, and ConsoleCanvas.java, which defines another class that is used by the Console class in turn. From the first lab, you should already have copies of these files in a folder called "Lab 1 Starter" on your M drive. You should copy them from that folder to your new "ApplicationStarter" folder. (If you don't remember how to do this, ask for help.)
After copying Console.java and ConsoleCanvas.java to the ApplicationStarter folder, you still have to tell Developer Studio that they are part of the project. To do this, go to the Developer Studio Project menu, select Add to Project, and from there select Files. You will get a dialog box from which you can select the two files that you want to add:
After adding the files to your project, you should be able to compile your program (unless there are other errors introduced by bad typing). Once your program compiles without error, there is still one more hurdle. You have to tell the computer which class to execute and whether it should be run as an applet or as a stand-alone project. Since you have not set up this information already, the computer will ask you to enter it before it runs the program. It will display this dialog box:
This should, finally, allow the program to run. Congratulations! You have created a complete, working Visual J++ project! Fortunately, this is not something you need to do regularly. The next time you have to write a program, you can just make a copy of your ApplicationStarter folder, open the .dsw file in the copied folder, and rewrite the MyProgram class to do something new. You will also find a "Console Application Starter" folder in the cpsc124 folder that you can use as a starting point for programs.
The program you worked with in the preceding section did nothing but multiply two numbers and then quit. Programs that do more complicated tasks must have to ability to repeat the same task over and over and the ability to make decisions among alternative courses of actions. Here is an improved -- though still pretty simple -- program in which the user can tell the computer to add, subtract, multiply, or divide two numbers. The program decides among these alternatives based on the user's choice from a list of available options. Furthermore, the program repeats the process of getting the user's input and computing the output over and over, as long as the user wants to continue. The program is shown here as a "console applet" that runs on the page. As an exercise, you will be writing the same program as a stand-alone application. You can do this by modifying your ApplicationStarter project.
As a first step, modify the program from the preceding section so that it prints out the list of choices, reads the user's choice, and computes the answer by applying the operation requested by the user. Assuming that choice is declared to be a variable of type int, you can read the user's choice with the statement:
choice = getlnInt();
Then, to do the computation requested by the user, you can use this if statement:
if (choice == 1) ans = x + y; else if (choice == 2) ans = x - y; else if (choice == 3) ans = x * y; else ans = x / y;
Here, the condition "choice == 1" tests whether the value of the variable, choice, is 1. If it is, then the associated statement, "ans = x + y;", is executed. The other two conditions work in the same way. The last statement, "ans = x / y" is a default case that is executed if none of the three preceding conditions is true. You can copy this statement exactly as it appears into your program, but you should note how the statement is formed since later in the lab you will have to write your own if statement.
Before proceeding, you should make sure that your program can be successfully compiled and run. Correct any errors that the computer finds when you try to run it. Ask for help if you need it.
To complete the program, you have to introduce repetition. One way to do this in Java is with a while loop. A while statement has the form:
while (condition) { statements to be repeated }
The condition can be replaced by any test that can have the value true or false. In this case, you can use a loop that looks like:
boolean again = true; while (again) { . . // statements to be repeated . console.putln("Do you want to go again? "); again = console.getlnBoolean(); }
Here, the boolean variable again is initialized to be true so that the while will be executed at least once. At the end of the while loop, a new value for again is read from the user. The command "console.getlnBoolean()" allows the user to answer yes or no. If the user answers yes, then again will be true, and the loop will be repeated. If the user answers no, then the loop will end.
To introduce repetition into your program, all you have to do is put most of the statements that the program already contains inside the { and } of the while loop. Complete the program now, and make sure that it can be correctly compiled and run.
Programs are meant to be read by computers. But they are also meant to be read by people. For this reason, programs should be written so that they are as easy as possible for human readers to read and understand. Good programming style means writing programs that satisfy this requirement. Although there is some room for taste, there are definite rules of good style, and every program that you turn in for this course should follow those rules. This includes the programs that you turn in for this lab. Grading will be based on style as well as on correctness.
Here are some rules that I expect every program to follow:
I will probably add other style requirements as the course proceeds.
One fun program that I like to have my students write early in their programming career is a guessing game program, in which the user tries to guess a number picked by the computer. Such a program uses both loops and branches. You can try out such a guessing game program in this applet:
One of your exercises for this lab is to write such a game as a stand-alone application. As a starting point, you can copy the "Console Application Starter" that is in the "cpsc124" folder into the "java" folder on your M drive. (As an alternative, you could use a copy of your own "ApplicationStarter" folder.) One more thing that you will have to know is how to tell the program to choose a random number between 1 and 100. Assume that you have a variable named randomNumber of type int. Then the following statement tells the computer to choose a random integer between 1 and 100 and to store that random number in the variable randomNumber:
randomNumber = (int)(100 * Math.random()) + 1;
Once it has this random number, your program can read in guesses from the user and compare them to randomNumber using the operators ==, >, <, and !=. (The != operator means "not equal to".) The most natural way to write this program uses a do loop instead of a while loop. The loop you need takes the form:
do { . . . } while (guess != randomNumber);
where guess is the number guessed by the user. This loop repeats until the guess is equal to the random number.
On this lab worksheet, you've seen two "console applets" that provide console-style interaction in an applet running on a Web page. Since you will be writing several console-style applets, you might be interested in knowing how to write such applets so that you can publish your work on the World Wide Web. This section of the lab explains how to write such an applet. As one of your assignments for the course, you are asked to convert your stand-alone guessing game program into a console applet and to publish that applet in your WWW directory on the Campus VAX.
To write a console applet, you should start by copying the folder "Console Applet Starter" from the "cpsc124" folder into the "java" folder on your M drive. Open your copy of the folder and double-click the .dsw file that it contains. You will create your console applet by editing the file "MyApplet.java" in this project.
You only need to do a few things. First, change the title of the program in the applet's init() method. Second, copy all the code from the main() routine of your stand-alone program except for the lines "Console console = new Console();" and "console.close();". Paste this code to the program() method of the applet, and remove the line "console.putln("Hello World");. That's it! When this applet is used on a Web page, it will run your program. Try executing the program to make sure that it works.
To publish your console applet on the Web, use FTP to transfer the following files into the WWW directory of your account on hws3.hws.edu: TestMyApplet.html, MyApplet.class, ConsoleApplet.class, ConsolePanel.class, and ConsoleCanvas.class. The URL of your page on the web will be
where "username" should be replaced by your own username.
A problem with this is that the name of your applet will be "MyApplet". It would be nice to give it a better game, such as "GuessingGameApplet". This will be especially important if you ever want to publish more than one console applet. Unfortunately, it is rather complicated to change the name of an Applet in Visual J++. Here are all the things you have to do in your Visual J++ project to rename MyApplet to GuessingGameApplet:
It's too bad that this is so complicated, and you are welcome to leave the name set to "MyApplet" for this assignment.
From time to time, I will ask you to publish applets on the Web so that I can look at them. You can always do this by using FTP to copy a few files into your account on hws3.hws.edu. You will not need to learn any more about HTML and Web publishing in order to do this. However, if you want to be more serious about Web publishing and to create a nice home page on the Web, I encourge you to do so. This is not a required part of this lab or of the course, but I'd be happy to help you get started and to answer some of your questions.
If you want to be serious about Web publishing, I suggest that you create a folder called "WWW" on your M drive (or on your own computer, if you prefer). Do all your work on the Web site in this directory. When you have something ready to publish, use FTP to copy all the files that you've added or modified over to your account on the campus VAX. This will make your work visible to everyone on the Web.
If you want to view one of the HTML files in the WWW folder on your M drive, you can simply drag it onto the Netscape icon. You can make modifications to the page using the Composer component of Netscape Communicator 4.0. All you have to do is open the page with Netscape, then choose "Edit Page" from the File menu. You can edit the page much like you would in a word-processor. It's easy to add hypertext links to the page, set font and background colors, and drag images -- such as those found at -- onto your page. You can read the instructions in Netscape's help, or you can ask me for a demonstration.
Netscape composer does not make it easy to add an applet to a page. One solution to this is to leave your applets on html pages copied from your Visual J++ projects. You can edit those pages in Netscape Composer, and you can make links to the pages from your home page. If you want to add an applet to an existing page, you can edit the html file with a text editor, such as NotePad, and add the html commands that place the applet on the page. For example, the following commands would be used to center an applet named MyApplet on a page and to set its size to 520 pixels by 300 pixels:
<center> <applet code="MyApplet.class" width=520 height=300> </applet> </center>
By the way, you can also edit HTML pages using word processors like WordPerfect or Microsoft Word. Like Netscape, they allow you to edit the page visually. If you are willing to work with the raw HTML codes, you can edit the page in a plain text editor such as NotePad. If you want to create quality pages, you should consider learning the basics of HTML so that you can directly creatly edit HTML files in a text editor.
Exercise 1. Complete the simple program described above, which can add, subtract, multiply, or divide numbers entered by the user. The program should have the same behavior as the sample console applet. Your program should obey the style rules discussed above. Turn in a printout of your working program.
Exercise 2. Write the guessing game program described and illustrated above. Make sure that it follows the rules of good programming style. Turn in a printout of your working program.
Exercise 3. Create a console applet version of your guessing game, as described above, and publish it in your WWW account on hws3.hws.edu. Tell me the URL of the page containing the applet. I will check to see whether it is there and is working properly. You might want to beef up your program to make it more interesting than the sample guessing game applet given above. If you make it nice enough, turn in a printout of the source code, and maybe you will get some extra credit.)
Exercise 4. Section 5 of the text discusses the use of stepwise refinement and pseudocode to develop algorithms. For this final exercise, you should pretend that you have not already written your guessing game program. Read Section 5 carefully and use the methods discussed in that section to develop an algorithm for a guessing game program. Write up a description of the development process. You can imitate the discussions in the text. Your answer should include at least five pseudocode outlines of the algorithm. Each outline should be more detailed and complete than the previous outline. Also include some discussion between stages, as is done in the examples in the text. This exercise will certainly require at least one full page, and it might take several pages to do it right.
|
http://math.hws.edu/eck/cs124/labs98/lab2/index.html
|
crawl-001
|
refinedweb
| 3,154
| 71.14
|
.
Code On Time generator allows creating data controllers from the result set of a stored procedure. Some stored procedures use parameters in order to perform operations on the data. In the Northwind sample database, the [Employee Sales By Country] stored procedure shows total sales amounts grouped by employee, and then by country. It accepts two parameters, @Starting_Date and @Ending_Date to determine the filter.
Let’s create a controller from this stored procedure and pass parameters to the script via properties in the BusinessRules class of the app.
This picture shows the results of the stored procedure with @Beginning_Date and @Ending_Date parameters returned by a business rule property. business rule properties as SQL parameters.
-- debug
DECLARE @BusinessRules_BeginningDate datetime,
@BusinessRules_EndingDate datetime
-- end debug
EXEC [dbo].[Employee Sales by Country]
@BusinessRules_BeginningDate,
@BusinessRules_EndingDate
Press OK to generate the controller..
Let’s create two properties in the BusinessRules class. These properties will return a DateTime value that will be picked up and used by the query to filter the results. If the user is in role “Administrators”, it will display all records between 1970 and 2000. Otherwise, no records will be displayed.
On the Project Designer toolbar, press Browse to first generate the web app. Then, press Develop to open the solution in Visual Studio.
In the Solution Explorer on the right side, right-click on App_Code folder and press Add | Class.
Assign a name of “EmployeeSalesByCountryProperties” and press OK to create the file. Replace the contents of the file with the following:
C#:
using System;
namespace MyCompany.Data
{
public partial class BusinessRules
{
public static DateTime BeginningDate
{
get
{
if (Controller.UserIsInRole("Administrators"))
return new DateTime(1970, 1, 1);
else
return DateTime.Now;
}
}
public static DateTime EndingDate
{
get
{
if (Controller.UserIsInRole("Administrators"))
return new DateTime(2000, 1, 1);
else
return DateTime.Now;
}
}
}
}
Visual Basic:
Imports Microsoft.VisualBasic
Namespace MyCompany.Data
Partial Public Class BusinessRules
Public ReadOnly Property BeginningDate As DateTime
Get
If Controller.UserIsInRole("Administrators") Then
Return New DateTime(1970, 1, 1)
Else
Return DateTime.Now
End If
End Get
End Property
Public ReadOnly Property EndingDate As DateTime
Get
If Controller.UserIsInRole("Administrators") Then
Return New DateTime(2000, 1, 1)
Else
Return DateTime.Now
End If
End Get
End Property
End Class
End Namespace
Make sure to save the file.
Press Ctrl+F5 to start the app without debugging. Log in as an administrator and navigate to the Employee Sales By Country page. Notice that all 809 records are displayed.
Log out, and log in again as a user. Notice that no records are displayed.
|
http://codeontime.com/blog/label/Data%20Sources
|
CC-MAIN-2017-22
|
refinedweb
| 419
| 51.24
|
Defect Report #148
Submission Date
: 23 Feb32: Defining library functions
Subclause 7.1.7 is unclear about when it is permitted to declare a library function. Consider the following translation unit:
#include <math.h>
double (sin)(double);
Subclause 7.1.7 states in part:
Any function declared in a header may be additionally implemented as a macro defined in the header, so a library function should not be declared explicitly if its header is included.
Since the wording uses the term "should", this does not appear to actually be a requirement on programs, and the code appears to be strictly conforming; in other words, the C Standard here simply uses overly restrictive wording while trying to assist readers, and does not actually forbid the above code.
Is this interpretation correct?
Note that code such as the above is useful if the
#include
is conditionally compiled or is within a header not under the control of the code's author.
Suggested Technical Corrigendum:
If the intent was to forbid such a declaration, then change the quoted text to:
A library function shall not be declared explicitly if its header is included.
If the intent was to allow the macros described in subclause 7.1.7 to be object-like macros (though other wording in 7.1.7 appears to forbid this), then change the quoted text to:
A library function must not be declared explicitly if its header is included, unless any macro definition of the name has been removed with
#undef
.
If the intent was to allow the example declaration, then change the quoted text to:
Any function declared in a header may be additionally implemented as a macro defined in the header, so one of the techniques below should be used to ensure that any explicit declaration of a library function is not affected by any such macro.
Response
The wording of the C Standard is as intended. The term "should" is intended as guidance to the programmer as is the sentence following the one cited in the C Standard.
Previous Defect Report
< - >
Next Defect Report
|
http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_148.html
|
CC-MAIN-2019-13
|
refinedweb
| 347
| 50.26
|
Any chance to access the train scripts to get that rebuild?
Best regards
Any chance to access the train scripts to get that rebuild?
Best regards
Hi,
you can use these scripts: train.zip (8.5 KB)
for installing DA for Delphi 10.3.3 (compiling all dcu for all supported platforms), it uses these parameters:
Train.exe “-vRORoot=C:\Program Files (x86)\RemObjects Software\RemObjects SDK for Delphi” “-vEWRoot=C:\Program Files (x86)\RemObjects Software\Everwood” “-vDARoot=C:\Program Files (x86)\RemObjects Software\Data Abstract for Delphi” “-vEWVersion=4.7.0.865” “-vROVersion=10.0.0.1474” “-vDAVersion=10.0.0.1474” “-vDelphi_Versions=26” “-vCBuilder_Versions=26” “-vWin32=26” “-vWin64=26” “-vOSX32=26” “-vOSX64=26” “-vLinux64=26” “-vAndroid32=26” “-vAndroid64=26” “-viOSSimulator=26” “-viOSDevice32=26” “-viOSDevice64=26” “-vFMX=26” “-vServer=1” c_DA.train “-t=C:\Program Files (x86)\RemObjects Software\Data Abstract for Delphi\log.html” “-x=C:\Program Files (x86)\RemObjects Software\Data Abstract for Delphi\log.xml”
Note: you can check actual command line during installing RO/DA setup in TaskMan or Process Explorer. setup launches
train.exe when build task is selected.
Eugene,
since setup uses these scripts too, would it make sense to just leave them in place/deploy them (and train) somewhere, so all users can easily find/use them, if they so desire?
@mh: We can do this. Nowadays train and his scripts are put to temporary folder and removed after installing
Let’s.
Thanks, logged as bugs://84270
Need to add UNIDAC package. Try by myself without success. Also tray to remove iOS and android packages from the command line but IDE packages fails.
you can remove
“-vAndroid32=26” “-vAndroid64=26” “-viOSSimulator=26” “-viOSDevice32=26” “-viOSDevice64=26” parameters
something like
buildDADelphiPackage(_version, ‘Drivers/DataAbstract_UniDACDriver’, define, ‘System;winapi;System.Win;Data.Win;Datasnap.Win;Web.Win;Soap.Win;Xml.Win;Bde’,_platform);
you may need to adjust namespaces , i.e.
System;winapi;System.Win;Data.Win;Datasnap.Win;Web.Win;Soap.Win;Xml.Win;Bde; line
|
https://talk.remobjects.com/t/rebuild-ro-and-da-libraries-with-train/21930
|
CC-MAIN-2020-24
|
refinedweb
| 332
| 51.14
|
How do I read and output a text file from a Servlet?
Created May 3, 2012
Alex Chaffee Try the following:Also note the use of a finally block to close the file. This way, even if the reading throws an exception, the file will be closed. This is important on a server, since file descriptors are limited, and you don't want any leaks, since the server will be up for a very long time (hopefully!).
import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class MessageServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { // output an HTML page res.setContentType("text/html"); // load a configuration parameter (you must set this yourself) String root = getInitParameter("root"); // print some html ServletOutputStream out = res.getOutputStream(); out. println("<html>"); out.println("<head><title>Message of the Day</title></head>"); out.println("<body><h1>Today's Message:</h1>"); // print the file InputStream in = null; try { in = new BufferedInputStream (new FileInputStream(root + "/message.txt") ); int ch; while ((ch = in.read()) !=-1) { out.print((char)ch); } } finally { if (in != null) in.close(); // very important } // finish up out.println("</body></html>"); } }[Note: I have now successfully compiled and run the above example. You asked for working source, you got it :-)]
You may want to do more than just copy the file; look in the java.io package for classes that help you process a file, like StreamTokenizer.
Pay attention to the use of an InitParameter to provide a root on the file system. That way your servlet can be used on other servers without hardcoding a file path.
Whenever you access local resources, you have to consider security holes. For instance, if you make a file name based on a FORM parameter, you should validate it, to make sure if a hacker sends in, e.g., "/etc/passwd" as his user name, he won't actually get the system password file.
|
http://www.jguru.com/faq/view.jsp?EID=11569
|
CC-MAIN-2016-44
|
refinedweb
| 321
| 64.91
|
/* Declarations for getopt (GNU extensions).
This file is part of the GNU C Library and is also part of gnulib.
Patches to this file should be submitted to both projects.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 3 of the License,; if not, see
<>. */
#ifndef _GETOPT_EXT_H
#define _GETOPT_EXT_H 1
/* This header should not be used directly; include getopt.h instead.
Unlike most bits headers, it does not have a protective #error,
because the guard macro for getopt.h in gnulib is not fixed. */
__BEGIN_DECL)
__END_DECLS
#endif /* _GETOPT_EXT_H */
|
https://emba.gnu.org/emacs/emacs/blame/master/lib/getopt-ext.h
|
CC-MAIN-2020-34
|
refinedweb
| 113
| 65.93
|
Hello experts,
I'm trying to gather configuration information from Hitachi arrays by using SMI-S. I have no issue to discover configuration information for AMS and HUSVM storage arrays because I just connect directly to Command Suite server with root/smis/current namespace.
But VSP G arrays have embedded SMI-S provider, I can't connect to this Provider directly with /root/hitachi/smis namespace and I have no idea why it's happen. I use SMI-S client to check connectivity and it returns "test communication failed, but port 5989 is listening and user is exist, license also is installed.
I have used next manual to configure SMI-S provider for VSP G arrays in the right way (SRM: Enable a HDS onboard SMI-S provider - SolarWinds Worldwide, LLC. Help and Support ) .
Could anyone help me with the issue? Maybe some steps are missed in the manual?
I am in the process of configuring this same connection. I know there is an option for the SVP embedded version , and the Command Suite version. Looking for tips. I need to configure this for G400 and HUS100.
|
https://community.hitachivantara.com/thread/12882-cant-connect-to-vsp-g-storages-by-using-smi-s
|
CC-MAIN-2019-09
|
refinedweb
| 187
| 65.12
|
XPath's name, local-name, and namespace-uri functions
Discussion in 'XML' started by Marc A. Criley,,562
- Simon Harris
- May 10, 2005
java.net.URI.relativize(java.net.URI) not really workingStanimir Stamenkov, Aug 12, 2005, in forum: Java
- Replies:
- 1
- Views:
- 2,569
- Stanimir Stamenkov
- Aug 17, 2005
XSLT: Relative URI "my.dtd" can not be resolved without a base URIPavel, Aug 2, 2004, in forum: XML
- Replies:
- 2
- Views:
- 1,777
- Peter Flynn
- Aug 4, 2004
Re: XSLT: Relative URI "my.dtd" can not be resolved without a base URIetheriau, Aug 23, 2004, in forum: XML
- Replies:
- 1
- Views:
- 736
- Pavel
- Aug 23, 2004
How to get absolute uri by combining the baseuri and the relative uri in an html page?Turbo, Oct 30, 2006, in forum: Javascript
- Replies:
- 2
- Views:
- 195
- Turbo
- Nov 1, 2006
|
http://www.thecodingforums.com/threads/xpaths-name-local-name-and-namespace-uri-functions.168491/
|
CC-MAIN-2015-11
|
refinedweb
| 139
| 58.92
|
0
This is my prompt. Write a program that asks the user how many twin primes the user wants to find, reads in that goal, and then successively examines the numbers starting at 2 to see if the number is a twin prime. The program stops when the specified number of twin primes has been found. It then prints out the twin primes found.
I've searched this forum and I found a lot of stuff on twin prime numbers up to 100, but I can't figure out how to make it defined by the user. It's been years since I've done C++ so I've forgotten a few things, but I 'borrowed' the loops from cgcgames, a user here.
Here's what I have:
#include <iostream> #include <math.h> using namespace std; int main () { int testnumber = 3; //declares the number that will be tested on. this is the first prime int findingprime = testnumber - 1; // the number that is used to divide by testnumber to check if there is a remainder int numberoftwins; // number of twin prime numbers cout << "Twin Prime Numbers \n"; cout << "---------------------------------------------\n"; cout << "How many twin prime numbers would you like to find?" << endl; cin >> numberoftwins; int number=numberoftwins*2; // sets number to twin values(doubles) while (testnumber < 100 how do I make this defined by the user?) { //loops while primes are under 100 if (testnumber%findingprime == 0) { // check for to see if there is no remainder and if there is its not a prime number and adds 2 the testnumber to start testing the next number testnumber = testnumber + 2; findingprime = testnumber - 1; } else { //else if there is a remainder it takes one of the finding prime variable and reruns the loop findingprime = findingprime - 1; } while (findingprime == 1) { //if it goes through all the looping and finding prime is equal to 1 then that means testnumber is a prime cout << testnumber << "\n"; //print the prime to the screen testnumber = testnumber + 2;//moves onto next number findingprime = testnumber - 1; // sets findingprime to one lest then testnumber } } cout << "jhijhgijfhg" << endl; // this line has no purpose cin.get(); // waits for user to press enter to stop the program.
|
https://www.daniweb.com/programming/software-development/threads/380889/finding-twin-prime-number-specified-by-user
|
CC-MAIN-2017-17
|
refinedweb
| 361
| 67.42
|
package Sorting; import javax.swing.JOptionPane; public class Sorting2 { public static int s[] = new int[100]; public static void main(String[] args) { String ask = ""; for (int i = 0; i< 5;i++){ ask = JOptionPane.showInputDialog("Enter: "); s[i] = Integer.parseInt(ask); System.out.println(s[i]); } for (int x = s.length-1; x>= 0; x--) { System.out.println(x); } } }
This is my code ,i want to sort in descending the input that i made,,the problem is it does not output the descending order of the numbers i input. This is my sample input:
Enter: 2 6 8 5 7 9
Output: 9 8 7 6 5 2
But the output is:
Output: 100..............1,
because of the [100] i assigned in int [s], wil somebody help me? i really dont know how to fix it. I hope you can help me. Thank you in advance.
|
https://www.daniweb.com/programming/software-development/threads/177418/how-do-i-sort-in-descending
|
CC-MAIN-2018-17
|
refinedweb
| 145
| 68.47
|
Visiting New Orleans on a budget and in only a weekend
Enjoying the cultural jewel that is New Orleans
When I first visited New Orleans in the summer of 2003, I was only slightly impressed. A large number of the buildings in and around the French Quarter were crumbling and derelict. Bourbon Street seemed very over-hyped, when all I could focus on was the filth on the sidewalks and the smell of urine at every corner (especially to an 18 year old who couldn't enjoy the libations most typically visit for).
The food and coffee were highlights, even then however. We stayed in an old bed and breakfast in the Garden District, that according to their website was haunted. It was even featured on one of those haunting shows. The home was old and beautiful; decorated in period theme. The "haunting" aspects, such as the television being turned on by itself after we first checked in, were very theatrical. Perhaps though, it was the fact I had seen the innkeeper flicking with a switch under his desk while walking past him with our luggage. The entire attic level was deemed not safe to spend the night in, due to lack of easily accessible fire exits; however, the owners had put games and a Ouija board upstairs and guests were allowed to spend time during the day lounging around. The majority of pictures our family has from the B&B were actually taken up in the attic.
The day before we were set to leave, I remember saying to my mom "Well we can say we visited New Orleans, but I don't think I will ever come back". How wrong was I.
About one week later I was recounting some of the fabulous meals. The next week I found myself reminiscing of the mornings sitting in a courtyard of a French Quarter coffeehouse, while my mom and her boyfriend read the paper, and my brothers and I people watched and chuckled at the eccentric locals, or "Quarter rats" as many adoringly refer to themselves. Maybe it was the whole "Big Easy" mentality. Life indeed did seem more laid-back and easy. About a month later my mom read about the upcoming Southern Decadence Festival.
It was an annual festival held in the French Quarter on Labor Day weekend. Next to Fantasy Fest in Key West, it was known as one of the largest gay pride festivals. Party-goers drink to excess (it is New Orleans, after all) and the parade that marches through the tiny Quarter streets features patrons dressed as their favorite southern decadent character.
We decided to return to the centuries old city and give it another chance. This time the statement to my mother before we left was "I will live here someday". While I still have yet to fulfill that wish, my mother and I have made pilgrimages to the old city from Southwest Florida, on average, every four to six months ever since. The visits usually take place as roadtrips, and we usually only stay an average of three nights.
Many travelers these days find that they cannot afford to take those week-long vacations of the past, and instead opt for shorter, sometimes drive-distance trips. This article will highlight my personal favorite parts of the city and some venues we try to see each and every time we make the trip to this melting pot southern city.
Is it safe to visit?
If you have never been to New Orleans, there is no better time than the present to visit. Since Hurricane Katrina, the city has bounced back quite nicely; especially if you confine your trip to the 78 square blocks that encompass the French Quarter, or Vieux Carre (old square) as the French founders referred to it. On the east bank side (and the center of this metropolitan area), the French Quarter was one of the few areas of the city to escape flooding and major structural damage.
The city itself is known as a fishbowl, due to the positioning between the Mississippi River in the lower region and Lake Pontchartrain on the upper. The land in between sits below sea level, and as such, fills as a fishbowl when torrential downpours such as with Katrina occur. The Quarter sits higher than the surrounding land, thus keeping it drier than the rest of the city.
One fun fact (or not so fun) about the city of New Orleans is that it is sinking at a rate of one inch per year. It is believed that it has been sinking, for the most part, since it was founded. Over-development, drainage and natural seismic shifts are all believed to be contributing factors to the sinking, according to the journal Nature.
Westbank/ Algiers Point
On the west bank, the town of Algiers was also largely spared the complete devastation. This small town is one of the top, free activities, I recommend visiting during your weekend getaway. Algiers Point is situated directly across the Mississippi River from the French Quarter. From a dock there, adjacent to the Riverwalk and immediately behind the Audubon Aquarium of the Americas, one can catch a free ferry across the river. The ferry runs from 6am until 12:15am, every day. If you visit during Mardi Gras, be prepared to possibly wait for a second docking, as the locals of Algiers fill the ferry all day to catch the parades and festivities in New Orleans.
Taking fifteen minutes to reach the west bank, both tourists and locals alike use this ferry as the primary means of transportation between the two shores. For one dollar, you may drive your car onto the ferry, or pay the toll for the Crescent City Connection bridge and drive around the town. While it is a mainly a residential neighborhood, there are a few quaint bars and restaurants near the river. There is no better place to view the New Orleans skyline, than from the west bank, while walking along the levee.
Cafe Du Monde & The French Quarter
Arriving back on the east bank, it is imperative that one indulges in a cafe au lait and a beignet. This combination of chicory coffee with milk and french doughnuts (fried dough sprinkled in powdered sugar) is a New Orleans staple. There is no better, or more famous cafe to enjoy this snack at, than Cafe Du Monde in the French Quarter. It is a 24 hour "coffee stand", that has been a staple of the city since 1862. It is only closed for Christmas Day, or when a "hurricane passes too close to New Orleans" as the website boasts.
During the day, especially in season and during one of the many festivals the city is known for, the line to snag a table (all self-seating here) is sometimes stretched past the cafe itself and several yards towards Jackson Cathedral. Local pan-handlers, playing saxophone or singing or even telling jokes, set up shop right outside the main entrance. While of course looking for a buck or two in return (there are a great deal of people in this city who make their living as "street-performers of some sort, all year round), the entertainment is usually welcome and is really as New Orleans as red beans and rice on a Monday.
My personal favorite time to visit Cafe Du Monde is between 9pm and 12am. There are a plethora of empty tables and the cafe au lait gives a much needed boost to get through a long night braving the crowds of Bourbon Street. Beware germ-a-phobes, this outdoor cafe is covered only by an awning and pigeons run rampant 24 hours a day through the stand. Add to that powdered sugar coating everything from the tables, to the chairs to the floor and for an unprepared patron it may all be slightly overwhelming. But I promise, the freshness and taste when you bite into a beignet, and the strong flavor of the cafe au lait, more than make up for the inconveniences of the outdoor coffee house.
French Market
If leaving Cafe Du Monde anytime around the hours of 9am and 6pm, any day of the week and 365 days out of the year, head "downriver" or away from Riverwalk, and take in the French Market. Covering roughly six blocks, the main entrance features a farmers market where locals come to sell fresh produce and local hot sauces and spices. There are also several eateries, specializing in seafood and Cajun or creole delicacies. The rear portion of the market is a true flea market, with locals selling handmade crafts and candles or knock-off sunglasses and purses.
Even if you do not purchase anything in the market, this historic market has been around for three centuries and is well worth the visit. My personal favorite part of the market is listening to many of the vendors speaking in their native Acadian tongue and trying to make out the Cajun dialects. And if you love a bargain, haggling is well accepted and expected in the flea market area.
Fauborg Marigny
When leaving the market, continue to head south towards Esplanade Avenue. After crossing Esplanade you will be entering the neighborhood known as Fauborg Marigny. Back in the 19th century the neighborhood first became popular for white creole gentlemen to set up homes for their colored mistresses and their illegitimate offspring.
The neighborhood is much like the French Quarter, with the eclectic colored cottages and serenity of the neighborhood streets. Frenchmen Street is the Marigny's answer to Bourbon, with more locals. From jazz to latin to reggae clubs, there is something for everyone. Of course there are numerous late night eateries as well.
Dinner in the Quarter
Heading back into the French Quarter for dinner, my all time favorite New Orleans eatery is Oceana Grill. Located on Conti, between Bourbon and Royal, this family owned and operated seafood restaurant & bar boasts being open until 1am, although many times, depending on the crowd, they stay open even later. Their grilled oysters are well-known and to die for. Also serving breakfast from 8am until 1pm, this restaurant really does have it all. If you are too tired from your busy day to leave your hotel room, no need to worry, they also deliver anywhere in the Quarter.
Lakeview
If you have access to a car, I strongly suggest venturing out a little further from the French Quarter area. Take a trip north on Elysian Fields towards the University of New Orleans campus. In the Lakeview section of town, behind the campus off of Lakeshore Drive is a small waterfront park. Situated on the banks of Lake Pontchartrain, visitors can climb the levee and take in the breathtaking views of the Lake. Cement steps, that look much like bleachers in a football stadium, are the perfect place to relax and enjoy the serenity of the lake.
Garden District/ St. Charles Avenue
Head back to the center of town, and be sure to hop onto the St. Charles streetcar. It is imperative that you refer to it as only a streetcar, not a trolley or tram. For over 165 years, these streetcars have transported locals and tourists alike from Canal Street, through the Garden District and past Loyola & Tulane Universities. After passing Audubon Park, it follows the Riverbend and ends at Carrollton Avenue. For $1.25 you can ride as far as you need. Or, purchase a one or three day VisiTour pass, and ride as often as needed.
Back in the Garden District, there are many restaurants dotting St. Charles Avenue. The atmosphere is much more laid back and relaxed here, than in the Quarter. There are many self-guided tours on the internet or in travel books that visitors may partake on. Sandra Bullock's home is listed on a few of these.
Uptown
A few blocks toward the river sits Magazine Street. Stretching for roughly six miles, from Audubon Park downriver to the French Quarter, this historic street is well known for its antique shops, as well as eclectic eateries and shops.
Head uptown, towards Audubon Park, and walk a few blocks north to Prytania Street. Here is the location of The Creole Creamery. By far some of the best ice cream in town, they specialize in obscure flavors, which change daily. My favorite to date is the lavender honey. Don't be upset though if you return the next time and do not see your former favorite; just pick another and chances are, you won't be upset for long.
While in the Uptown and Audubon area, you may want to visit the Audubon Zoo. You may also purchase the Audubon Experience Package which also allows you access to the Audubon Aquarium of the Americas as well as the Entergy I-Max theater and the Audubon Butterfly Garden and Insectarium, back in the French Quarter.
Metairie
The final highlight of your weekend getaway must include hopping onto I-10 west and driving to Metairie. Get off on the Airline Drive exit and head right. There you will find an excellent, hole in the wall seafood shack called RiverPond. The crawfish (in season) is by far the best cooked and the largest around. They serve fresh seafood, as well as po' boys and a few other staples. They also serve alcohol (again, it is New Orleans). The laid-back atmosphere is welcoming and the seating area is always clean. Every time we have gone, the owner has been hard at work behind the bar and in the kitchen, yet still has time to chit chat with the guests, most of which are locals. Trust me, the drive outside of the metropolitan area is well worth it, once you truly experience eating crawfish with red potatoes and corn on the cob served a la carte.
This article touched on just a slight few of the hundreds of activities to do, and thousands of restaurants to patronize while in the New Orleans area. You can visit every month and still discover something new each time you return. I hope though, I was able to highlight a few venues that you and your family will find as magical and welcoming as mine do.
I will be visiting New Orleans for the 2nd time this April. I am from Australia & fell in love with this place on my 1st visit in 2012. Thank you for your suggestions. I will now be visiting places I didn't get to see last time. Your information is extremely helpful. Thank you.
Congratulation to hub win, interesting hub, well done:)...B
Nicole welcome to HubPages. Great hub! Makes me want to go back to New Orleans and have a muffuletta sandwich at the Central Grocery in the French Quarter. It is an old family grocery store on Decatur Street that has a sandwich counter. Try it next time you are there!
One of my favorite cities ever. I've been there twice and I don't really travel much so that's saying a lot for me. There are plenty of mornings where I find myself longing for some cafe du monde 'chickory' coffee and a Bigne (?.... I wish a could spell this French donut properly).. Great post. Voted up awesome
Nice Blg Nicole.... Makes me wanna go there.....Maybe....lol
Very interesting. This hub gives you a flavor of some expectations if you decide to visit New Orleans. Thank you.
11
|
https://hubpages.com/travel/Visiting-New-Orleans-on-a-budget-and-in-only-a-weekend
|
CC-MAIN-2018-05
|
refinedweb
| 2,592
| 69.01
|
List
ion-list
ion-list
The List is a widely used interface element in almost any mobile app, and can include content ranging from basic text all the way to buttons, toggles, icons, and thumbnails.
Both the list, which contains items, and the list items themselves can be any HTML element.
Using the List and Item components make it easy to support various interaction modes such as swipe to edit, drag to reorder, and removing items.
Instance Members
closeSlidingItems()
Close any sliding items that are open.
Input Properties
Advanced
Enable the sliding items.
import { Component, ViewChild } from '@angular/core'; import { List } from 'ionic-angular'; @Component({...}) export class MyClass { @ViewChild(List) list: List; constructor() { } stopSliding() { this.list.enableSlidingItems(false); } }
|
https://ionicframework.com/docs/v3/3.6.1/api/components/list/List/
|
CC-MAIN-2019-13
|
refinedweb
| 118
| 55.54
|
find code problem - Hibernate
hibernate code problem String SQL_QUERY =" from Insurance
as insurance where insurance.
lngInsuranceId='1'";
Query query...
thanks
shakti Hi friend,
Your code is :
String SQL_QUERY =" from
sql query - SQL
sql query hi sir,i have a month and year numbers,when i am enter a month and year in sql query then i want results for 1st day of month to last day... java.sql.*;
import java.util.*;
class Select {
public static void main(String[] args
SQL query - SQL
SQL query hi sir/Madam i am using MS Access where
i have table...,Paid from Fees_Struc where id=1");
String due="";
int paid=0;
if(rs.next... to system date and Paid=0 then i have to put some value to Penalty Field and it has
SQL Query - JSP-Servlet
SQL Query
AS mysql backend updation query shows a syntax error. I gave the full query and the generated error here. Please send me the correct query anyone.
st.executeUpdate("update stud_detail set name='"+newname
hibernate - Hibernate
();
//Using from Clause
String SQL_QUERY ="from Insurance insurance";
Query query = session.createQuery(SQL_QUERY);
for(Iterator...hibernate hi i am new to hibernate.
i wan to run a select query
how to call list objects as string into my sql query?
how to call list objects as string into my sql query? how to call list data as string into my sql query so that i can retrieve all values from database?
List has data retrieved from xml(using xmlSAXparser
numbers of sids.i want to delete the sid based on the mid.for that i need sql query plz help to me...sql query hi friend,
Im doing a project,in that a main id
display sql query in hibernate
display sql query in hibernate If you want to see the Hibernate generated SQL statements on console, what should we do
JDBC connection and SQL Query - JDBC
or udate Query it is not accepting as the format for them is executeQuery(String...JDBC connection and SQL Query Hi,
I'm reading a all files one after the other in a directory in java. storing the values in an array of string
sql query
sql query SQL QUERY BROWSER
declare @cout00 int
declare @cout01 int...);
this is the query i have written for the table "dpscomp" -
station date month...
select @cout00=count(*) from aws.dpscomp where ra='0' and RAcal='0'
print @cout00
SQL QUERY
Gopal oracle C
Now i need to write a query "which...SQL QUERY am a having a table 'PROGRAMMER' with columns... C pascal
Bhanu Sql
SQL query
SQL query I need to combine two tables in order to get the values. As an example we have three tables
having namely usertable,job table... this how can get the employee name having access to the jobs. I need to have
Hibernate Native SQL Query Introduction
In this section, you will learn Hibernate Native SQL query
sql query - JDBC
sql query I need a SQL query to add data into database
Hibernate SQL Query/Native Query
This tutorial describes Hibernate SQL Query, which is also known as Native Query
Hibernate Named Native SQL Query
In this section, you will learn Named Native SQL Query in Hibernate
SQL QUERY - JDBC
SQL QUERY I m running a query using apache tomcat the sql query is on adding an employee in the database whenever i click on add after inserting the values i am getting a java.lang.nullpointer exception
Sql query from oracle
Sql query from oracle Please help me that I want to get the table names form the existing database who does it having eid coloumn
plz provide me query in oracle database - SQL
SQL Query Hi
I would like to know how to create a SQL query which would copy values from a field which contains multiple values to an existing table. I created table 2 and defined the fields.I tried different types of insert
Sql query Duplicate
Sql query Duplicate I have a Employee table with duplicate ID values. How can I find out duplicate records?
Hello Friend,
We have...
3 D Delhi
Then we have used the following query to find the duplicate data
Doubt In Sql query
tries with this query but it is returning redundancy records.
select * from...Doubt In Sql query Hi
Have a glance @.
I Need to fetch all the distinct records of countries with the latest country
delete query problem - Hibernate
,
String hql = "delete from Insurance insurance where id = 2";
Query... = sess. beginTransaction();
String hql = "delete from STUDENT where name = 'mitha...=query.executeUpdate();
tx.commit();
i coded the above query but the IDEA 6.0
hibernate - Hibernate
();
session =sessionFactory.openSession();
//Create Select Clause HQL
String SQL_QUERY ="Select Branches.branch_id from Branches branches";
Query query = session.createQuery(SQL_QUERY);
for(Iterator it=query.iterate();it.hasNext
Hibernate Named Native SQL Query using XML Mapping
In this section, you will learn Named Native SQL Query using XML Mapping in Hibernate with an example
hi i m new to hibernate..plzzzzzzzzzzzzzz help me.... - Hibernate
";
//String SQL_QUERY = "from indiabulls.test.Contact contact";
Query query..._QUERY = "from Contact contact";
Query query = session.createQuery(SQL_QUERY... poonam
This is wrong query. you are using wrong query.
String SQL_QUERY
sql query to get data from two tables
sql query to get data from two tables how can i get the data from two different tables?
Hi Friend,
Please visit the following link:
JOIN Query
Simple Query
Thanks
hibernate - Hibernate
();
//Create Select Clause HQL
String SQL_QUERY ="Select Branches.branch_id from Branches branches";
Query query...*,resultset*,(query|sql-query)*)".
What should I do to rectify this?
sql query to get name,age,phone,address from tables t1,t2,t3,t4,t5 ..
sql query to get name,age,phone,address from tables t1,t2,t3,t4,t5 .. ... , address FROM t1 order by name";
this is for 2 tables :
query ="SELECT t.name... by name";
i want for 12 tables :
i want to fetch name age pwd phone address from 12
SQL Query
SQL Query Selecting the third highest salary of Employee without using any subquery?
Here is a query:
SELECT salary FROM employee ORDER BY salary DESC LIMIT 2,1
Sql Query
Sql Query Is this query work in Db2 or not ?
Select * from FORUM LIMIT 2
sql query
sql query two tables are emp,loc
write a query to display all the emp information whose locname not equal to bangalore
upgrading sql query join
upgrading sql query join upgrading sql query join
Hibernate - Hibernate
= sessionFactory.openSession(); String SQL_QUERY ="from Procedure proced"; Query query = session.createQuery(SQL_QUERY); for(Iterator...Hibernate SessionFactory Can anyone please give me an example
Hibernate joining multiple tables
mean by the line?
String sql_query = "from
Product p inner join p.dealer as d... Friend,
The query is incomplete.
Here is a complete query:
String sql_query... JOIN
Thanks
Hai,
The query you have given was the plain old sql
Hibernate Select Clause
, insurance.investementDate)
from Insurance table.
Hibernate generates the necessary sql query and selects
all the records from Insurance table. Here... from Insurance
table using Hibernate Select Clause. The select clause
picks up
Create table and insert data by sql query
Create table and insert data
by sql query... to connect java application and execute
sql query like create table in mysql database, insert some values and retrieve values from
the table.
Before running
optimize sql query
optimize sql query How to optimize sql query in mysql?
Thanks
Hibernate - Hibernate
Hibernate pojo example I need a simple Hibernate Pojo example ... java.util.*;public class pojoexample { public static void main(String arg...){ System.out.println(e.getMessage()); } finally{ } }}hibernate mapping <class name
SQL QUERY ERROR
SQL QUERY ERROR Im writing a query which shows error of INVALID CHARACTER
The Query is
Insert into
PMST_EMP_MST(PMSNUM_EMP_ID,PMSSTR_EMP..._UserType+",'"+user_password+"');";
AND THE DATA WHICH IS INSERTED FROM
string
string String helloString = new String(helloArray);
System.out.println(helloString);
i am unable to understand this. could u plz explain
String
< s.length(); i++) {
String st = s.substring(i, i + 1... characters in string?
import java.util.*;
class RemoveDuplicateCharatcersFromString
{
public static String removeDuplicates(String s
string
string a java program using string function to input any string... ArrangeStringAlphabetically
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.print("Enter string
Hibernate Architecture
.
Hibernate automatically generates the SQL query automatically to perform...,
querying, updating and deleting the data from database.
Hibernate is a good... Transaction management component
of Hibernate or JTA. I provides the API for efficient
string
string just i want to a program in a short form to the given string in buffered reader for example
input string: Suresh Chandra Gupta
output: S. C...;
public class StringTest {
public static void main(String [] args
string
string how do i extract words from strings in java???
Hi...: ");
String st=input.nextLine();
String str[]=st.split(" ");
for(int i=0... ExtractWords
{
public static void main(String[] args)
{
Scanner input
string
string program for String reverse and replace in c,c++,java...(String[] args)
{
String array[]=new String[5];
Scanner input...: ");
for(int i=0;i<array.length;i++){
array[i]=input.next
string
and also displaying that contain word?
Like I want to find "a" in the string....
Here is a java example that accepts a sentence from the user and a character. It then count the occurrence of that character in the string and display
Hibernate Named Native SQL in XML Returning Scalar
In this section, you will learn to execute Hibernate named native SQL query written in XML mapping file which return scalar values(raw values
Searching - Hibernate
();
String SQL_QUERY = "from RecordInformation as record where record.userid LIKE 'Sandeep' order by record.userid";
Query query = session.createQuery(SQL...Searching How we can search the record through Hibernate. As we do
Hibernate Criteria Queries - Hibernate
Hibernate Criteria Queries Can I use the Hibernate Criteria Query... static void main(String args[]) {
Configuration configuration = new Configuration();
// configuring hibernate
SessionFactory
Reagrsding Hibernate joins - Hibernate
Reagrsding Hibernate joins Hi, I am trying to make join in Hibernate... HibernateExample { /** * @param args */ public static void main(String[] args...{ // This step will read hibernate.cfg.xml and prepare hibernate question, i have downloaded the complete project from the roseindia site for the hibernate.thus i do have the firstExample.java ,contact.hbm
public static
PHP SQL Query Where Clause
;
from the sql query execution, we have created whereClause.php page.
First... PHP SQL Query Where Clause
This example illustrates how to create and execute the sql
org.hibernate.InvalidMappingException: Could not parse mapping document - Hibernate
();
session = sessionFactory.openSession();
String SQL_QUERY ="from Procedure proced";
Query query = session.createQuery(SQL_QUERY...?,sql-update?,sql-delete?,filter*,resultset*,(query|sql-query
PHP SQL Injection Example
PHP SQL Injection Example
This Example illustrates how to injection is used in the sql query.
The "SQL Injection" is subset.... By using a single quote (') they have ended the
string part of our MySQL query
Persist a List Object in Hibernate - Hibernate
Persist a List Object in Hibernate
Hi All,
I have a query on hibernate.
How to persist a List object in Hibernate ?
Can you give me... {
/**
* @param args
*/
public static void main(String[] args
in connectivity - Hibernate
in connectivity Hi,my first application in which i have used the hibernate and postgresql
that progrram is running while showing no error... insertted Hi friend,
This is connectivity and hibernate configuration
hibernate
hibernate Hi
Good Morning
Will u please send me the some of the tutorials of hibernate.Because ,i have to learn the hibernate.i am new to this its...;Hi Friend,
Please visit the following link:
hibernate annotations
hibernate annotations I am facing following problem, I have created 2 tables (student and address) with foreign key in address table. I am using hibernate annotations to insert records into these tables. But it is trying... FirstExample {
public static void main(String[] args) {
Session session = null
Hibernate - Framework
();
String hql="from Person p where p.firstName like :searchFirstName";
List pList...Hibernate where i get NamedSqlQuery examples? Hi friend,
Example of "NamedSqlQuery"
In this code "from Person p where p.firstName @ManyToOne persisting problem - Hibernate
Hibernate @ManyToOne persisting problem hello,
In my apllication... is using a join table. I followed examples I found on internet and at books. So I...(name="CLASS_ID")
private Integer id;
private String name;
@ManyToOne
i want display integer number in a string of statement
i want display integer number in a string of statement i want display integer number in a string of statement firstExample not inserting data - Hibernate
hibernate firstExample not inserting data hello all ,
i followed... for more information.
Thanks. ...
*
*/
public class FirstExample
{
public static void main(String
hi - Hibernate
Userin instances");
try {
String queryString = "from Userin";
Query...hi hi all,
I am new to hibernate.
could anyone pls let me know...: " + propertyName
+ ", value: " + value);
try {
String queryString = delete a row error - Hibernate
Hibernate delete a row error Hello,
I been try with the hibernate delete example (;
//=======================================
sess = fact.openSession();
String hql = "delete from Contact contact
|
http://roseindia.net/tutorialhelp/comment/13203
|
CC-MAIN-2014-42
|
refinedweb
| 2,169
| 56.66
|
/* Case-insensitive string comparison function. Copyright (C) 1998-1999, 2005-2007 Free Software Foundation, Inc. Written by Bruno Haible <bruno@clisp.org>, 2005, based on earlier glibc> #if HAVE_MBRTOWC # include "mbuiter.h" #endif #define TOLOWER(Ch) (isupper (Ch) ? tolower (Ch) : (Ch)) /* Compare the character strings S1 and S2, ignoring case, returning less than, equal to or greater than zero if S1 is lexicographically less than, equal to or greater than S2. Note: This function may, in multibyte locales, return 0 for strings of different lengths! */ int mbscasecmp (const char *s1, const char *s2) { if (s1 == s2) return 0; /* Be careful not to look at the entire extent of s1 or s2 until needed. This is useful because when two strings differ, the difference is most often already in the very few first characters. */ #if HAVE_MBRTOWC if (MB_CUR_MAX > 1) { mbui_iterator_t iter1; mbui_iterator_t iter2; mbui_init (iter1, s1); mbui_init (iter2, s2); while (mbui_avail (iter1) && mbui_avail (iter2)) { int cmp = mb_casecmp (mbui_cur (iter1), mbui_cur (iter2)); if (cmp != 0) return cmp; mbui_advance (iter1); mbui_advance (iter2); } if (mbui_avail (iter1)) /* s2 terminated before s1. */ return 1; if (mbui_avail (iter2)) /* s1 terminated before s2. */ return -1; return 0; } else #endif { const unsigned char *p1 = (const unsigned char *) s1; const unsigned char *p2 = (const unsigned char *) s2; unsigned char c1, c2; do { c1 = TOLOWER (*p1); c2 =); } }
|
http://opensource.apple.com/source/gnutar/gnutar-450/gnutar/lib/mbscasecmp.c
|
CC-MAIN-2016-36
|
refinedweb
| 216
| 63.59
|
IaGraph: A Python Package for Quick Interactive Graphing
This is a package of interactive graphing tools, built upon the
Climate Data Analysis Tools (CDAT)
package (v4.0).
IaGraph will create line plots,
scatter plots, and contour plots.
The current version of the package is 0.3.1.
The page is subdivided into these categories:
If you don't find the information you're looking for on this page, see the manual.
The routines in this package allows you to make quick plots of atmospheric sciences data with a single line of Python code. I try to emulate IDL syntax, but there are substantial differences. Perhaps 30% of the time, the plot generated will also be suitable for publication, and procedures in this package will allow you to write those plots to a Postscript or GIF file. The other 70% of the time, however, you will want a more complex plot for publication, which this package cannot make.
Because
IaGraph is designed
to be simple as opposed to powerful,
this web page and the examples it links to
should be enough for most users. If you'd like more information
about the structure of the package, troubleshooting, etc., see the
manual.
All procedures are the same name as the module they are contained
in (and there is only one non-private procedure in that module).
Thus, the
plot function, which makes an x-y plot,
in the
plot module.
Normally if you import a package via a plain
import you have to specify the entire package/module
path in order to access a function
(e.g.
IaGraph.plot.plot).
Since the purpose of this package is to allow you to do quick and dirty
graphing, I recommend you put the following lines in
your .pythonrc.py file, which starts up
automatically each time you do an interactive session:
import IaGraph
from IaGraph import *
The first import line gives you access to the package's system variables (this is optional; you don't need to do this import if you are not planning to change any of the settings stored in the system variables). The second import line allows you to access all key package procedures (see the "Module Listing" section below) by procedure name, without needing the package and module names.
To plot an x-y line plot of vectors
x and
y
on screen just type:
>>> plot(x, y)
To make a contour plot on screen of
data,
where the columns of
data are indexed by vector
x and the
rows of
data are indexed by vector
y,
type:
>>> contour(data, x, y)
In plots of quantities on the Earth, usually
x is longitude and
y is
latitude, where
data has rows of constant latitude.
When you execute a
plot or
contour
command, any preexisting plot in the active canvas is replaced by the
new plot. Thus, the package currently can only make one plot at a
time.
To write the last plot made
(i.e. the plot specified by the
IaGraph
"active canvas" system variable) to the Postscript file plot.ps, type:
>>> active2ps("plot.ps")
Writing GIF to a file is done similarly:
>>> active2gif("plot.gif")
Overplotting additional plots is done using the
oplot and
ocontour commands,
for overplotting line and contour plots, respectively.
By default, the active canvas is in window 0. To change the active canvas to a new window (window 1), use:
>>> window(1)
Subsequent plotting commands will be directed to the new window. Note that the old window is not closed and still remains in memory for later editing.
A summary list of bugs and fixes, updates to the package, and a summary of the version history (with links to gzipped tar files of previous releases of the package) is found here.
[Back up top to the Introduction.]
For more information on any command, type
help(cmd
), where cmd
is the name of the command (e.g.
plot). The
command docstrings give detailed information regarding
keyword options and settings.
By looking through a few examples, you'll find out 90% of all you need to know about this package:
Use
help to list the codes for the
available symbol codes, linestyles, etc. for each routine.
Finally, here are some web pages that provide quick summaries
of additional topics:
psym)
linestyle)
ctindex)
For more information see the concise package description and the manual.
[Back up top to the Introduction.]
All modules in the package are listed below. Only "key" commands
are made available by the
from IaGraph import *
command; all other modules need to be imported by the full
package/module name.
The "Module Name" column provides links to the module source code.
The "Pydoc" column provides links to
documentation produced from the module docstrings by the
pydoc tool.
The "Key?" column notes whether the module contains key package
commands or not (key commands are made readily available via
a
from IaGraph import * statement).
[Back up top to the Introduction.]
I've only tested
IaGraph on a
GNU/Linux
system, though
it should work on any Unix platform that runs
CDAT.
Since I'm distributing the package as a gzipped tar file, if you're using Windows email me about getting the source code or download the modules one at a time from the module listing section above.
Python:
IaGraph has been tested on and
works on v2.2.2. and 2.3.3.
Full functionality of
IaGraph
requires the following packages and modules
be installed on your system and
findable
via your
sys.path:
cdms: Climate Data Management System (in CDAT v4.0)
MA: Masked arrays operations package (v11.2.1 or higher)
Numeric: Array operations package (v22.1 or higher)
vcs: Visualization and Control System (in CDAT v4.0)
Both
cdms and
vcs are part of the
Climate Data Analysis Tools (CDAT).
Numeric and
MA are part of the
Numerical Python (Numpy)
package.
Installation of Numpy is trivial.
Installation of CDAT,
on the other hand, is more difficult
(see their web site for details).
Nonetheless, without the CDAT packages,
IaGraph cannot
do much (only
plot will work without CDAT, and even then
in only a limited way).
Package
IaGraph itself is written entirely
in the Python language.
First, get the following file:
Expansion of the tar file will create the directory IaGraph-0.3.1.1. This directory contains the source code, the full documentation (HTML as well as images), a copy of the license, and example scripts.
To unzip and expand the tar file, execute at the command line:
gunzip IaGraph-0.3.1.1.tar.gz
tar xvf IaGraph-0.3.1.1.tar
There are a few ways you can install the package. For all these methods, first go into the IaGraph-0.3.1.1 directory:
This will install the packageThis will install the package
python setup.py install
IaGraphin the default site-packages directory in your default Python. You'll probably need administrator privileges, however, in order to do this install.
This will install the packageThis will install the package
python setup.py install --home=~
IaGraphin the directory ~/lib/python/IaGraph (where ~ means your home directory). However, you'll need to make sure ~/lib/python is on your path.
import IaGraphcommand only looks for a directory named IaGraph on your Python path and executes the __init__.py file in it. Of course, you'll have to make sure the directory IaGraph is in is on your path.
WhereWhere
import sys
sys.path.append('newpath')
'newpath'is the full path of the location you're appending to your Python path. Thus, if the directory IaGraph is in a directory /home/jlin/lib/python,
'newpath'is
'/home/jlin/lib/python'. You can automate this by making the proper settings in a user customized .pythonrc.py file.
That's it!
The IaGraph-0.3.1.1 directory contains a complete copy of the documentation for the package, including images. Keep this directory around (you can rename it) if you'd like to have a local copy of the documentation. The front page for all documentation is the Doc/index.html file in IaGraph-0.3.1.1. The most recent copy of the documentation is located online here.
[Back up top to the Introduction.]
Unless otherwise stated, the Python via this email or at the University of Chicago, Department of the Geophysical Sciences, 5734 S. Ellis Ave., Chicago, IL 60637, USA.
The referring web page is part of the documentation
of the
IaGraph package and Dean Williams for lots.
|
http://www.johnny-lin.com/py_pkgs/IaGraph/Doc/
|
crawl-002
|
refinedweb
| 1,417
| 64
|
"slackplan9 bsd"
Staalmannen (not verified) - August 3, 2012 @ 2:28pm
+1 to the suggestion of a Linux distro with BSD user land, statically linked and rather than PATH environment variables etc a proper union mount system with "private namespaces" like in Plan9.
A working Glendix distro (clean Plan9, but with Linux kernel) that could be self-hosting would be very close to ideal (if enough people came to it and ported the most essential suckless applications/libraries to it).
Right Now! It's Sabayon
Don Johnson (not verified) - August 3, 2012 @ 3:32pm
I think Sabayon is about as perfect as it gets at right now. From it's default LVM installation, cutting edge rolling release based on Gentoo, KDE with good default software installed, stability, all codecs installed ready to rock and roll for doing/playing anything out of the box, beautiful startup screen, Rigo the NEW binary package manager isn't perfect yet, Hey it's new, but I do like it, very simple.
Ubuntu derivatives: Zorin & Pinguy
'Buntu User (not verified) - August 4, 2012 @ 10:54pm
Personally I like the Ubuntu derivatives Zorin and Pinguy. I would give a mention to Mint and Ubuntu. As one noted, one's favorite distro says more about the person than the distro.
All the major families are very solid. The choice is more the what philosophy appeals to me and which distro allows me to work my way.
Specifically I like the Ubuntu repository system and the generalist nature of the Ubuntu family.
Finally landed on SolusOS
Nicholas Ng (not verified) - August 6, 2012 @ 5:09am
After using Ubuntu for few years then switch to Linux Mint when Ubuntu switch to Unity, but now my heart goes to SolusOS!
Some other points:
* I like Debian-based distro
* Working out-of-the-box with flash (I know, but my work need it) and multimedia codecs ready
* With all my hardware working (no matter is closed source drivers or not) - no point installing the OS if the basic hardware (ie. wireless card, etc) are not working
* Up-to-date application
Debian Is The Best...
Swamoy (not verified) - August 11, 2012 @ 7:49am
My Ideal Distribution Is Debian As Well As Debian Based Distros Like Ubuntu,Mint And SolusOS.
My Ideal Distribution Configuration:
=> Based On Debian Testing. [SolusOs Testing or Linux Mint Debian Edition]
=> Ext4 File System. [Ubuntu,Mint]
=> Desktop Environment GNOME 2. [Debian Stable Squeeze]
=> All Multimedia Codec pre-installed. [Linux Mint]
=> Rolling Distribution. [LMDE Or Arch]
=> Supports Deb Packages. [Debian Based Distros]
=> Up-to-date Applications. [Debian Testing]
=> Fast And Stability. [Debian]
=> Good Community Support. [Ubuntu]
Light Austrumi type
nathan3 (not verified) - August 11, 2012 @ 12:47pm
Loved Austrumi for it's very light but stylish footprint.
I wish that Austrumi would re-incorporate analog modem support for us cheapy people who cannot afford broadband in the US.
Noob-Friendly & Geek-Tweakable*
Steve I. (not verified) - August 24, 2012 @ 4:52am
(*I know most Linuxes are very geek-tweakable)
Ideally something Debian/Ubuntu based for stability, updates and repository ease, BUT:
1- OS "Upgrades" at most yearly or (preferably) less (Like Ubuntu LTS), with no major changes to the look & feel.
2- All multimedia codecs should be installed by default, so people can just put in a DVD (or other media) and play it.
3-I'd REALLY like to see a Puppy-like installer that walks the noob-user through installation (and analyses all the hardware first) walking people through initial setup/default-application decisions with some basic queries about their qualifications and end-use.
For example:
A- "You have a powerful machine and can easily run any of the word processor options. If you are a power-user and require a large, fully-featured professional program (similar to MS Word), choose LibreOffice as your default word processing application. If you only need to write business letters, reports or your first novel, you should find AbiWord much simpler and less cluttered to use, yet still fully capable. It will also load and run significantly faster. Don't worry, both will be installed on your computer (you have plenty of available disc space) and you can always choose either one from the drop-down menu, we are just setting up the default program that opens via shortcut."
B- "Your computer has only moderately-powerful capabilities (CPU and RAM). For best performance, we recommend the XFCE desktop environment.
Screenshots of your other options, Gnome 2.x, KDE and Unity are shown below.
If you have mobile devices (tablets, phones) that use Unity or a similar interface, we recommend you choose it just to keep your user-experience consistent across platforms.
If you have used MS Windows extensively and have a hard time learning "computer stuff", we suggest you try Gnome 2.x at first as it will look and feel similar, though, unlike Windows, it can be extensively customized to your personal needs and tastes.
Remember, this is only the *default* desktop environment you are choosing. You have plenty of disc space so all four of them will be installed and available for you to try at your leisure. (And please do! You might just fall in love.) If, after playing around a bit, you find you like another desktop environment better, it is very easy to change the default environment that your computer boots into (of course all of them will still be available should you wish to use another at certain times).
This could seriously ease the main-streaming of Linux (and dispel the "which distro/desktop would compete with Windows FUD), as well as making setup easier for those of us who build boxes for friends.
It's a simple paradigm, give them options but with guided reasons and illustrations/examples for those who don't know what to choose.
Perhaps it could be the basis for a new installer?
If anyone here also reads ZDNET regularly... :P
Steve I. (not verified) - August 24, 2012 @ 5:08am
you are familiar with their trolling MS Fanboi Loverock Davidson..
Surprisingly, I have not seen him comment here and sometimes, in some really sick way, I actually miss his unassailable MS loyalty, mountains of FUD and sociopathic penguin-bashing.
I will therefore leave his comment in proxy:
"The ideal'distribution' is MS Windows." --LRD
I don't much care what it LOOKS like, so long as it ACTS right
Anonymous Egg (not verified) - August 27, 2012 @ 2:42am
S0 much wrong with linux distros that are all bling and no substance! Drop it guys, get the thing working, THEN decorate.
Here's the nightmare, a personal journey:
In fact, here's the average Linux live distro from wherever...
Load up: Specify locale in the boot parms.
Locale ignored, you're in the good old U/S of A, whatever. And you keyboard is presenting you with rubbi$h.
Dig around for keyboard settings, or (Lord forbid) dig away for config files.
But that's after your display doesn't work, and the menu entry doesn't help, just tells you it (mint13, that is) "has no proprietary drivers installed" when you waNt the damn proprietary drivers because the linux driver thingy is out of date & doesn't work with Firefox. Take a computer science class to learn how to install a working Nvid driver, only to be told you have to reboot your liveDVD (which you can't do without starting over, of course) for it to work. D'uh. It's a shorthand lie, anyway, you just need to know how to restart the screen or Xorg.
Only someone thought it was a good idea to disable ctl+alt+backsp. Who knows, maybe they were right at the time.
You can go to terminal at F1 & do such things, but a nooob has NO chance, he's off back to Redmond.
Ok, you have your screen properly resolved & now your keyboard properly set to wherever you dwell. If you're luck you can tweak it so it doesn't drive you up the wall by getting the caps lock by mistake. Or maybe you can't.
For security, you set/change passwords.
(Not that you are warned to do so. I wonder if there's a massive botnet of linux live distros? Should I patent the idea? I could be rich like Dotcom!)
Just for the hell of it, you swap session, but the keyboard defaults back to the good old U/S of A and you can't enter your shiny new pa$$word, so switch off & start the whole process again.
(Maybe Alt+SysRq reisub to do that, but it doesn't work because someone changed it to AltGr+SysRq & nobody told you.)
Look for ever-popular Firefox so you can find out how to sssort out the mess. Not there, some Kdweeb effort that half-works. Install FF, if you're lucky and you know the repository (as a noob, you're expected to be psychic). Find it's several versions old & doesn't work properly, but you can't feedback to Moz because it's not the latest version. Seek out how to get latest/beta FF & take the risk (Hey, don't distro writers know what FF is doing beforehand? Does no-one tell them there's a release schedule?).
Go to your mail. It needs JRE. You haven't got JRE. Or the plugin. More searching (for out-of date versions, but you don't know that until after they install). Spend a few minutes/hours seeking how to get up-to-date JRE & where/how to install it.
Same silly story with the Adobe Crash Player.
Get VLC, find out where the repository builders have hidden the codecs.
(By now, all the noobs have gone. They are in a heap by the window, crying out of frustration.)
Oooh! but just l00k at the pretty effects on the screen...
OK, take look at the text files a Windoh user might have. WHAT??!!!?? Where ARE they??? Zero files? Whaaaa?
Gradually you find out how to get ownership of your own files - ok, you have to do that somehow, but it's not a guided simple process for the nooby-person.
If you're relatively unlucky, there isn't support for NTFS. If you're REALLY unlucky, there isn't support for NTFS but the system doesn't say (because of linux snobbery?) and you corrupt your NTFS files. Or you have an old version which will corrupt your NTFS files without warning. Maybe on an un-re-formatted USB drive. Maybe important data, maybe not. Like you're going to re-format for a live DVD try-out?
Anyway, linux has great data-recovery routines. Pity about the indices & lost file-names & 10% lost corrupted data, though. Can't have been important.
Then you notice the date-time isn't set properly, because you miss a priority appointment.
By sheer chance you happen to be trying PClinuxOS, and some brain-dead joker has fixed the digital clock so that if you select London, it points you at Belfast with the time about five hours out. I can guess some Limey-hating Richard Head, whose uninformed personal politics over-ride any respect for the Project, plus lack of vigilance by aNy0ne else at all. But he did a thorough job & locked away the manual time-setting, too.
Which you might have a chance of finding if you knew the name of the clock widget thing, which you don't and can't find out without more hours at the forum. (They used to feed people to lions at the forums, didn't they? I can think of a candidate, if I can find him.)
Just maybe, you think, it's been fixed in an update, since your attempts at searches turn up nothing or far too much that's no use. See if the live edition can take an update (hey, way out of n00b territory by now..). Risky because the distro hasn't picked up the swap partition but after a few weeks's study you can fix that. But still the swap doesn't always cope so well with updates.
But you might regain space with bleachbit (if you know about it & where to install it; better do that before it's too late). Or one of the other space-reclaimers that don't work (or work too enthusiastically & are lethal in the hands of the ingenue). But they don't work anyway after a while on a live DVD because the systems are set up with some COW-son of a filesystem that doesn't reclaim space or indices or something unless you reboot (which you can't with a liveDVD...). So you end up with swappy panics that won't give the keyboard back so you can save work before giving in to the off button. And presumably shorten the life of your precious blu-ray reader.
(How do they expect servers to work? Reboot all the time?)
No updater. Install updater. Try the update. Get 563 broken packages and dependency hell if you try to fix it. Yeah, like I'm really going to install this one...
Lazy, shoddy, thoughtless distros. Just like the reason I left M*ckros**t.
But what the heck, it's free, and look at the NICE BLING, chaps.
~~~~~~~~~~~~~~~~~~~~
Credit where it's due. PClOS did give me an NVIDia driver straight away, thank the Lord, though it needed some tweaking. Why can't the others do that? And Puppy is a good dog, though a little eccentric at times. Don't even talk to me about Cinnamon, the essence of all that is wrong. But this facility is not available at this time.
Gimme GUI tools
Trying hard to love linux (not verified) - August 27, 2012 @ 1:19pm
My ideal might look like PCLinux2007 (KDE3). Ran it on this old laptop for 3 years. Later versions are too resource hungry (even LXDE). I want something that installs easily, finds my Wireless connection without messing around, and has simple graphical utilities for tweaking everything. As soon as I have to start editing config files, or use command line, I lose interest, and go back to my main PC running Windows. Currently I've settled for Lucid Puppy 5.2.8, which is eccentric, but tolerable, and at least has the Ubuntu repos available.
A little bit of everything (wow)
ahmedakg (not verified) - September 5, 2012 @ 3:20pm
1. Menu from (Linux Mint 13 Mate)
Reason: Search and Application is very easy and quick
2. Theme Customization from Windows 7.
Reason: You can easily change or customise the whole theme with slide show wallpaper, sounds, icons, window style etc
3. File Explorer from (Ideally Windows XP but a mix of Krusader and Dolphin is the next best thing)
4. Icons (Fedora) It Should be Glossy and HD Style
5. Dock Bar from Mac
6. Glass App Launcher Overlay like App Drawer from Android or iOS
7. HD Wallpapers selection
8. Easy to learn keyboard shortcuts for App Drawer, Change Workspace, Minimize All etc
9. Widgets (From Android OS) like "News Republic", Weather, Facebook, Twitter, Gmail... Sort of personalized desktop for who you are and feel connected to everything you're about.
10. Automatic File Sorting to Defined Folder like docs to docs and music to music and videos to videos no matter where you put them. they will be in their specific folder and you'll know where to find them after a year or two.
11. MS office with ribbon or libreoffice with ribbon
12. LightRoom 4 on linux (Wow)
13. glossy glass appearence.
14. Window Effects from mint 13 cinamon
15. bleeding edge stable updated os, security, Apps, Driver Support, Kernel etc
16. Multimedia Codecs complete full support
17. Flash And Java
18. IPv6 Compatible
19. Long Term Support
20. Software Manager (Like Google Play or Apple Appstore: Deepin Software Center is Close enough)
21. HDMI A/V out supported
22. Fonts (MS Core Truetype, Mac) Pre-installed
23. Software pre installed list
a. Picasa (Photo Manager)
b. Firefox & Chrome
c. Office
d. Skype (Original)
e. Photoshop Lightroom 4/5
f. vuze
g. Download Manager (Browser integration)
h. Video Editor & Slide Show Maker with Hollywood effects and auto movie maker feature
i. Video Trans-coder from any format to any other without loosing any quality or AV sync for dummies. click and done
24. Light on Resources
25. All processor architecture supported 32bit or 64bit
26. Big Red Shut Down button with sleep and restart in sub- menu
Please can someone make this for me??? I'm just an end-user full of desires for such a OS since the times of MS-Dos. Linux community never helped me then and now that there are so many developers, wont anyone of you make my dream come true :'(
ahmedakg@gmail.com in case someone wants to give me such a distro. Still dreaming and wishing ;)
Perfection
erixz (not verified) - September 13, 2012 @ 8:23pm
Cyclically (semi) rolling updates. That is stable updates a la Solus.
LXSkins script to change skins without login out/in in between from Cameleon Linux.
Hy-menu of Hybryde linux to change desktop/window manager without login out/in in between.
IceWM, Fluxbox, Open box, Crystal-FvWM, Deepin version of Gnome 2, KDE, Compiz.
Script to check for and run Chromium updates.
Deepin linux software center
Install without having to authenticate.
Software:
Libre office
VLC player
Chromium
my sort of a dream distro would have
koll apraas - September 20, 2012 @ 7:31pm
stability of debian and/or freebsd
light DE - preferably LXDE or lighter (window manager alternative?)
security and LTS
able to run on old and older machines
configurability/ customization - if i don't want it i can chuck it and if i want it, i can get it
userfriendliness of at least Linux Mint Debian Edition (LMDE)
good driver support
multiarch support
rolling release or if better alternative, then that.
out of the box audio and flash.
friendly community to aid you in your OS troubles.
Documentation that is easily comprehensible (or at least FIND-able.)
My dream OS should not hang when I am using virtualbox for 8 hours or more to run at least 2 commercial OSes, firefox with at least 90 or so tabs open, opera with 25 tabs open, chromium with 35 tabs open, a libreoffice calc, and writer being used along with a pdf reader/editor and VLC player belting out some tunes all at the same time --- I guess, I can dream on.
My Ideal Distro...
Zardoz (not verified) - December 20, 2012 @ 5:43pm
is 64 Bit
DE= Gnome2 Default (no Unity or Gnome3 garbage) IceWM, Fluxbox.
Fully editable GDM
is Compiz and Emerald Friendly
is Debian based.
has Dependable, current repositories.
has bleeding edge kernel
Nautilis
has no amazon search or other Canonical spyware crap!
In fact, just keep Canonical and Ubuntu away from it altogether!
Improved superiority
erixz (not verified) - December 27, 2012 @ 6:40pm
Basically Ultimate edition as a cyclically rolling release a la Solus
Hy-menu from Hybryde Linux or Look changer from Zorin OS to change between window managers without the nag of loggin in/out in between and all the window managers.
Easier installs a la Bodhi Linux or PC BSDs App café.
Menu look of Matriux linux.
The responsiveness of Backtrack.
A script to automatically check for and install updates for Chromium.
VLC
LibreOffice
Irfanview via Play on linux.
Hardware recognition of Knoppix.
and of course exchange the linux kernel with the optimized Exton kernel form linux_exton_net
starting to feel pretty good now. i just need for somebody to actually make this distro.
PS When is this poll ever go into an article, Tuxradar?
Post new comment
|
http://www.tuxradar.com/content/open-ballot-whats-your-ideal-distribution-look?page=1
|
CC-MAIN-2014-15
|
refinedweb
| 3,308
| 73.58
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.