content
stringlengths 228
999k
| pred_label
stringclasses 1
value | pred_score
float64 0.5
1
|
---|---|---|
blob: c26f4f86651c98e96a4d68b0f5764cc3f9c2fbf8 [file] [log] [blame]
/* BEGIN_HEADER */
#include "mbedtls/entropy.h"
#include "entropy_poll.h"
#include "mbedtls/md.h"
#include "string.h"
typedef enum
{
DUMMY_CONSTANT_LENGTH, /* Output context->length bytes */
DUMMY_REQUESTED_LENGTH, /* Output whatever length was requested */
DUMMY_FAIL, /* Return an error code */
} entropy_dummy_instruction;
typedef struct
{
entropy_dummy_instruction instruction;
size_t length; /* Length to return for DUMMY_CONSTANT_LENGTH */
size_t calls; /* Incremented at each call */
} entropy_dummy_context;
/*
* Dummy entropy source
*
* If data is NULL, write exactly the requested length.
* Otherwise, write the length indicated by data or error if negative
*/
static int entropy_dummy_source( void *arg, unsigned char *output,
size_t len, size_t *olen )
{
entropy_dummy_context *context = arg;
++context->calls;
switch( context->instruction )
{
case DUMMY_CONSTANT_LENGTH:
*olen = context->length;
break;
case DUMMY_REQUESTED_LENGTH:
*olen = len;
break;
case DUMMY_FAIL:
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
}
memset( output, 0x2a, *olen );
return( 0 );
}
/*
* Ability to clear entropy sources to allow testing with just predefined
* entropy sources. This function or tests depending on it might break if there
* are internal changes to how entropy sources are registered.
*
* To be called immediately after mbedtls_entropy_init().
*
* Just resetting the counter. New sources will overwrite existing ones.
* This might break memory checks in the future if sources need 'free-ing' then
* as well.
*/
static void entropy_clear_sources( mbedtls_entropy_context *ctx )
{
ctx->source_count = 0;
}
#if defined(MBEDTLS_ENTROPY_NV_SEED)
/*
* NV seed read/write functions that use a buffer instead of a file
*/
static unsigned char buffer_seed[MBEDTLS_ENTROPY_BLOCK_SIZE];
int buffer_nv_seed_read( unsigned char *buf, size_t buf_len )
{
if( buf_len != MBEDTLS_ENTROPY_BLOCK_SIZE )
return( -1 );
memcpy( buf, buffer_seed, MBEDTLS_ENTROPY_BLOCK_SIZE );
return( 0 );
}
int buffer_nv_seed_write( unsigned char *buf, size_t buf_len )
{
if( buf_len != MBEDTLS_ENTROPY_BLOCK_SIZE )
return( -1 );
memcpy( buffer_seed, buf, MBEDTLS_ENTROPY_BLOCK_SIZE );
return( 0 );
}
/*
* NV seed read/write helpers that fill the base seedfile
*/
static int write_nv_seed( unsigned char *buf, size_t buf_len )
{
FILE *f;
if( buf_len != MBEDTLS_ENTROPY_BLOCK_SIZE )
return( -1 );
if( ( f = fopen( MBEDTLS_PLATFORM_STD_NV_SEED_FILE, "w" ) ) == NULL )
return( -1 );
if( fwrite( buf, 1, MBEDTLS_ENTROPY_BLOCK_SIZE, f ) !=
MBEDTLS_ENTROPY_BLOCK_SIZE )
return( -1 );
fclose( f );
return( 0 );
}
int read_nv_seed( unsigned char *buf, size_t buf_len )
{
FILE *f;
if( buf_len != MBEDTLS_ENTROPY_BLOCK_SIZE )
return( -1 );
if( ( f = fopen( MBEDTLS_PLATFORM_STD_NV_SEED_FILE, "rb" ) ) == NULL )
return( -1 );
if( fread( buf, 1, MBEDTLS_ENTROPY_BLOCK_SIZE, f ) !=
MBEDTLS_ENTROPY_BLOCK_SIZE )
return( -1 );
fclose( f );
return( 0 );
}
#endif /* MBEDTLS_ENTROPY_NV_SEED */
/* END_HEADER */
/* BEGIN_DEPENDENCIES
* depends_on:MBEDTLS_ENTROPY_C
* END_DEPENDENCIES
*/
/* BEGIN_CASE */
void entropy_init_free( int reinit )
{
mbedtls_entropy_context ctx;
/* Double free is not explicitly documented to work, but it is convenient
* to call mbedtls_entropy_free() unconditionally on an error path without
* checking whether it has already been called in the success path. */
mbedtls_entropy_init( &ctx );
mbedtls_entropy_free( &ctx );
if( reinit )
mbedtls_entropy_init( &ctx );
mbedtls_entropy_free( &ctx );
/* This test case always succeeds, functionally speaking. A plausible
* bug might trigger an invalid pointer dereference or a memory leak. */
goto exit;
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */
void entropy_seed_file( char * path, int ret )
{
mbedtls_entropy_context ctx;
mbedtls_entropy_init( &ctx );
TEST_ASSERT( mbedtls_entropy_write_seed_file( &ctx, path ) == ret );
TEST_ASSERT( mbedtls_entropy_update_seed_file( &ctx, path ) == ret );
exit:
mbedtls_entropy_free( &ctx );
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */
void entropy_write_base_seed_file( int ret )
{
mbedtls_entropy_context ctx;
mbedtls_entropy_init( &ctx );
TEST_ASSERT( mbedtls_entropy_write_seed_file( &ctx, MBEDTLS_PLATFORM_STD_NV_SEED_FILE ) == ret );
TEST_ASSERT( mbedtls_entropy_update_seed_file( &ctx, MBEDTLS_PLATFORM_STD_NV_SEED_FILE ) == ret );
exit:
mbedtls_entropy_free( &ctx );
}
/* END_CASE */
/* BEGIN_CASE */
void entropy_no_sources( )
{
mbedtls_entropy_context ctx;
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
mbedtls_entropy_init( &ctx );
entropy_clear_sources( &ctx );
TEST_EQUAL( mbedtls_entropy_func( &ctx, buf, sizeof( buf ) ),
MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED );
exit:
mbedtls_entropy_free( &ctx );
}
/* END_CASE */
/* BEGIN_CASE */
void entropy_too_many_sources( )
{
mbedtls_entropy_context ctx;
size_t i;
entropy_dummy_context dummy = {DUMMY_REQUESTED_LENGTH, 0, 0};
mbedtls_entropy_init( &ctx );
/*
* It's hard to tell precisely when the error will occur,
* since we don't know how many sources were automatically added.
*/
for( i = 0; i < MBEDTLS_ENTROPY_MAX_SOURCES; i++ )
(void) mbedtls_entropy_add_source( &ctx, entropy_dummy_source, &dummy,
16, MBEDTLS_ENTROPY_SOURCE_WEAK );
TEST_ASSERT( mbedtls_entropy_add_source( &ctx, entropy_dummy_source, &dummy,
16, MBEDTLS_ENTROPY_SOURCE_WEAK )
== MBEDTLS_ERR_ENTROPY_MAX_SOURCES );
exit:
mbedtls_entropy_free( &ctx );
}
/* END_CASE */
/* BEGIN_CASE depends_on:ENTROPY_HAVE_STRONG */
void entropy_func_len( int len, int ret )
{
mbedtls_entropy_context ctx;
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE + 10] = { 0 };
unsigned char acc[MBEDTLS_ENTROPY_BLOCK_SIZE + 10] = { 0 };
size_t i, j;
mbedtls_entropy_init( &ctx );
/*
* See comments in mbedtls_entropy_self_test()
*/
for( i = 0; i < 8; i++ )
{
TEST_ASSERT( mbedtls_entropy_func( &ctx, buf, len ) == ret );
for( j = 0; j < sizeof( buf ); j++ )
acc[j] |= buf[j];
}
if( ret == 0 )
for( j = 0; j < (size_t) len; j++ )
TEST_ASSERT( acc[j] != 0 );
for( j = len; j < sizeof( buf ); j++ )
TEST_ASSERT( acc[j] == 0 );
exit:
mbedtls_entropy_free( &ctx );
}
/* END_CASE */
/* BEGIN_CASE */
void entropy_source_fail( char * path )
{
mbedtls_entropy_context ctx;
unsigned char buf[16];
entropy_dummy_context dummy = {DUMMY_FAIL, 0, 0};
mbedtls_entropy_init( &ctx );
TEST_ASSERT( mbedtls_entropy_add_source( &ctx, entropy_dummy_source,
&dummy, 16,
MBEDTLS_ENTROPY_SOURCE_WEAK )
== 0 );
TEST_ASSERT( mbedtls_entropy_func( &ctx, buf, sizeof( buf ) )
== MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
TEST_ASSERT( mbedtls_entropy_gather( &ctx )
== MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
#if defined(MBEDTLS_FS_IO) && defined(MBEDTLS_ENTROPY_NV_SEED)
TEST_ASSERT( mbedtls_entropy_write_seed_file( &ctx, path )
== MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
TEST_ASSERT( mbedtls_entropy_update_seed_file( &ctx, path )
== MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
#else
((void) path);
#endif
exit:
mbedtls_entropy_free( &ctx );
}
/* END_CASE */
/* BEGIN_CASE */
void entropy_threshold( int threshold, int chunk_size, int result )
{
mbedtls_entropy_context ctx;
entropy_dummy_context strong =
{DUMMY_CONSTANT_LENGTH, MBEDTLS_ENTROPY_BLOCK_SIZE, 0};
entropy_dummy_context weak = {DUMMY_CONSTANT_LENGTH, chunk_size, 0};
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 };
int ret;
mbedtls_entropy_init( &ctx );
entropy_clear_sources( &ctx );
/* Set strong source that reaches its threshold immediately and
* a weak source whose threshold is a test parameter. */
TEST_ASSERT( mbedtls_entropy_add_source( &ctx, entropy_dummy_source,
&strong, 1,
MBEDTLS_ENTROPY_SOURCE_STRONG ) == 0 );
TEST_ASSERT( mbedtls_entropy_add_source( &ctx, entropy_dummy_source,
&weak, threshold,
MBEDTLS_ENTROPY_SOURCE_WEAK ) == 0 );
ret = mbedtls_entropy_func( &ctx, buf, sizeof( buf ) );
if( result >= 0 )
{
TEST_ASSERT( ret == 0 );
#if defined(MBEDTLS_ENTROPY_NV_SEED)
/* If the NV seed functionality is enabled, there are two entropy
* updates: before and after updating the NV seed. */
result *= 2;
#endif
TEST_ASSERT( weak.calls == (size_t) result );
}
else
{
TEST_ASSERT( ret == result );
}
exit:
mbedtls_entropy_free( &ctx );
}
/* END_CASE */
/* BEGIN_CASE */
void entropy_calls( int strength1, int strength2,
int threshold, int chunk_size,
int result )
{
/*
* if result >= 0: result = expected number of calls to source 1
* if result < 0: result = expected return code from mbedtls_entropy_func()
*/
mbedtls_entropy_context ctx;
entropy_dummy_context dummy1 = {DUMMY_CONSTANT_LENGTH, chunk_size, 0};
entropy_dummy_context dummy2 = {DUMMY_CONSTANT_LENGTH, chunk_size, 0};
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE] = { 0 };
int ret;
mbedtls_entropy_init( &ctx );
entropy_clear_sources( &ctx );
TEST_ASSERT( mbedtls_entropy_add_source( &ctx, entropy_dummy_source,
&dummy1, threshold,
strength1 ) == 0 );
TEST_ASSERT( mbedtls_entropy_add_source( &ctx, entropy_dummy_source,
&dummy2, threshold,
strength2 ) == 0 );
ret = mbedtls_entropy_func( &ctx, buf, sizeof( buf ) );
if( result >= 0 )
{
TEST_ASSERT( ret == 0 );
#if defined(MBEDTLS_ENTROPY_NV_SEED)
/* If the NV seed functionality is enabled, there are two entropy
* updates: before and after updating the NV seed. */
result *= 2;
#endif
TEST_ASSERT( dummy1.calls == (size_t) result );
}
else
{
TEST_ASSERT( ret == result );
}
exit:
mbedtls_entropy_free( &ctx );
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */
void nv_seed_file_create( )
{
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
TEST_ASSERT( write_nv_seed( buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) == 0 );
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO:MBEDTLS_PLATFORM_NV_SEED_ALT */
void entropy_nv_seed_std_io( )
{
unsigned char io_seed[MBEDTLS_ENTROPY_BLOCK_SIZE];
unsigned char check_seed[MBEDTLS_ENTROPY_BLOCK_SIZE];
memset( io_seed, 1, MBEDTLS_ENTROPY_BLOCK_SIZE );
memset( check_seed, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
mbedtls_platform_set_nv_seed( mbedtls_platform_std_nv_seed_read,
mbedtls_platform_std_nv_seed_write );
/* Check if platform NV read and write manipulate the same data */
TEST_ASSERT( write_nv_seed( io_seed, MBEDTLS_ENTROPY_BLOCK_SIZE ) == 0 );
TEST_ASSERT( mbedtls_nv_seed_read( check_seed, MBEDTLS_ENTROPY_BLOCK_SIZE ) ==
MBEDTLS_ENTROPY_BLOCK_SIZE );
TEST_ASSERT( memcmp( io_seed, check_seed, MBEDTLS_ENTROPY_BLOCK_SIZE ) == 0 );
memset( check_seed, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
/* Check if platform NV write and raw read manipulate the same data */
TEST_ASSERT( mbedtls_nv_seed_write( io_seed, MBEDTLS_ENTROPY_BLOCK_SIZE ) ==
MBEDTLS_ENTROPY_BLOCK_SIZE );
TEST_ASSERT( read_nv_seed( check_seed, MBEDTLS_ENTROPY_BLOCK_SIZE ) == 0 );
TEST_ASSERT( memcmp( io_seed, check_seed, MBEDTLS_ENTROPY_BLOCK_SIZE ) == 0 );
}
/* END_CASE */
/* BEGIN_CASE depends_on:MBEDTLS_MD_C:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_PLATFORM_NV_SEED_ALT */
void entropy_nv_seed( data_t * read_seed )
{
#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
const mbedtls_md_info_t *md_info =
mbedtls_md_info_from_type( MBEDTLS_MD_SHA512 );
#elif defined(MBEDTLS_ENTROPY_SHA256_ACCUMULATOR)
const mbedtls_md_info_t *md_info =
mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 );
#else
#error "Unsupported entropy accumulator"
#endif
mbedtls_md_context_t accumulator;
mbedtls_entropy_context ctx;
int (*original_mbedtls_nv_seed_read)( unsigned char *buf, size_t buf_len ) =
mbedtls_nv_seed_read;
int (*original_mbedtls_nv_seed_write)( unsigned char *buf, size_t buf_len ) =
mbedtls_nv_seed_write;
unsigned char header[2];
unsigned char entropy[MBEDTLS_ENTROPY_BLOCK_SIZE];
unsigned char buf[MBEDTLS_ENTROPY_BLOCK_SIZE];
unsigned char empty[MBEDTLS_ENTROPY_BLOCK_SIZE];
unsigned char check_seed[MBEDTLS_ENTROPY_BLOCK_SIZE];
unsigned char check_entropy[MBEDTLS_ENTROPY_BLOCK_SIZE];
memset( entropy, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
memset( buf, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
memset( empty, 0, MBEDTLS_ENTROPY_BLOCK_SIZE );
memset( check_seed, 2, MBEDTLS_ENTROPY_BLOCK_SIZE );
memset( check_entropy, 3, MBEDTLS_ENTROPY_BLOCK_SIZE );
// Make sure we read/write NV seed from our buffers
mbedtls_platform_set_nv_seed( buffer_nv_seed_read, buffer_nv_seed_write );
mbedtls_md_init( &accumulator );
mbedtls_entropy_init( &ctx );
entropy_clear_sources( &ctx );
TEST_ASSERT( mbedtls_entropy_add_source( &ctx, mbedtls_nv_seed_poll, NULL,
MBEDTLS_ENTROPY_BLOCK_SIZE,
MBEDTLS_ENTROPY_SOURCE_STRONG ) == 0 );
// Set the initial NV seed to read
TEST_ASSERT( read_seed->len >= MBEDTLS_ENTROPY_BLOCK_SIZE );
memcpy( buffer_seed, read_seed->x, MBEDTLS_ENTROPY_BLOCK_SIZE );
// Do an entropy run
TEST_ASSERT( mbedtls_entropy_func( &ctx, entropy, sizeof( entropy ) ) == 0 );
// Determine what should have happened with manual entropy internal logic
// Init accumulator
header[1] = MBEDTLS_ENTROPY_BLOCK_SIZE;
TEST_ASSERT( mbedtls_md_setup( &accumulator, md_info, 0 ) == 0 );
// First run for updating write_seed
header[0] = 0;
TEST_ASSERT( mbedtls_md_starts( &accumulator ) == 0 );
TEST_ASSERT( mbedtls_md_update( &accumulator, header, 2 ) == 0 );
TEST_ASSERT( mbedtls_md_update( &accumulator,
read_seed->x, MBEDTLS_ENTROPY_BLOCK_SIZE ) == 0 );
TEST_ASSERT( mbedtls_md_finish( &accumulator, buf ) == 0 );
TEST_ASSERT( mbedtls_md_starts( &accumulator ) == 0 );
TEST_ASSERT( mbedtls_md_update( &accumulator,
buf, MBEDTLS_ENTROPY_BLOCK_SIZE ) == 0 );
TEST_ASSERT( mbedtls_md( md_info, buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
check_seed ) == 0 );
// Second run for actual entropy (triggers mbedtls_entropy_update_nv_seed)
header[0] = MBEDTLS_ENTROPY_SOURCE_MANUAL;
TEST_ASSERT( mbedtls_md_update( &accumulator, header, 2 ) == 0 );
TEST_ASSERT( mbedtls_md_update( &accumulator,
empty, MBEDTLS_ENTROPY_BLOCK_SIZE ) == 0 );
header[0] = 0;
TEST_ASSERT( mbedtls_md_update( &accumulator, header, 2 ) == 0 );
TEST_ASSERT( mbedtls_md_update( &accumulator,
check_seed, MBEDTLS_ENTROPY_BLOCK_SIZE ) == 0 );
TEST_ASSERT( mbedtls_md_finish( &accumulator, buf ) == 0 );
TEST_ASSERT( mbedtls_md( md_info, buf, MBEDTLS_ENTROPY_BLOCK_SIZE,
check_entropy ) == 0 );
// Check result of both NV file and entropy received with the manual calculations
TEST_ASSERT( memcmp( check_seed, buffer_seed, MBEDTLS_ENTROPY_BLOCK_SIZE ) == 0 );
TEST_ASSERT( memcmp( check_entropy, entropy, MBEDTLS_ENTROPY_BLOCK_SIZE ) == 0 );
exit:
mbedtls_md_free( &accumulator );
mbedtls_entropy_free( &ctx );
mbedtls_nv_seed_read = original_mbedtls_nv_seed_read;
mbedtls_nv_seed_write = original_mbedtls_nv_seed_write;
}
/* END_CASE */
/* BEGIN_CASE depends_on:ENTROPY_HAVE_STRONG:MBEDTLS_SELF_TEST */
void entropy_selftest( int result )
{
TEST_ASSERT( mbedtls_entropy_self_test( 1 ) == result );
}
/* END_CASE */
|
__label__pos
| 0.998016 |
logo
Practical Approach to Automate the Discovery and Eradication of Open-Source Software Vulnerabilities at Scale
Conference: BlackHat USA 2019
2019-08-08
Summary
The presentation discusses the challenges of open source security and proposes a practical approach to address them.
• Open source adoption has accelerated in the last decade, but finding and fixing security vulnerabilities in the ecosystem is a major challenge
• The approach to addressing this challenge is broken down into three stages: discovery, triage, and remediation
• Discovery involves finding vulnerabilities and mapping them to impacted services
• Triage involves prioritizing and managing the risk based on data-driven decisions
• Remediation involves fixing the vulnerabilities and ensuring compatibility and enablement
• Netflix's solution, Astrid, helps map dependencies and identify the impact of libraries on the ecosystem
The speaker describes the frustration of spending a week dealing with a serious remote code execution vulnerability in an open source Java package, and the need for a solution that can respond faster with less effort and more stability.
Abstract
Over the last decade, there has been steady growth in the adoption of open-source components in modern web applications. Although this is generally a good trend for the industry, there are potential risks stemming from this practice that requires careful attention. In this talk, we will describe a simple but pragmatic approach to identifying and eliminating open-source vulnerabilities in Netflix applications at scale.Our solution at Netflix is focused on identifying, triaging, and eliminating vulnerabilities in common software packages and their transitive dependencies.This talk will cover the following topics:A brief history of open source security and vulnerabilitiesReasons why this attack surface is still a problem in modern open-source librariesMethods that attackers use to exploit vulnerabilities in open-source librariesReasons why it is easy to carry out attacks against any organizationWe will then explore how the Netflix AppSec team has worked to solve the problem at scale, describing the various stages in our automation strategy and the tools that we are using to help us achieve our goals.
Materials:
Tags:
Post a comment
|
__label__pos
| 0.953133 |
Skip to content
master
Go to file
Code
Latest commit
Git stats
Files
Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
lib
src
Readme.md
Uri Templates
Build Status NuGet
.NET implementation of the URI Template Spec RFC6570.
Library implements Level 4 compliance and is tested against test cases from UriTemplate test suite.
Here are some basic usage examples:
Replacing a path segment parameter,
[Fact]
public void UpdatePathParameter()
{
var url = new UriTemplate("http://example.org/{tenant}/customers")
.AddParameter("tenant", "acmé")
.Resolve();
Assert.Equal("http://example.org/acm%C3%A9/customers", url);
}
Setting query string parameters,
[Fact]
public void ShouldResolveUriTemplateWithNonStringParameter()
{
var url = new UriTemplate("http://example.org/location{?lat,lng}")
.AddParameters(new { lat = 31.464, lng = 74.386 })
.Resolve();
Assert.Equal("http://example.org/location?lat=31.464&lng=74.386", url);
}
Resolving a URI when parameters are not set will simply remove the parameters,
[Fact]
public void SomeParametersFromAnObject()
{
var url = new UriTemplate("http://example.org{/environment}{/version}/customers{?active,country}")
.AddParameters(new
{
version = "v2",
active = "true"
})
.Resolve();
Assert.Equal("http://example.org/v2/customers?active=true", url);
}
You can even pass lists as parameters
[Fact]
public void ApplyParametersObjectWithAListofInts()
{
var url = new UriTemplate("http://example.org/customers{?ids,order}")
.AddParameters(new
{
order = "up",
ids = new[] {21, 75, 21}
})
.Resolve();
Assert.Equal("http://example.org/customers?ids=21,75,21&order=up", url);
}
And dictionaries,
[Fact]
public void ApplyDictionaryToQueryParameters()
{
var url = new UriTemplate("http://example.org/foo{?coords*}")
.AddParameter("coords", new Dictionary<string, string>
{
{"x", "1"},
{"y", "2"},
})
.Resolve();
Assert.Equal("http://example.org/foo?x=1&y=2", url);
}
We also handle all the complex URI encoding rules automatically.
[Fact]
public void TestExtremeEncoding()
{
var url = new UriTemplate("http://example.org/sparql{?query}")
.AddParameter("query", "PREFIX dc: <http://purl.org/dc/elements/1.1/> SELECT ?book ?who WHERE { ?book dc:creator ?who }")
.Resolve();
Assert.Equal("http://example.org/sparql?query=PREFIX%20dc%3A%20%3Chttp%3A%2F%2Fpurl.org%2Fdc%2Felements%2F1.1%2F%3E%20SELECT%20%3Fbook%20%3Fwho%20WHERE%20%7B%20%3Fbook%20dc%3Acreator%20%3Fwho%20%7D", url);
}
There is a blogpost that discusses these examples and more in detail.
As well as having a set of regular usage tests, this library also executes tests based on a standard test suite. This test suite is pulled in as a Git Submodule, therefore when cloning this repo, you will need use the --recursive switch,
git clone --recursive [email protected]:tavis-software/Tavis.UriTemplates.git
Current this library does not pass all of the failure tests. I.e. If you pass an invalid URI Template, you may not get an exception.
About
.Net implementation of the URI Template Spec https://tools.ietf.org/html/rfc6570
Resources
License
Releases
No releases published
Packages
No packages published
You can’t perform that action at this time.
|
__label__pos
| 0.639146 |
What is 492 to the 2nd Power?
So you want to know what 492 to the 2nd power is do you? In this article we'll explain exactly how to perform the mathematical operation called "the exponentiation of 492 to the power of 2". That might sound fancy, but we'll explain this with no jargon! Let's do it.
What is an Exponentiation?
Let's get our terms nailed down first and then we can see how to work out what 492 to the 2nd power is.
When we talk about exponentiation all we really mean is that we are multiplying a number which we call the base (in this case 492) by itself a certain number of times. The exponent is the number of times to multiply 492 by itself, which in this case is 2 times.
492 to the Power of 2
There are a number of ways this can be expressed and the most common ways you'll see 492 to the 2nd shown are:
• 4922
• 492^2
So basically, you'll either see the exponent using superscript (to make it smaller and slightly above the base number) or you'll use the caret symbol (^) to signify the exponent. The caret is useful in situations where you might not want or need to use superscript.
So we mentioned that exponentation means multiplying the base number by itself for the exponent number of times. Let's look at that a little more visually:
492 to the 2nd Power = 492 x ... x 492 (2 times)
So What is the Answer?
Now that we've explained the theory behind this, let's crunch the numbers and figure out what 492 to the 2nd power is:
492 to the power of 2 = 4922 = 242,064
Why do we use exponentiations like 4922 anyway? Well, it makes it much easier for us to write multiplications and conduct mathematical operations with both large and small numbers when you are working with numbers with a lot of trailing zeroes or a lot of decimal places.
Hopefully this article has helped you to understand how and why we use exponentiation and given you the answer you were originally looking for. Now that you know what 492 to the 2nd power is you can continue on your merry way.
Feel free to share this article with a friend if you think it will help them, or continue on down to find some more examples.
Cite, Link, or Reference This Page
If you found this content useful in your research, please do us a great favor and use the tool below to make sure you properly reference us wherever you use it. We really appreciate your support!
• "What is 492 to the 2nd Power?". VisualFractions.com. Accessed on February 27, 2024. http://visualfractions.com/calculator/exponent/what-is-492-to-the-2nd-power/.
• "What is 492 to the 2nd Power?". VisualFractions.com, http://visualfractions.com/calculator/exponent/what-is-492-to-the-2nd-power/. Accessed 27 February, 2024.
• What is 492 to the 2nd Power?. VisualFractions.com. Retrieved from http://visualfractions.com/calculator/exponent/what-is-492-to-the-2nd-power/.
Exponentiation Calculator
Want to find the answer to another problem? Enter your number and power below and click calculate.
Calculate Exponentiation
Random List of Exponentiation Examples
If you made it this far you must REALLY like exponentiation! Here are some random calculations for you:
|
__label__pos
| 0.93497 |
dcsimg
AJAX page chugs in Firefox; Konqueror is fine
0 posts in topic
Flat View Flat View
TOPIC ACTIONS:
Posted By: Ben_Forbes
Posted On: Wednesday, December 20, 2006 08:26 AM
I made my first AJAX application today. It's simple; there's a text box and button. When the button is pressed, the contents of the text box are passed to a PHP script and a list of words that match is returned. I then populate a table with those results. There's about 100 words total. It works okay, but Firefox starts chugging after a dozen or so queries. Actually, just the tab with the AJAX in it chugs. Other tabs and windows are fine. I thought I could fix it by reusing TRs and TDs in the table, but the problem is still there. In Konqueror there is absolutely no problem, it runs fine. Could this be More>>
I made my first AJAX application today. It's simple;
there's a text box and button. When the button is
pressed, the contents of the text box are passed to a PHP
script and a list of words that match is returned.
I then populate a table with those results.
There's about 100 words total.
It works okay, but Firefox starts chugging after a dozen
or so queries. Actually, just the tab with the AJAX in
it chugs. Other tabs and windows are fine. I thought I
could fix it by reusing TRs and TDs in the table, but
the problem is still there.
In Konqueror there is absolutely no problem, it runs fine.
Could this be some kind of memory drain issue?
I've heard Firefox is pretty bad with memory,
although honestly I've never noticed in the few years
I've been using it.
Or could it be the fact that I'm
dynamically manipulating the DOM tree? Konqueror may
be more efficient in doing this.
Here's a bit of code:
function alertContents(http_request) {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var txt=http_request.responseText;
var arr=txt.split(",");
clearResults();
for (var i=0;i
addResult(arr[i]);
}
} else {
alert('There was a problem with the request.');
}
}
}
function clearResults() {
var theTable=document.getElementById('theTable');
var rows=theTable.getElementsByTagName('tr');
while (rows.length>1) {
rowStore.push(rows[1]);
rows[1].parentNode.removeChild(rows[1]);
}
}
function addResult(s) {
var theTable=document.getElementById('theTable');
//var newTr=document.createElement('tr');
//var newTd=document.createElement('td');
//Be nice
var newTr;
var newTd;
if (rowStore.length>0) {
newTr=rowStore.pop();
var tds=newTr.getElementsByTagName('td');
newTd=tds[0];
}
else {
newTr=document.createElement('tr');
rowsCreated++;
var theSpan2=document.getElementById('theSpan2');
theSpan2.innerHTML=rowsCreated;
newTd=document.createElement('td');
newTr.appendChild(newTd);
}
newTd.innerHTML=s;
newTr.style.borderBottom='1px solid grey';
theTable.appendChild(newTr);
}
<<Less
About | Sitemap | Contact
|
__label__pos
| 0.957817 |
ZPT Basics (part 1)
Use Zope Page Templates to collaborate on Zope application development.
Out With The Old...
Not too long ago, I introduced you to something called DTML, the Document Template Markup Language. I defined it as HTML on steroids, and spent lots of time and bandwidth showing you how it could be used to build complex Zope applications.
DTML isn't the only thing Zope has going for it, though. Over the next few pages, I'm going to introduce you to a brand-spanking-new creature from the Zope stable. It's called Zope Page Templates, or ZPT, and it's rapidly overtaking DTML as the de-facto standard for developing applications in Zope.
The Zope Web site is pretty wordy when it comes to describing ZPT. It defines ZPT as "a consistent, XML compliant, markup language [which] embed[s] all logic in namespaced attributes ...and provide[s] a means to supply prototypical content to give the presentation designer a sense of context." Or, to put it in simpler terms, ZPT allows Web developers greater flexibility in separating an application's presentation layer from the business logic that drives it, thereby making it possible to easily update one without disrupting the other.
I'm going to show you how in the following pages. Before I begin, though, make sure that you have a working copy of Zope and ZPT (this tutorial uses Zope 2.5.0, which comes with ZPT built in), and can log in to the Zope management interface. In case you can't, drop by http://www.zope.org/, get yourself set up and come back when you're ready to roll.
The Right Choice
Let's start with a very basic, but important, question: why use ZPT when you can use DTML?
There are a couple of reasons why you might prefer to use ZPT instead of DTML. First, DTML isn't really all that friendly, even to developers who are used to wading in the muddy waters of open-source programming languages. The language comes with numerous idiosyncrasies, which can be both annoying and confusing to developers. For example, the result value obtained from a DTML variable often depends on the manner in which it is accessed, and the connectivity between DTML and Python can often leave you confused and desperately searching for a Python programmer to help you get unstuck.
In addition to the technical problems with DTML, it's also not perfect when it comes to separating business logic from interface code. Since DTML documents contain both HTML code and DTML commands, interface designers and developers must collaborate closely with each other whenever a change needs to be made to the interface or processing sequences within a DTML document. Obviously, this means more time and effort to implement changes.
ZPT attempts to resolve this last problem by using templates to separate presentation and layout information from program code. This two-tiered approach affords both developers and designers a fair degree of independence when it comes to maintaining a Zope application, and can substantially reduce the time and effort required in the post-release phases of a development project.
Does this mean DTML is now redundant? No, not really. ZPT should not be considered a replacement for DTML; rather, it should be treated as an alternative to DTML. There still are some things that can be handled only using DTML - sending mail, managing sequences, batching and so on. If you're planning on working with Zope, you're going to need to keep your DTML skills current. It's just that you now have a little more choice.
The Power Of Three
ZPT actually consists of three different components, which interact with each other to offer developers a fair amount of power and flexibility. Here they are:
1. TAL: First up is the Template Attribute Language, also referred to as TAL. As per the official TAL specification, TAL is "an attribute language used to create dynamic templates...it allows elements of a document to be replaced, repeated, or omitted." Put more simply, TAL is a template language which uses special attributes within HTML tags to perform different actions, like variable interpolation, tag repetition and content replacement.
2. METAL: Nope, this isn't the music that makes your head hurt and your eardrums pound. METAL is the Macro Expansion Template Attribute Language, and it is defined as "an attribute language for structured macro preprocessing". In ZPT, macros allow developers to create a single snippet of code and reuse it extensively across the application. The advantage: a change to the macro will be immediately reflected across the templates it has been used in.
3. TALES: Apart from having a familiar ring to it, this acronym actually stands for Template Attribute Language Expression Syntax. Officially, TALES "describes expressions that may be used to supply TAL and METAL with data." These expressions may be in the form of paths to specific Zope objects, Python code or strings, including strings containing variables to be substituted, and they form a significant component of ZPT.
Let's see what all this means with a quick look at some code.
What's In A Name?
Consider the following simple code snippet:
My name is <b tal:content="template/id">template id</b>.
If you were to render this through Zope, in a template with the ID "MyFirstTemplate", you'd see the following output:
My name is <b>MyFirstTemplate</b>.
What happened here? Roughly translated, the line
<b tal:content="template/id">template id</b>
means "replace the content enclosed within the <b> element with the result obtained by evaluating the TALES expression [template/id]". When the template is rendered, this TALES expression will evaluate to the ID of the current page template, and will appear within the <b> tag.
The TALES expression
template/id
is a path expression pointing to a specific Zope object - in this case, the ID of the current template - and it provides an easy and intuitive way of accessing the value of any object within Zope. It need not be restricted to objects alone either - TALES expressions are equally versatile at evaluating string data or Python code.
TALES path expressions always begin with a variable name, and drill down hierarchically to the required object. A TALES path is traversed in a sequential manner until the final step is reached or until an error occurs. The result of the path expression is the value of the object found at the end of the path.
The "tal:content" attribute indicates to the Zope parser that only the content within the enclosing element should be replaced with the results of the TALES expression. TAL comes with a number of such special attributes, each with its own particular function - I'll be discussing them in detail over the course of this tutorial.
Note the special "tal:" namespace, which must prefix every TAL attribute, and which provides developers with an easy way to separate their own custom names from those defined in the TAL specification.
Usage of the TAL namespace also has one very important additional benefit, closely related to the developer/designer interaction problem discussed on the previous page. Most HTML editors will not understand the TAL namespace prefix or attributes, and will therefore ignore it when rendering a page; this allows designers to view and make changes to the HTML interface of a page without interfering with its business logic or requiring the intervention of developers (so long, obviously, as they don't fiddle with the special TAL statements embedded within the code).
Practical Magic
Let's take a look at a more concrete example of how TAL works. Start up Zope and log in to the management interface with the user name and password that was created when you installed Zope.
As you should know by now, this is the tool that you will be using to build your Web applications. You can use it to create documents, folders, and your own Zope products. And the first step in this process is to create a folder to store all the objects we're going to be creating.
Create a Folder by selecting it from the drop-down menu that appears at the top of the page, and name it "ZPT Basics".
The next step is to navigate to the folder that you just created and add a Page Template to it, using the process outlined above.
Give this template an ID of "MyFirstTemplate", and a title of "Hello ZPT!".
As you may have guessed by now, the object ID that you assign at each stage is fairly important - it provides a unique identifier for the object within Zope, which can be used to access and manipulate it from your scripts.
A default page template will be created in the "ZPT Basics" folder. Replace the code within it with the following:
<html>
<head>
<title tal:content="template/title">The title</title>
</head>
<body>
<h2>Welcome to <span tal:replace="here/title_or_id">content title or id</span></h2>
This is a Page Template with ID <em tal:content="template/id">template id</em> and title <em tal:content="template/title">template title</em>.
</body>
</html>
Here's the output of this template (you can see this via the "Test" option in the Zope management interface),
and here's the corresponding HTML code generated by Zope.
<html>
<head>
<title>Hello ZPT!</title>
</head>
<body>
<h2>Welcome to ZPT Basics</h2>
This is a Page Template with ID <em>MyFirstTemplate</em> and title <em>Hello ZPT!</em>.
</body>
</html>
Anatomy Lesson
There are a number of TALES expressions in the code snippet shown in the previous page - here's the first one:
<title tal:content="template/title">The title</title>
As you've already seen, this means "replace the content enclosed within the <title> element with the result obtained by evaluating the TALES expression [template/title]".
When the template is rendered, this TALES expression will evaluate to the title of the current page, which will appear within the <title> tag, like this:
<title>Hello ZPT!</title>
The second statement is similar, except that this time, the element itself is replaced, together with the content enclosed within it. When the page is rendered, the TAL statement
<h2>Welcome to <span tal:replace="here/title_or_id">content title or id</span></h2>
will replace the <span>... tags with the results of evaluating the TALES expression within it, like this:
<h2>Welcome to ZPT Basics</h2>
Putting It All In Context
You'll remember that I told you, a while back, that every TALES path expression must begin with a variable name. The TALES specification defines a number of such variables - here's a list of the most important ones:
"nothing" - a null value
"repeat" - a built-in TALES variable used for repetition
"root" - the starting point for the object hierarchy
"here" - the current context
"template" - the template itself
"container" - the template's container
"request" - the request object
You've already seen the "template" context in action - now let's take a look at the "request" context, which contains information about the current HTTP request. Consider the following example,
You are currently viewing the URL <i tal:content="request/URL">URL comes here</i>.
which, when rendered, displays the current URL:
You are currently viewing the URL http://medusa:8080/ZPT%20Basics/MyFirstTemplate.
This context also comes in handy when you're building Web forms and need to access the values of the various form variables. Consider the following simple DTML Document:
Please enter the following details:
<br>
<form action="formHandler" method="POST">
<p>
Your name
<br>
<input type="text" size="20" name="name">
<br>
</p>
<p>
Your favourite sandwich filling
<br>
<input type="text" size="15" name="filling">
<br>
</p>
<input type="submit" name="submit" value="Hit Me"><br>
</form>
This displays the following form to the user.
Next, create the form processing script, "formHandler", using a Page Template:
Hello, <span tal:replace="request/form/name">name here</span>.
I like <span tal:replace="request/form/filling">filling type here</span> sandwiches too. Maybe we should exchange recipes.
Try it out - here's an example of what you might see:
The beauty of this example lies in its simplicity. I've used the "request" context and obtained access to the form variables simply by specifying the appropriate path - the "request/form/name" path for the form variable "name", and the "request/form/filling" path for the form variable "filling".
And that's about it for this first part of the series. In this article, I gave you a gentle introduction to the ZPT way of doing things, explaining the special "content" and "replace" TAL attributes. In the next segment, I'll be looking at a few more of TAL's special attributes, including the ones that let you define variables and write conditional statements. Make sure you tune in for that one...and until then, stay healthy!
Note: All examples in this article have been tested on Linux/i586 with Zope 2.5.0. Examples are illustrative only, and are not meant for a production environment. Melonfire provides no warranties or support for the source code described in this article. YMMV!
This article was first published on14 Sep 2002.
|
__label__pos
| 0.568916 |
Adam Albrecht
ruby & javascript developer in columbus, ohio.
Authenticating your Angular / Rails App with JSON Web Tokens
UPDATE: There have been some changes in the JWT Gem that make some of the below not work exactly right (it’ll still be about 90% the same). Specifically, they added expiration support. See my post on the same topic, but using React.js. The server side code in this post will work just as well with Angular.
Overview
I’m a big proponent of rolling your own authentication solution, especially if you’re only doing simple username/password based logins (as opposed to logging in via an OAuth provider). I’ve tried to use Devise on a number of Rails apps, but I always end up ripping it out. It’s not because Devise is a bad gem, but because it always takes me more time to customize it to my liking than it does to just write everything myself. And the flexibility of a custom solution almost always comes in handy down the road. I have generally implemented it the same way that Ryan Bates does in this Railscasts episode.
But now that most of my greenfield projects are single page javascript apps, authentication has become slightly more complicated. While you can certainly continue doing traditional authentication with cookies and server-rendered views, my preference is to use a token-based approach. This has a number of benefits:
A relatively new standard for accomplishing this is JSON Web Tokens (abbreviated to JWT). I won’t dig into the details because there are plenty of good resources, but JWT is a way of digitally signing data to be transferred between two parties. The data is represented as an encoded JSON object. In a nutshell, these tokens are passed to the client upon successful authentication and then subsequently used in every HTTP request in order to verify the identity of the client.
Client/Server Data Flow
So the application flow will look something like this:
1. Client sends username and password to server.
2. If credentials are valid, the server generates a token that include’s the user’s ID inside the token payload. (Remember, this payload is not encrypted - the client can read it - so don’t put anything you don’t want the client to see)
3. The token is returned to the client, who saves it somewhere for later use.
4. When the client makes a request for protected data from the server, it includes the token in an HTTP header.
5. Upon receiving a request for protected data, the server looks at the token and verifies that it was indeed generated for the user represented by the ID in the payload.
Server-Side Code
So let’s start with the server-side code and assume you already have a basic user model. We’ll first need some code to generate a JWT for a given user. So install the jwt gem into your Gemfile. Next, I found there to be fair amount of logic around the JWT auth tokens, so I extracted it into a simple AuthToken class that takes care of encoding and decoding the tokens for us.
class AuthToken
def self.encode(payload, exp=24.hours.from_now)
payload[:exp] = exp.to_i
JWT.encode(payload, Rails.application.secrets.secret_key_base)
def self.decode(token)
payload = JWT.decode(token, Rails.application.secrets.secret_key_base)[0]
DecodedAuthToken.new(payload)
rescue
nil # It will raise an error if it is not a token that was generated with our secret key or if the user changes the contents of the payload
end
end
# We could just return the payload as a hash, but having keys with indifferent access is always nice, plus we get an expired? method that will be useful later
class DecodedAuthToken < HashWithIndifferentAccess
def expired?
self[:exp] <= Time.now.to_i
end
end
And let’s add a helper method to our User model that uses this class:
def generate_auth_token
payload = { user_id: self.id }
AuthToken.encode(payload)
end
Ok, now we need to take care of that initial authentication request in our Client/Server Data flow. The client sends a username/password combination and the server sends back a new token. So go ahead and create a new controller called AuthController and add a new post route to routes.rb. You may also want to return some information about the current user inside the JSON response, but for now we’ll just return the auth token.
class AuthController < ApplicationController
skip_before_action :authenticate_request # this will be implemented later
def authenticate
user = User.find_by_credentials(params[:username], params[:password]) # you'll need to implement this
if user
render json: { auth_token: user.generate_auth_token }
else
render json: { error: 'Invalid username or password' }, status: :unauthorized
end
end
end
# in routes.rb:
post 'auth' => 'auth#authenticate'
Ok, now we need to add code to validate the token on subsequent requests. What we’ll do first is implement a few helper methods in our ApplicationController that take care of decoding/validating the token and, based on the token payload, finding the current user. Then we’ll tie them all together in a a before filter/action. If the token is properly decoded and the user found, the request can be continued. If not, we’ll return a 401 Unauthorized response.
class ApplicationController < ActionController::Base
before_action :set_current_user, :authenticate_request
rescue_from NotAuthenticatedError do
render json: { error: 'Not Authorized' }, status: :unauthorized
end
rescue_from AuthenticationTimeoutError do
render json: { error: 'Auth token is expired' }, status: 419 # unofficial timeout status code
end
private
# Based on the user_id inside the token payload, find the user.
def set_current_user
if decoded_auth_token
@current_user ||= User.find(decoded_auth_token[:user_id])
end
end
# Check to make sure the current user was set and the token is not expired
def authenticate_request
if auth_token_expired?
fail AuthenticationTimeoutError
elsif !@current_user
fail NotAuthenticatedError
end
end
def decoded_auth_token
@decoded_auth_token ||= AuthToken.decode(http_auth_header_content)
end
def auth_token_expired?
decoded_auth_token && decoded_auth_token.expired?
end
# JWT's are stored in the Authorization header using this format:
# Bearer somerandomstring.encoded-payload.anotherrandomstring
def http_auth_header_content
return @http_auth_header_content if defined? @http_auth_header_content
@http_auth_header_content = begin
if request.headers['Authorization'].present?
request.headers['Authorization'].split(' ').last
else
nil
end
end
end
end
You’ll also need to define the 2 errors that are being rescued from:
class NotAuthenticatedError < StandardError
end
class AuthenticationTimeoutError < StandardError
end
Client Side Code
That should take care of the server side. Next, we’ll need to add support for these API’s into our angular app. To do this, we’ll need to implement two pieces of code: An AuthService that will handle logging in followed by an HTTP interceptor that will automatically attach our auth token to every http request and handle auth-related error responses.
First, our AuthService. Note that there are two dependencies you’ll need to implement. First, AuthToken is a simple service for storing the auth token in local storage while AuthEvents is a constant with a few auth/login related events so we’re not using magic strings.
app.factory("AuthService", function($http, $q, $rootScope, AuthToken, AuthEvents) {
return {
login: function(username, password) {
var d = $q.defer();
$http.post('/api/auth', {
username: username,
password: password
}).success(function(resp) {
AuthToken.set(resp.auth_token);
$rootScope.$broadcast(AuthEvents.loginSuccess);
d.resolve(resp.user);
}).error(function(resp) {
$rootScope.$broadcast(AuthEvents.loginFailed);
d.reject(resp.error);
});
return d.promise;
}
};
});
You’ll need to implement a basic login form and controller that use this service.
Next, let’s add our two http interceptors. The first is quite simple. Just attach “Bearer” followed by the auth token. This is the standard format for adding a JWT to your http headers. The error interceptor is slightly more complicatated. First, we check to make sure this isn’t our intial auth request because we want that to handle errors on its own. Then, we check to see if the response code matches any of our auth-related codes. If so, we broadcast an appropriate event.
app.factory("AuthInterceptor", function($q, $injector) {
return {
// This will be called on every outgoing http request
request: function(config) {
var AuthToken = $injector.get("AuthToken");
var token = AuthToken.get();
config.headers = config.headers || {};
if (token) {
config.headers.Authorization = "Bearer " + token;
}
return config || $q.when(config);
},
// This will be called on every incoming response that has en error status code
responseError: function(response) {
var AuthEvents = $injector.get('AuthEvents');
var matchesAuthenticatePath = response.config && response.config.url.match(new RegExp('/api/auth'));
if (!matchesAuthenticatePath) {
$injector.get('$rootScope').$broadcast({
401: AuthEvents.notAuthenticated,
403: AuthEvents.notAuthorized,
419: AuthEvents.sessionTimeout
}[response.status], response);
}
return $q.reject(response);
}
};
});
app.config(function($httpProvider) {
return $httpProvider.interceptors.push("AuthInterceptor");
});
// Elsewhere....
$rootScope.$on(AuthEvents.notAuthorized, function() {
// ... Take some action in response to a 401
});
How you handle these auth error events will be up to you. The simplest solution is to just redirect the user to the login page. Or you may want to pop up a modal login form so that the user doesn’t lose his or her work.
Also, this naively assumes you’ll have a long session length and the user won’t mind logging in again at the end, even if they’ve been actively using it the whole time. In my app, the session timeout length is just 60 minutes. So I implemented a timer that, every x minutes, requests to reissue the token (thus pushing back the expiration date) so long as there had been recent user activity. I may share this code in a future blog post, but I figured it was out of scope for the time being.
I’d love to hear your feedback because, again, this was roughly extracted from my application and I’m not even sure it’s the best implementation. So let me know on twitter, where I’m @adam_albrecht, if you find any bugs or ways to improve the code. Thanks!
|
__label__pos
| 0.721082 |
Design Patterns
Design Patterns
Last week I received a heavy parcel through the post from Amazon containing Thomas Erls new book SOA Design Patterns. I have been interested in design patterns for many years and still regularly refer to my copy of the gang of four (Design Patterns: Elements of Reusable Object-Oriented Software). For those of you unaware of them, patterns provide a proven solution to a problem. The gang of four book identifies four essential elements in a pattern (from section 1.1 What is a Design Pattern?).
1. A pattern name that extends our vocabularly when talking with colleagues, witness the common use of facade as a shorthand for the design principles of the facade pattern.
2. A problem that is addressed by the pattern.
3. A solution that describes an abstract design to solve the problem.
4. The consequences of applying the pattern, its results and its impacts both positive and negative.
It is worth noting that patterns are not created, they are discovered. An important aspect of a pattern is that it should have been used in more than one solution. The gang of four identified and documented 23 design patterns focused on object oriented languages. The Thomas Erl book focuses as the name suggests on service oriented patterns. Some of these patterns are service oriented forms of the gang of four patterns. For example the service facade is an example of the facade pattern. However Thomas explains how the service facade works in a a SOA and gives detailed explanations of its trade offs and benefits all closely related to SOA, providing a lot of added value even to people already familiar with the facade pattern. The facade pattern in the gang of four covers 9 pages, in Thomas’ book it covers 12 pages but also includes a case study and is focused purely on SOA.
Think of the SOA Design Patterns as a cookbook of possibilities. They cover lots of different patterns, many of them contributed by other SOA gurus such as Oracles David Chappell. Use it as a reference book to see if there is a proven design approach that can solve some of your problems. Remember that is a guide to good design, not a guarantor.
Well worth adding to your library!
Comments:
Post a Comment:
Comments are closed for this entry.
About
Musings on Fusion Middleware and SOA Picture of Antony Antony works with customers across the US and Canada in implementing SOA and other Fusion Middleware solutions. Antony is the co-author of the SOA Suite 11g Developers Cookbook, the SOA Suite 11g Developers Guide and the SOA Suite Developers Guide.
Search
Archives
« April 2015
SunMonTueWedThuFriSat
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Today
|
__label__pos
| 0.781836 |
NodeJS or ColdFusion, which one is better?
By interprogram on Sep 18, 2019 07:30 pm PDT | Updated Jan 28, 2023 11:45 am PST
ColdFusion:
A server-side programming environment, was initially developed more than twenty years ago in 1995 by J.J Allaire brothers. In 2001, it was acquired by Macromedia and in 2005, it was later attained by Adobe Systems.
After more than twenty years of growth, ColdFusion has become an impressive complete solution for database management, API development, client and server-side coding, file format operation, security and many more. Due to the fusion of multiple web technologies like XML, JAVA, Web Services; ColdFusion provides an easy programming environment for the development of server-side pages in less time as compared to other web-based technologies like PHP and ASP. The code in ColdFusion can be written in ColdFusion Markup language (CFML), which closely resembles XML and HTML.
Node.JS:
Node.JS is another server-side environment, originally developed by Ryan Dahl in 2009. It is an open-source JavaScript environment. Node.JS runs on several platforms e.g. Windows, Linux, Unix.
JavaScript is evolving rapidly since many software development teams working for major browsers are trying to improve support for making JavaScript run faster. Since it is an open-source environment, a large library of JavaScript modules is available which makes development fast and easy to a great extent. Node.JS is not only restricted to the development of server-side programs but can also be used for various other applications.
High level comparison between Node.JS and ColdFusion:
These two web server environments can be compared in the following respects:
Performance:
CF Scripts in ColdFusion helps to organize relevant code and data in a single file. CFCs gives ColdFusion, an object oriented language like properties and patterns. CFCs are already compiled and therefore, provide a faster execution time. Moreover, CFML requires significantly less infrastructure setup as compared to JAVA, while providing faster development experience than JAVA.
Node.JS is built on the Google Chrome’s V8 JavaScript engine, due to which its core run-time code executes very fast. Due to single-threaded implementation, on one hand, it avoids management of large number of threads; however, single threaded nature makes it inefficient for handling CPU intensive applications.
Coding:
Since Node.JS uses straightforward JavaScript syntax, most Web Developers can easily apply their existing knowledge to develop with Node.JS.
ColdFusion uses a special language CFML, which is a bit tricky to learn, therefore learning efforts are required.
To be continued...
|
__label__pos
| 0.568192 |
TypeOfNaN
Variable Assignment and Primitive/Object Mutability
Nick Scialli
January 21, 2020
laptop on table
If you’re not familiar with how JavaScript variable assignment and primitive/object mutability works, you might find yourself encountering bugs that you can’t quite explain. I think this is one of the more important foundational JavaScript topics to understand, and I’m excited to share it with you today!
JavaScript Data Types
JavaScript has seven primitive data types[1]:
• Boolean (true, false)
• Null (null)
• Undefined (undefined)
• Number (e.g., 42)
• BigInt (e.g., 10000000000000000n)
• String (e.g., "Hello world")
• Symbol (e.g., Symbol(11))
Additionally, JavaScript has object data types. JavaScript has several built-in object data types, the most well-known and widely-used being Array, Object, and Function.
Assignment, Reassignment, and Mutation
Assignment, reassignment, and mutation are important concepts to know and differentiate in JavaScript. Let’s define each and explore some examples.
Assignment
To understand assignment, let’s analyze a simple example.
let name = 'Julie';
To understand what happened here, we need to go right-to-left:
1. We create the string "Julie"
2. We create the variable name
3. We assign the variable name a reference to the string we previously created
So, assignment can be thought of as the process of creating a variable name and having that variable refer to data (be it a primitive or object data type).
Reassignment
Let’s extend the last example. First, we will assign the variable name a reference to the string "Julie" and then we will reassign that variable a reference to the string "Jack":
let name = 'Julie';
name = 'Jack';
Again, the play-by-play:
1. We create the string "Julie"
2. We create the variable name
3. We assign the variable name a reference to the string we previously created
4. We create the string "Jack"
5. We reassign the variable name a reference to the string "Jack"
If this all seems basic, that’s okay! We’re laying the foundation for understanding some more complicated behavior and I think you’ll be glad we did this review.
Mutation
Mutation is the act of changing data. It’s important to note that, in our examples thus far, we haven’t changed any of our data.
Primitive Mutation (spoiler: you can’t)
In fact, we wouldn’t have been able to change any of our data in the previous example even if we wanted to—primitives can’t be mutated (they are immutable). Let’s try to mutate a string and bask in the failure:
let name = 'Jack';
name[2] = 'e';
console.log(name);
// "Jack"
Obviously, our attempt at mutation failed. This is expected: we simply can’t mutate primitive data types.
Object Mutation
We absolutely can mutate objects! Let’s look at an example.
let person = {
name: 'Beck',
};
person.name = 'Bailey';
console.log(person);
// { name: "Bailey" }
So yeah, that worked. It’s important to keep in mind that we never reassigned the person variable, but we did mutate the object at which it was pointing.
Why This All Matters
Get ready for the payoff. I’m going to give you two examples mixing concepts of assignment and mutation.
Example 1: Primitives
let name = 'Mindy';
let name2 = name;
name2 = 'Mork';
console.log(name, name2);
// "Mindy" "Mork"
Not very surprising. To be thorough, let’s recap the last snippet in more detail:
1. We create the string "Mindy"
2. We create the variable name and assign it a reference to the string "Mindy"
3. We create the variable name2 and assign a reference to the string "Mindy"
4. We create the string "Mork" and reassign name2 to reference that string
5. When we console.log name and name2, we find that name is still referencing "Mindy" and name2 is referencing the string "Mork"
Example 2: Objects
let person = { name: 'Jack' };
let person2 = person;
person2.name = 'Jill';
console.log(person, person2);
// { name: "Jill" }
// { name: "Jill" }
If this surprises you, try it out in the console or your favorite JS runtime environment!
Why does this happen? Let’s do the play-by-play:
1. We create the object { name: "Jack" }
2. We create the person variable and assign it a reference to the created object
3. We create the person2 variable and set it equal to person, which is referring to the previously-created object. (Note: person2 is now referencing the same object that person is referencing!)
4. We create the string "Jill" and mutate the object by reassiging the name property to reference "Jill"
5. When we console.log person and person2, we note that the one object in memory that both variables were referencing has been mutated.
Pretty cool, right? And by cool, I mean potentially scary if you didn’t know about this behavior.
The Real Differentiator: Mutability
As we discussed earlier, primitive data types are immutable. That means we really don’t have to worry about whether two variables point to the same primitive in memory: that primitive won’t change. At best, we can reassign one of our variables to point at some other data, but that won’t affect the other variable.
Objects, on the other hand, are mutable. Therefore, we have to be keep in mind that multiple variables may be pointing to the same object in memory. “Mutating” one of those variables is a misnomer, you’re mutating the object it’s referencing, which will be reflected in any other variable referencing that same object.
Is This a Bad Thing?
This question is far too nuanced to give a simple yes or no answer. Since I have spent a good amount of time understanding JavaScript object references and mutability, I feel like I actually use it to my advantage quite a bit and, for me, it’s a good thing. But for newcomers and those who haven’t had the time to really understand this behavior, it can cause some pretty insidious bugs.
How Do I Prevent This from Happening?
In many situations, you don’t want two variables referencing the same object. The best way to prevent this is by creating a copy of the object when you do the assignment.
There are a couple ways to create a copy of an object: using the Object.assign method and spread operator, respectively.
let person = { name: 'Jack' };
// Object.assign
let person2 = Object.assign({}, person);
// Spread operator
let person3 = { ...person };
person2.name = 'Pete';
person3.name = 'Betty';
console.log(person, person2, person3);
// { name: "Jack" }
// { name: "Pete" }
// { name: "Betty" }
Success! But a word of caution: this isn’t a silver bullet because we’re only creating shallow copies of the person object.
Shallow Copies?
If our object has objects nested within it, shallow copy mechanisms like Object.assign and the spread operator will only create copies of the root level object, but deeper objects will still be shared. Here’s an example:
let person = {
name: 'Jack',
animal: {
type: 'Dog',
name: 'Daffodil',
},
};
person2 = { ...person };
person2.name = 'Betty';
person2.animal.type = 'Cat';
person2.animal.name = 'Whiskers';
console.log(person);
/*
{
name: "Jack",
animal: {
type: "Cat",
name: "Whiskers"
}
}
*/
Ack! So we copies the top level properties but we’re still sharing references to deeper objects in the object tree. If those deeper objects are mutated, it’s reflected when we access either the person or person2 variable.
Deep Copying
Deep copying to the rescue! There are a number of ways to deep copy a JavaScript object[2]. I’ll cover two here: using JSON.stringify/JSON.parse and using a deep clone library.
JSON.stringify/JSON.parse
If your object is simple enough, you can use JSON.stringify to convert it to a string and then JSON.parse to convert it back into a JavaScript object.
let person = {
name: 'Jack',
animal: {
type: 'Dog',
name: 'Daffodil',
},
};
person2 = JSON.parse(JSON.stringify(person));
And this will work… but only in limited situations. If your object has any data that cannot be represented in a JSON string (e.g., functions), that data will be lost! A risky gambit if you’re not super confident in the simplicity of your object.
Deep Clone Library
There are a lot of good deep clone libraries out there. One such example is lodash with its _.cloneDeep method. These libraries will generally traverse your object and do shallow copies all the way down until everything has been copied. From your perspective, all you have to do is import lodash and use cloneDeep:
let person = {
name: 'Jack',
animal: {
type: 'Dog',
name: 'Daffodil',
},
};
person2 = _.cloneDeep(person);
Conclusion
This discussion is really the tip of the iceburg when it comes to variable assignment and data mutability in JavaScript. I invite you to continue researching this topic, experimenting with topics like equality comparison when assigning object references and copying objects.
References:
1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures
2. https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript
If you'd like to support this blog by buying me a coffee I'd really appreciate it!
Nick Scialli
Nick Scialli is a senior UI engineer at the Microsoft.
© 2023 Nick Scialli
|
__label__pos
| 0.996502 |
Question
Using the regression table in Exercise 13, answer the following questions.
a) How was the t-ratio of 0.221 found for Police Officer Wage? (Show what is computed using numbers from the table.)
b) How many states are used in this model. How do you know?
c) The t-ratio for Graduation Rate is negative. What does that mean?
$1.99
Sales0
Views61
Comments0
• CreatedMay 15, 2015
• Files Included
Post your question
5000
|
__label__pos
| 0.997797 |
Shopify: Setting up a multipurpose CMSed liquid homepage section
Setting up a multipurpose CMSed liquid homepage section for Shopify.
The below schema includes two sets of data
1. A YouTube Video display
2. A list of testimonials (max 5)
{% schema %}
{
"name": "Video & Testimonial",
"max_blocks": 5,
"settings": [
{
"id": "video_title",
"type": "text",
"label": "Heading",
"default": "Learn 'How to' with our video"
},
{
"id": "video_sub",
"type": "text",
"label": "Heading",
"default": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed incididunt. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod"
},
{
"id": "video_code",
"type": "text",
"label": "YouTube Code",
"default": "GF60Iuh643I"
},
{
"id": "video_image",
"type": "image_picker",
"label": "Background Image"
}
],
"blocks": [
{
"type": "testimonial",
"name": "Testimonial Option",
"settings": [
{
"id": "testimonial_subject",
"type": "text",
"label": "Testimonial Subject"
},
{
"type": "image_picker",
"id": "image",
"label": "Image"
},
{
"id": "testimonial_desc",
"type": "textarea",
"label": "Testimonial Description"
},
{
"id": "testimonial_author",
"type": "text",
"label": "Testimonial Author"
}
]
}
],
"presets": [
{
"name": "Video and Testimonial",
"category": "Testimonial",
"settings": {}
}
]
}
{% endschema %}
First we grab and display the variables from the Settings section of the JSON
<div class="medium-6 columns">
<div class="content-wrap">
<h3><span class="subheading">Learn 'How to' with our</span>{{ section.settings.video_title }}</h3>
<p>{{ section.settings.video_sub }}</p>
<a data-fancybox href="https://www.youtube.com/watch?v={{ section.settings.video_code }}" class="button">View Video</a>
</div>
</div>
<div class="medium-6 columns">
<a data-fancybox class="image-wrap" href="https://www.youtube.com/watch?v={{ section.settings.video_code }}">
<img class="play-button" src="//cdn.shopify.com/s/files/1/2602/4064/t/2/assets/play-button.png">
<img src="{{ section.settings.video_image | img_url }}">
</a>
</div>
Then we grab the repeating testimonial blocks
{% if section.blocks.size > 0 %}
<section class="testimonial1 angle-bigarrow">
<div class="row">
<div class="small-12 column">
<ul class="grid-1 wow fadeInUp">
{% for block in section.blocks %}
<li {{ block.shopify_attributes }}>
<div class="testimonial-inner">
<img src="{{ block.settings.image | img_url: '150x150' }}" alt="slider" />
<h5>{{ block.settings.testimonial_author }}</h5>
<p>{{ block.settings.testimonial_desc }}</p>
</div>
</li>
{% endfor %}
</ul>
</div>
</div>
</section>
{% endif %}
Shopify: List product variations on collection pages
The code below will allow you to display a set of product variations on a Shopify product collection pages.
Set this code in the collections page product loop, or within the liquid snippet that controls the display of products. On line three I’ve specified “Weight” as the option I want to display so on the list page the customer can see that I have 25ml, 50ml, and 100ml product sizes available.
{% for option in product.options %}
{% if option == 'Weight' %}
{% assign index = forloop.index0 %}
{% for variant in product.variants %}
{{ variant.options[index] }}
{% endfor %}
{% endif %}
{% endfor %}
|
__label__pos
| 0.50143 |
0
My Program changes it's My.settings to default , it looses the Location Where it is saved
This only happens when i move to a new area
But if i take a new builded exe and put it in same Dir of old exe then It Remembers old Settings
Anybody wanna share on how's this possible and maybe if there's a Fix or workaround
:)
4
Contributors
7
Replies
8
Views
5 Years
Discussion Span
Last Post by VB 2012
0
Can you please explain what you mean by
This only happens when i move to a new area
and
it looses the Location Where it is saved
?
0
The Settings are getting old Properties from last Build App in dir somehow??
0
If your project increase the file version each time you build your project then the settings are back to default.
The "my.settings" are stored in the file "user.config" at the following path:
C:\Users\<your user name>\AppData\Roaming\<your company>\<your project>\<version number>\user.config
As example:
C:\Users\GeekByChoiCe\AppData\Roaming\Multiplayer Gaming Solutions\GV_ACS\3.0.1.0\user.config
in most cases the company name in the project is not set, so the folder will be "Microsoft".
Edited by GeekByChoiCe: n/a
0
try to use the xml , to remember your application setting , i used xml file in my project to store , dbname , servername , bgcolo , text , location ,and other information , try to use xml to store your settings ,
Hope this will give u some idea ,
Best Regards
M.Waqas Aslam
0
Im am thinking about that idea waqasaslammmeo
Save.Settings still very Beta :(
and by the way anybody know the Location in Windows XP
Of wat GeekByChoiCe suggested
0
Okay i found Location but can someone help with Global Reading and writing (using ini,xml etc.)
0
And its still getting the Saved Settings some of it is Strings
How is this possible where are these files which have these properties stored
Or is it maybe in App:icon_neutral: if so then im kinda F*****
:'(
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.
|
__label__pos
| 0.549908 |
In Javascript, how would you print out the contents of an object?
Printing out the contents of a Javascript object can be very useful when debugging your Javascript code. There are a few different ways to print out an object, and we will show you all of them.
The Javascript For/in loop
One way to print out the contents of a Javascript object is by using the for/in loop. The for/in loop is completely different from a regular for loop, because the for/in loop is specifically used to iterate through the contents of an object. The general structure of a for/in loop looks like this:
for( variable in object)
statement
When using the for/in loop, the string that comes after the “in” must be an actual object – so whatever the name of your object is you can place it there. And the string that comes before the “in” operator can have any arbitrary name – in the code above it’s called “variable”, but we can technically call it whatever we want – whether it’s “foo”, “bar”, or whatever it does not matter since it is just a placeholder for each property in the Javascript object (this will make more sense when you see an example below).
So, to specifically print out each and every property’s value in the object, we can do this:
Example of using the Javascript For/in loop
// this is our sample object with 3 properties
var sampleObject = { x:1, y:2, z:3 };
var alertText = ' ';
/*Put the name of your own object after "in",
and you can change the text "property"
to be whatever you please.
*/
for (property in sampleObject) {
/*this will create one string with all the Javascript
properties and values to avoid multiple alert boxes: */
alertText += property + ':' + sampleObject[property]+'; ';
}
alert(alertText);
Console.log to print out Javascript objects
What if you don’t want to use a Javascript alert – maybe because you find that alert boxes are annoying? Another option is to use Console.log – it is a simple and clean way to print out the contents of a Javascript object, and it does not require that you iterate through each and every property like the for/in loop. But there is a catch: you must be working with a console. What is a console anyways? Well, think of it as your Javascript debugger. Every major browser comes with a console either built in or as an add-on. Firebug (for the popular Firefox browser) is the most popular debugging tool, and Chrome/Safari/IE all have their own developer tools that will display a Javascript console as well.
This is what a call to console.log would look like – remember that you can only see the output in your browser’s console screen:
var sampleObject = { x:1, y:2, z:3 };
console.log(sampleObject);
Console.log may break Internet Explorer Browsers
You should always remember to remove the calls to console.log from your code once you are done debugging – because those calls may prevent older versions of IE from correctly executing your scripts.
JSON.stringify function to print out Javascript objects
Another way to print out the contents of a Javascript object is to use the JSON.stringify function. This is a very nice way to print things out because you don’t have to use the console, and you don’t have to write out a for/in loop just to get properties to print out. It is our preferred way of printing out Javascript objects. Here’s an example of the JSON.stringify function in use:
var sampleObject = { x:1, y:2, z:3 };
var myObject = JSON.stringify(sampleObject);
alert(myObject); //this will output {"x":1, "y":2, "z":3}
JSON (JavaScript Object Notation) is a standard that is specifically meant for data interchange, and because JSON is a subset of Javascript, you should be able to use the function above without needing any supporting library files. The stringify method simply converts the Javascript object into JSON text, which is something that’s very easy to read and print out to the page.
toSource to print out objects in Firefox
And finally, we present one last option that isn’t very highly recommended simply because out of all the major browsers it will only work in Firefox (since Firefox is a Gecko based browser).
But, here is an example of using toSource to print out the contents of an object anyways:
var sampleObject = { x:1, y:2, z:3 };
alert("sampleObject is " + sampleObject.toSource());
Above, we presented a lot of different options for printing out Javascript objects. We personally think that the JSON Stringify function is the best because of its simplicity, but which one you choose to use is really up to you.
Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>
Subscribe to our newsletter for more free interview questions.
|
__label__pos
| 0.877638 |
Questions tagged [lower-bounds]
questions about lowerbounds on functions, usually the complexity of an algorithm or a problem
Filter by
Sorted by
Tagged with
46
votes
4answers
4k views
What are the best current lower bounds on 3SAT?
What are the best current lower bounds for time and circuit depth for 3SAT?
39
votes
2answers
2k views
Are the problems PRIMES, FACTORING known to be P-hard?
Let PRIMES (a.k.a. primality testing) be the problem: Given a natural number $n$, is $n$ a prime number? Let FACTORING be the problem: Given natural numbers $n$, $m$ with $1 \leq m \leq n$, ...
29
votes
7answers
2k views
Proving lower bounds by proving upper bounds
The recent breakthrough circuit complexity lower-bound result of Ryan Williams provides a proof technique that uses upper-bound result to prove complexity lower-bounds. Suresh Venkat in his answer to ...
22
votes
2answers
1k views
How does the Mulmuley-Sohoni geometric approach to producing lower bounds avoid producing natural proofs (in the Razborov-Rudich sense)?
The exact phrasing of the title is due to Anand Kulkarni (who proposed this site be created). This question was asked as an example question, but I’m insanely curious. I know very little about ...
18
votes
2answers
703 views
Bounds on the size of the smallest NFA for L_k-distinct
Consider the language $L_{k-distinct}$ consisting of all $k$-letter strings over $\Sigma$ such that no two letters are equal: $$ L_{k-distinct} :=\{w = \sigma_1\sigma_2...\sigma_k \mid \forall i\in[k]...
8
votes
2answers
1k views
(0,1)-vector XOR problem
this is a rewrite of another recent question of mine [1] that wasnt stated well (it had a semi obvious simplification, mea culpa) but I think theres still a nontrivial question at the heart of it. ...
58
votes
4answers
2k views
Problems that can be used to show polynomial-time hardness results
When designing an algorithm for a new problem, if I can't find a polynomial time algorithm after a while, I might try to prove it is NP-hard instead. If I succeed, I've explained why I couldn't find ...
23
votes
4answers
1k views
Separating Logspace from Polynomial time
It is clear that any problem that is decidable in deterministic logspace ($L$) runs in at most polynomial time ($P$). There is a wealth of complexity classes between $L$ and $P$. Examples include $NL$,...
18
votes
2answers
2k views
Hierarchy theorem for circuit size
I think that a size hierarchy theorem for circuit complexity can be a major breakthrough in the area. Is it an interesting approach to class separation? The motivation for the question is that we ...
14
votes
1answer
356 views
Lower bounds on the size of CFGs for specific finite languages
Consider the following natural question: Given a finite language $L$, what is the smallest context-free grammar generating $L$? We can make the question more interesting by specifying a sequence of ...
112
votes
17answers
8k views
Examples of the price of abstraction?
Theoretical computer science has provided some examples of "the price of abstraction." The two most prominent are for Gaussian elimination and sorting. Namely: It is known that Gaussian elimination ...
45
votes
0answers
1k views
Monotone complexity of s-t connectivity
In the problem CONN, we obtain a directed $n$-vertex graph (encoded as a boolean string of $n^2$ bits, one for each potential edge), and want to decide whether there is a path between all $n^2$ pairs $...
33
votes
2answers
1k views
Cohomological approach to boolean complexity
A few years ago, there was some work by Joel Friedman relating lower circuit bounds to Grothendieck cohomology (see papers: http://arxiv.org/abs/cs/0512008, http://arxiv.org/abs/cs/0604024). Has this ...
30
votes
0answers
4k views
Combinatorics of Bellman-Ford or how to make cyclic graphs acyclic?
Roughly speaking, my question is: How costly is to make a cyclic graph acyclic while preserving all simple $s$-$t$ paths? Let $K_n$ be a complete undirected graph on vertices $\{0,1,\ldots,n+1\}$. (...
25
votes
2answers
1k views
Formula size lower bounds for AC0 functions
Question: What is the best known formula size lower bound for an explicit function in AC0? Is there an explicit function with an $\Omega(n^2)$ lower bound? Background: Like most lower bounds, ...
19
votes
4answers
863 views
Parity and $AC^0$
Parity and $AC^0$ are like inseparable twins. Or so it has seemed for the last 30 years. In the light of Ryan's result, there will be renewed interest in the small classes. Furst Saxe Sipser to Yao ...
25
votes
3answers
3k views
Nontrivial algorithm for computing a sliding window median
I need to calculate the running median: Input: $n$, $k$, vector $(x_1, x_2, \dotsc, x_n)$. Output: vector $(y_1, y_2, \dotsc, y_{n-k+1})$, where $y_i$ is the median of $(x_i, x_{i+1}, \dotsc, x_{i+k-...
22
votes
2answers
1k views
Lower bound for determinant and permanent
In light of the recent chasm at depth-3 result (which among other things yields a $2^{\sqrt{n}\log{n}}$ depth-3 arithmetic circuit for the $n \times n $ determinant over $\mathbb{C}$), I have the ...
12
votes
2answers
2k views
Reversing a list using two queues
This question is inspired by an existing question about whether a stack can be simulated using two queues in amortized $O(1)$ time per stack operation. The answer seems to be unknown. Here is a more ...
6
votes
4answers
747 views
What are the best known upper bounds and lower bounds for computing O(log n)-Clique?
Input: a graph with n nodes, Output: A clique of size $O(\log n)$, Providing links to references would be great
7
votes
2answers
550 views
Communication lower bounds for partial boolean functions
There are well known techniques for proving lower bounds on the communication complexity of boolean functions, like fooling sets, the rank of the communication matrix, and discepancy. 1) How do we ...
40
votes
3answers
2k views
Circuit lower bounds over arbitrary sets of gates
In the 1980s, Razborov famously showed that there are explicit monotone Boolean functions (such as the CLIQUE function) that require exponentially many AND and OR gates to compute. However, the basis ...
14
votes
3answers
1k views
Lower Bounds for Data Structures
Are results known which rule out the existence of "too-good-to-be-true" data structures? For example: can one add $Split$ and $Join$ functionality to an order maintenance data structure (see Dietz ...
21
votes
6answers
1k views
References on Circuit Lower Bounds
Preamble Interactive proof systems and Arthur-Merlin protocols were introduced by Goldwasser, Micali and Rackoff and Babai back in 1985. At first, it was thought that the former is more powerful than ...
17
votes
2answers
768 views
Status on circuit lower bounds for polylog-bounded depth circuits
Bounded depth circuit complexity is one of the main areas of research within circuit complexity theory. This topic has origins in results like "the parity function is not in $AC^{0}$" and "the mod $p$ ...
22
votes
2answers
1k views
Protocol partition number and deterministic communication complexity
Besides (deterministic) communication complexity $cc(R)$ of a relation $R$, another basic measure for the amount of communication needed is the protocol partition number $pp(R)$. The relation between ...
15
votes
1answer
503 views
Do the proofs that permanent is not in uniform $\mathsf{TC^0}$ relativize?
This is a follow up to this question, and is related to this question of Shiva Kinali. It seems that the proofs in these papers (Allender, Caussinus-McKenzie-Therien-Vollmer, Koiran-Perifel) use ...
11
votes
4answers
536 views
Lower bound for testing closeness in $L_2$ norm?
I was wondering if there was any lower bound (in terms of sample complexity) known for the following problem: Given sample oracle access to two unknown distributions $D_1$, $D_2$ on $\{1,\dots,n\}$, ...
8
votes
1answer
350 views
Lower bound for NFA accepting 3 letter language
Related to a recent question (Bounds on the size of the smallest NFA for L_k-distinct) Noam Nisan asked for a method to give a better lower bound for the size of an NFA than what we get from ...
21
votes
2answers
987 views
Can addition be carried out in less than depth 5?
Using carry look ahead algorithm we can compute addition using a polynomial size depth 5 (or 4?) $AC^0$ circuit family. Is it possible to reduce the depth? Can we compute the addition of two binary ...
17
votes
2answers
581 views
Better lower bounds than 3n for non-boolean functions?
Blum's $3n-o(n)$ lower bound is the best known circuit lower bound over the complete basis for an explicit function $f : \{0,1\}^n \to \{0,1\}$, cf. Jukna's answer to this question for related results....
15
votes
0answers
578 views
Lower bounds on single-source shortest paths in directed graphs
Are there any non-trivial lower bounds on the complexity of single-source shortest paths (SSSP) in a directed graph, where all edges have non-negative edge weights? Can we rule out the possibility of ...
11
votes
1answer
497 views
Lower bounds for learning in the membership query and counterexample model
Dana Angluin (1987; pdf) defines a learning model with membership queries and theory queries (counterexamples to a proposed function). She shows that a regular language that is represented by a ...
11
votes
1answer
433 views
Lower bounds for Nondeterministic Multiparty Communication
This is a continuation of my previous question on communication lower bounds for partial boolean functions. Can someone suggest any reference on lower bounds for nondeterministic multiparty ...
9
votes
2answers
192 views
Existence of “colouring matrices”
Edit: there is now a follow-up question related to this post. Definitions Let $c$ and $k$ be integers. We use the notation $[i] = \{1,2,...,i\}$. A $c \times c$ matrix $M = (m_{i,j})$ is said to be ...
1
vote
1answer
325 views
Questions about computing matrix rigidity
Matrix rigidity was introduced by Valiant in 1977: The rigidity $Rig_M(r)$ of boolean matrix $M$ over GF(2) is the smallest number of entries of $M$ that must be changed in order to reduce its ...
19
votes
2answers
703 views
Deterministic communication complexity vs partition number
Background: Consider the usual two-party model of communication complexity where Alice and Bob are given $n$-bit strings $x$ and $y$ and have to compute some Boolean function $f(x,y)$, where $f:\{0,1\...
14
votes
2answers
674 views
Lower bounds on #SAT?
The problem #SAT is the canonical #P-complete problem. It's a function problem rather than a decision problem. It asks, given a boolean formula $F$ in propositional logic, how many satisfying ...
8
votes
1answer
340 views
Are there more polynomial time problems with complexity lower bounds?
I'm looking for more problems in $P$ with classical time complexity lower bounds. Some people might wonder how you could prove such a lower bound. See below. Exponential Lower Bounds: Claim: If ...
8
votes
0answers
256 views
Existence of “colouring matrices” — a generalisation
This is a generalisation of the following post: Existence of "colouring matrices". As the base case turned out to be fairly straightforward (in essence, precisely equal to the existence of Sperner ...
5
votes
2answers
378 views
Lower bound proof for compressive sensing (Gel'fand widths)?
Let $x \in \mathbb{R}^n$ have $k$ non-zero entries. The main insight of compressive sensing is that there exist $m\times n$ matrices $A$ with $m = O(k \log n/k)$ such that any $x$ can be recovered ...
5
votes
0answers
138 views
How hard is it to generate a set of relatively prime numbers between two given bounds?
Informal Question How hard is it to generate a set of relatively prime numbers between two given bounds? Decision Problem Given $a$, $b$, and $k \in \mathbb{N}$. Does there exist a set $S \...
5
votes
1answer
345 views
Stronger Lower Bounds on Nondeterministic Multiparty Communication
This is a continuation of my previous question on Lower bounds for Nondeterministic Multiparty Communication. From the answer, the $\mu^\infty$ norm lower bounds nondeterministic multiparty ...
4
votes
0answers
207 views
One-way randomized complexity of (variants of) Gap-Hamming-Distance?
The $\textsf{GapHammingDistance}$ problem over $\{0,1\}^n$ is defined as follows: Alice (resp. Bob) is given an input $x\in\{0,1\}^n$ (resp, $y\in\{0,1\}^n$), under the promise that their Hamming ...
4
votes
2answers
437 views
P/poly vs NP separation based on circuit trees instead of DAGs
there are various theorems that relate major complexity class separations to circuit family DAGs sizes, in particular for P/poly vs NP. in contrast, are there theorems/conjectures that relate P/...
3
votes
0answers
105 views
What is the strongest known lower bound against SIZE(n)?
What is the best known lower bound against (nonuniform) circuits of size $O(n)$? I understand that we don't know of any explicit functions that need circuits of size more than something like $5n$. But ...
3
votes
0answers
457 views
Is there a tight lower bound on the complexity of SSSP on a graph?
I'm an undergrad and I'm not sure if this is the right way to ask this question. I want to know the lower bound on single-source shortest path computation in a general graph. The graph is allowed to ...
10
votes
1answer
1k views
How many disjoint edge-cuts a DAG must have?
The following question is related to the optimality of the Bellman-Ford $s$-$t$ shortest path dynamic programming algorithm (see this post for a connection). Also, a positive answer would imply that ...
6
votes
1answer
393 views
Nondeterministic communication complexity of set disjointness?
In the two-party setting, bounds of $\Theta(n)$ bits are known for deterministic and bounded-error randomized protocols for $\text{DISJ}_n$. (Here $\text{DISJ}_n$ is the $n$-element set disjointness ...
5
votes
2answers
693 views
lower bound of majority function?
If a circuit ({AND OR NOT} circuit) with depth d computes the majority function, what's the best lower bound for majority function? I know the lower bound for parity function is $ 2^{\Omega (n^{1/d})} ...
|
__label__pos
| 0.888775 |
Mathematics: Discovered or Invented?
Discussion in 'Math' started by PG1995, Sep 26, 2011.
1. PG1995
Thread Starter Well-Known Member
Apr 15, 2011
813
6
Hi :)
Some people are of the position that math is discovered while others say it's invented. I think in a way both parties are at extreme ends. I think math is discovered as well as invented. There are some fixed mathematical relations in nature which exist on their own such as ratio of circumference over diameter, golden ration, ratio of sides of triangle, etc. These 'natural' relations constitute part of discovered mathematics. Then, humans use these relations and invent some of their own systems to create new math which is amalgamation of 'discovered' and 'invented' mathematics. This also implies that mathematics as a whole is not a universal language. I believe the part which includes natural relations (such as ration of circumference and diameter) is universal and will be true and applicable everywhere. But the part which contains human innovations and inventions is not universal. Recently someone told me that Godel's incompleteness theorem proves this point. What is your opinion on this? Please let me know. Thank you.
Regards
PG
2. Wendy
Moderator
Mar 24, 2008
21,526
2,972
I already had my say, this is the same thread restated as far as I can tell.
3. PG1995
Thread Starter Well-Known Member
Apr 15, 2011
813
6
Yes, Bill. But that thread was on imaginary numbers. I did'nt give it full attention there and I didn't put forward my case there. Here I have devoted a separate thread on this topic and have also stated my own opinion. As you have also given your opinion and I have read it, you are free to skip it if you like! ;)
Best wishes
PG
4. steveb
Senior Member
Jul 3, 2008
2,432
469
I'll be a devil and argue that mathematics is abstraction, and hence an invention of man. The aspects of math that we feel are discoveries are simply abstractions that closely relate to the physical world. Those physical things are discoveries of science, not mathematics.
For example, the fact that the ratio of the circumference of a circle to the diameter of a circle is always pi to very high accuracy is a scientific discovery. The mathematical description that pi is a transendental number with particular digits that is always exactly the same for any circle in any place, is an invented abstraction. We invent starting assumptions and create an abstract structure (called Euclidian space) and deduce these facts. If you've discovered anything, it is only a discovery in an artificial landscape you first had to invent, not a true discovery in the real world. Real discoveries like this are called scientific discoveries.
In other words, the fact that mathematics is useful as an abstract language of physics and other sciences, makes it appear to be discovered truth, but the real world never exactly conforms to our mathematical models. Hence, the pure mathematics is an invention which creates an abstract false-reality that is invented by us, and nothing in that false reality can be discovered because it results from an invention, and is hence an invention itself. At best, it's an invented discovery.
5. PG1995
Thread Starter Well-Known Member
Apr 15, 2011
813
6
Thank you, Steve.
I think you are referring to pure mathematics. But pure mathematics is a later stage and highly abstract field, the stage which comes first and has driven almost all the math in the past is applied math which is closely intertwined with physical science. That's my two cents!
Regards
PG
6. debjit625
Well-Known Member
Apr 17, 2010
790
186
I feel any invention is based on some discovery.Mathematics is a universal language, it was their all over the universe all the time, its just we humans discovered it on earth at some moment of time and still we are discovering it.
I like what Cantor said
In accadimics we don't get this freedom at least I feel so.
7. steveb
Senior Member
Jul 3, 2008
2,432
469
You are welcome PG.
I don't understand the distinction of "pure mathematics". Is there a pure and impure mathematics? :rolleyes: People seem to feel that "pure mathematics" is that which does not get applied to something, yet often the invented pure mathematics is later applied to something useful. Does the invention then become a discovery? Anyway, this term is not very useful to our discussion.
But, I do understand the term "abstract mathematics", and my argument is that ALL mathematics is abstract mathematics. Just because the invention of the mathematics was motivated by a real world problem, and just because we apply mathematics to some real world situation does not change that.
If you disagree, I would challenge you to find any mathematic model, that is applied to the real world, which is an EXACT description of reality. One example is all it takes for you to prove your point. Unfortunately, I have the more difficult problem of "trying to prove a negative". I can't prove that there is a reality that can not be exactly and perfectly described by mathematics. :p I can say that in all my studies, I have never found an example of it. As you may know, physicists are trying very hard to invent/discover a mathematical model of the universe that is exact, and they have, as yet, not even come close to achieving that goal.
Last edited: Sep 26, 2011
8. Wendy
Moderator
Mar 24, 2008
21,526
2,972
It could be argued math (all math) is a language, and is therefore an invention.
I may have been talking in the imaginary numbers thread, but my reply's were specifically answered this thread. As a matter of fact imaginary numbers are but a subset of math, which is to say there is no difference.
9. PG1995
Thread Starter Well-Known Member
Apr 15, 2011
813
6
Hi Bill
Yes, your reply was specifically about this topic and was helpful (perhaps, your reply was one of the reasons which made me think about the foundation of mathematics specifically). That's the reason I said that you can skip it if you like.
Peace
PG
10. tgotwalt1158
Member
Feb 28, 2011
110
18
The manifestation of the whole universe is based upon a divine algorithm. The existing known mathematics to humans or by humans may be a tiny sub set of that algorithm.
11. BillO
Distinguished Member
Nov 24, 2008
992
139
Yeah, right. Divine....
12. BillO
Distinguished Member
Nov 24, 2008
992
139
Although....
Mathematics is a wholly human construct inspired by the nature of our universe.
Just an opinion now, not the gospel.
13. Adjuster
Late Member
Dec 26, 2010
2,147
302
I wonder if this is a question we can ever expect to answer, and even whether it is worth trying. One difficulty I see is that some things may seem "obvious" to us which rest on assumptions we are not conscious of, but take for granted.
Trying to imagine for instance how a non-human intelligence would view the Universe, we might imagine that it would use a system of mathematics as we do. However, if the basis of this other intelligence was something very different from the human brain, it might have totally different ways of processing information. There appear to be structures in our brain that facilitate calculation: if these are damaged, then that ability is lost. Do we assume that we process information this way because mathematics is universal, or do we assume mathematics is universal because our brain structure makes it seem that way?
PG1995 likes this.
14. count_volta
Active Member
Feb 4, 2009
434
24
I like what you said Adjuster. I agree.
But lets look at the simple definition of math. You have a tiger in the jungle. Then you also have another tiger in the same jungle. Now we say that there are two tigers.
2 is a human invention to represent the fact that there are multiple tigers in the jungle. We did not create the first tiger, it was just born and there it is. Nor did we create the second tiger. So even if human beings did not exist there would be 2 tigers in the universe.
So the thing that we call 1 2 3 4 5 6....... exists independently of humans. Or hell just take the billions of stars in the universe. And they follow a certain universal law that Newton just happened to call gravity. So gravity is independant of humans also. This can be extended to all natural phenomena.
PG1995 likes this.
15. THE_RB
AAC Fanatic!
Feb 11, 2008
5,430
1,311
I think it's necessary to separate the meaning of the terms.
To me, "discovered" implies that which already existed before the "discovery" like "the island of Hawaii was discovered".
And "invented" implies that it did not exist before being invented, as in "Dubai's Palm Island was invented".
So when referring to math, the correct word would depend on whether that particular part of math already clearly existed (like Pi) or was "created" when no obvious examples were in existence.
I would say "infinity" was invented. Zero was discovered.
PG1995 likes this.
16. PG1995
Thread Starter Well-Known Member
Apr 15, 2011
813
6
Thank you, RB.
Actually this was my take in my original post. I don't think we can say math is entirely human invention.
Regards
PG
17. steveb
Senior Member
Jul 3, 2008
2,432
469
It's ok to say zero and pi are discoverd and it's ok to believe it . I'm not sure one can really prove numbers exists in reality, and as I said above, I can't prove a negative and claim that you can't find a place where these numbers have real existence. But, what is your argument to convince others that zero and pi are discovered?
What you said is confusing to me. You are saying that infinity was invented, but "pi already clearly existed" Huh? Clearly? Where does pi exist in the real world? We think of it as an infinite series of numbers. How can something made of infinity, which is invented, be something real to be discovered.
It seems to me pi is an abstraction that does not exist anywhere in the real world. It doesn't even exist as the ratio of circumference to diameter of a circle because circles in the real world don't obey this formula. Even if you could make a circle perfectly (which you can't), the warping of spacetime prevents the ratio from being perfectly accurate. And even if we lived in Euclidean space and could make a perfect circle, how could you do the measurement that proves with certainty that the space is Euclidean and the circle is perfect? The concept of pi in this context is an abstraction.
The concept of zero also is not straightforward. Where does zero exist in the real world? We can make an abstraction that there are zero tigers in the room, and the fact that there are no tigers there could even be termed as "a discovery". But the concept of zero is an abstraction that simplifies the reality and is not that reality. If the room has people in it, then all the basic ingredients of tigers are in that room, since maybe 4 people could have all the atoms and molecules needed to make one tiger. But, we abstract the idea of tiger and classify it, and then we count the number of things that fit the abstract concept in our minds. Yes, tigers exist and can be discovered once we define what a tiger is, but zero tigers can't exist. You can't discover zero of anything, but you can invent the abstract idea of the absence of something. Further, zero does not exist in the real world as in independent thing, as far as we know. Even a vacuum has stuff in it.
Last edited: Oct 5, 2011
18. THE_RB
AAC Fanatic!
Feb 11, 2008
5,430
1,311
Well let's say there is an alien civilisation out there on another planet somewhere...
At some early point in their science history the early mathematicians would have realised that there is a simple relationship (which exists even before discovery) between the diameter of a circle and the distance around its circumference. They would have the same discovery of Pi that we had, as the Pi relationship is real and always exists. The circle is a real thing, and both it's diameter and circumference are real characteristics, simple and empirically measurable.
I think that would always be the basis for "discovering" math principles, the fundamental principles that are real, can be measured and demonstrated with real models, and compared to a pure math model.
Likewise zero is a real model. A box can hold 3,2,1, or 0 apples. All 4 conditions are equally demonstratable. An object may have a speed of zero, or 1 or 2 or 3 MPH. A geometric object drawn on a grid can have one side with a length of 3cm, 2cm, 1cm or 0cm. All demonstratable and real. I have to conclude zero is a real thing and would be discovered quite early within the scientific development of a civilisation.
So any aliens we bump into will understand Pi, and have the same value for Pi we have, likewise other relationships for triangles, squares and square roots, multiplication and division etc. It is generally accepted that communication with an alien race (if one existed) would start with these math concepts as they MUST be universal and clearly understood by any advanced civilisation.
Now infinity on the other hand, to me seems "invented". It can't be modelled or demonstrated in any real way and only really exists conceptually as the reciprocal of zero. Or not the reciprocal of zero, as math nerds will argue. :)
19. steveb
Senior Member
Jul 3, 2008
2,432
469
Interesting discussion. I like the fact that you bring simple numbers into the discussion because it seems to me that it is easier to claim that counting numbers have real existence than numbers like 0, infinity, transcendental numbers and i=sqrt(-1). Many things seem to quantize to discrete levels in the real world. Atoms have discrete energy states and they also have a discrete number of particles. The hydrogen atom is like the number 1 if we count protons. A stray neutron is also like the number one. But, a neutron and a proton is also like the number 3 because they are made of 3 quarks, and this is where the abstraction reveals itself. It all depends on how you look at reality.
Anyway, a person who wants to prove that math has any aspects that are discovered, should start with the simplest example, since he only needs to prove one example, and natural counting numbers are a good place to look.
But, it's hard to prove anything here on either side.
I also like your argument that another alien civilization would come up with the same mathematics. If every independent intelligent being always arrives at the same mathematical language, it would tend to suggest that there is something "out there" tangible that we are all "discovering". But, I guess we can't know that for sure, unless we meet many other civilizations.
I don't like the argument about pi. I've mentioned this a couple of times above and nobody seems to want to address my points about the fact that we do not live in Euclidean space. Real circles with the property that ratio of circumference to diameter is a constant and that that constant is exactly equal to the transcendental number we call pi is a complete fairy story. It's just not true physics. It's approximately true physics for sure, but "approximately true" is infinitely far from "perfectly true" when it comes to mathematics. Perhaps this point is too subtle for anyone to notice, but I believe it is the crux of the entire question.
Personally, I feel that numbers are abstractions, but counting numbers come the closest to having real existence, in my mind. I also feel that infinity is invented, but I think it is the one candidate that had the potential to be a real discovery. If physics had discovered that the universe is infinite and unbounded (which doesn't seem to be the current view), then that would be an example of the math discovering something real. But it seems there is no place where you can find infinity of anything (distance, mass, charge, energy ... etc). But, if we find an example, then PG's point is proved conclusively.
So, my view is that mathematics has the potential to really discover something, but I don't know a good example of it, and perhaps it hasn't happened yet. But, that's why I'm asking for examples. I don't know everything and there may be a good example I'm not thinking of. It seems, so far, math has been abstraction that can model interesting aspects of the real world, but it never does so perfectly. Physics uses math more than any other science, and physics discoveries often take the form of ... "hey look, I have discovered that this particular aspect of nature behaves very similarly to this mathematical model I've developed". If only that model were exact, then a mathematical derivation might have discovered something real. But, it is usually experiments that reveal the discovery, and the model is made to fit the data.
One thing is certain however. Mathematics is a great tool for discovery. Whether we are inventing that tool, discovering that tool or doing a combination of both doesn't change that fact.
20. t_n_k
AAC Fanatic!
Mar 6, 2009
5,448
790
King Solomon apparently had an object [the "Sea"] made for his temple which points to an "estimate" for the value of what we call Pi - see Second Chronicles Chapter 4 verse 2.
Loading...
|
__label__pos
| 0.543474 |
From patchwork Tue Mar 1 10:12:38 2011 Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: [U-Boot,v2] fsl_esdhc: Correcting esdhc timeout counter calculation Date: Tue, 01 Mar 2011 00:12:38 -0000 From: Priyanka Jain X-Patchwork-Id: 84923 Message-Id: <[email protected]> To: Cc: Priyanka Jain , Andy Fleming , Kumar Gala - Timeout counter value is set as DTOCV bits in SYSCTL register For counter value set as timeout, Timeout period = (2^(timeout + 13)) SD Clock cycles - As per 4.6.2.2 section of SD Card specification v2.00, host should cofigure timeout period value to minimum 0.25 sec. - Number of SD Clock cycles for 0.25sec should be minimum (SD Clock/sec * 0.25 sec) SD Clock cycles = (mmc->tran_speed * 1/4) SD Clock cycles - Calculating timeout based on (2^(timeout + 13)) >= mmc->tran_speed * 1/4 Taking log2 both the sides and rounding up to next power of 2 => timeout + 13 = log2(mmc->tran_speed/4) + 1 Signed-off-by: Priyanka Jain Signed-off-by: Andy Fleming Signed-off-by: Kumar Gala Acked-by: Mingkai Hu --- Changes for v2: Added proper description as suggested by Wolfgang Denk drivers/mmc/fsl_esdhc.c | 15 +++++++++++++-- 1 files changed, 13 insertions(+), 2 deletions(-) diff --git a/drivers/mmc/fsl_esdhc.c b/drivers/mmc/fsl_esdhc.c index 9c69cc7..e8dd9b7 100644 --- a/drivers/mmc/fsl_esdhc.c +++ b/drivers/mmc/fsl_esdhc.c @@ -207,8 +207,19 @@ static int esdhc_setup_data(struct mmc *mmc, struct mmc_data *data) esdhc_write32(®s->blkattr, data->blocks << 16 | data->blocksize); /* Calculate the timeout period for data transactions */ - /* Timeout period = (2^(13+timeout))/mmc->trans_speed - * Timeout period should be minimum 250msec as per SD Card spec + /* + * 1)Timeout period = (2^(timeout+13)) SD Clock cycles + * 2)Timeout period should be minimum 0.250sec as per SD Card spec + * So, Number of SD Clock cycles for 0.25sec should be minimum + * (SD Clock/sec * 0.25 sec) SD Clock cycles + * = (mmc->tran_speed * 1/4) SD Clock cycles + * As 1) >= 2) + * => (2^(timeout+13)) >= mmc->tran_speed * 1/4 + * Taking log2 both the sides + * => timeout + 13 >= log2(mmc->tran_speed/4) + * Rounding up to next power of 2 + * => timeout + 13 = log2(mmc->tran_speed/4) + 1 + * => timeout + 13 = fls(mmc->tran_speed/4) */ timeout = fls(mmc->tran_speed/4); timeout -= 13;
|
__label__pos
| 0.961022 |
Class: Puppet::Util::CommandLine::Trollop::Parser
Inherits:
Object
• Object
show all
Defined in:
lib/puppet/util/command_line/trollop.rb
Overview
The commandline parser. In typical usage, the methods in this class will be handled internally by Trollop::options. In this case, only the #opt, #banner and #version, #depends, and #conflicts methods will typically be called.
If you want to instantiate this class yourself (for more complicated argument-parsing logic), call #parse to actually produce the output hash, and consider calling it from within Trollop::with_standard_exception_handling.
Constant Summary collapse
FLAG_TYPES =
The set of values that indicate a flag option when passed as the :type parameter of #opt.
[:flag, :bool, :boolean]
SINGLE_ARG_TYPES =
The set of values that indicate a single-parameter (normal) option when passed as the :type parameter of #opt.
A value of io corresponds to a readable IO resource, including a filename, URI, or the strings ‘stdin’ or ‘-’.
[:int, :integer, :string, :double, :float, :io, :date]
MULTI_ARG_TYPES =
The set of values that indicate a multiple-parameter option (i.e., that takes multiple space-separated values on the commandline) when passed as the :type parameter of #opt.
[:ints, :integers, :strings, :doubles, :floats, :ios, :dates]
TYPES =
The complete set of legal values for the :type parameter of #opt.
FLAG_TYPES + SINGLE_ARG_TYPES + MULTI_ARG_TYPES
INVALID_SHORT_ARG_REGEX =
:nodoc:
/[\d-]/
Instance Attribute Summary collapse
Instance Method Summary collapse
Constructor Details
#initialize(*a, &b) ⇒ Parser
Initializes the parser, and instance-evaluates any block given.
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/puppet/util/command_line/trollop.rb', line 93
def initialize *a, &b
@version = nil
@leftovers = []
@specs = {}
@long = {}
@short = {}
@order = []
@constraints = []
@stop_words = []
@stop_on_unknown = false
# instance_eval(&b) if b # can't take arguments
cloaker(&b).bind_call(self, *a) if b
end
Instance Attribute Details
#create_default_short_optionsObject
A flag that determines whether or not to attempt to automatically generate “short” options if they are not
explicitly specified.
81
82
83
# File 'lib/puppet/util/command_line/trollop.rb', line 81
def create_default_short_options
@create_default_short_options
end
#handle_help_and_versionObject
A flag indicating whether or not the parser should attempt to handle “–help” and
"--version" specially. If 'false', it will treat them just like any other option.
90
91
92
# File 'lib/puppet/util/command_line/trollop.rb', line 90
def handle_help_and_version
@handle_help_and_version
end
#ignore_invalid_optionsObject
A flag that determines whether or not to raise an error if the parser is passed one or more
options that were not registered ahead of time. If 'true', then the parser will simply
ignore options that it does not recognize.
86
87
88
# File 'lib/puppet/util/command_line/trollop.rb', line 86
def ignore_invalid_options
@ignore_invalid_options
end
#leftoversObject (readonly)
The values from the commandline that were not interpreted by #parse.
73
74
75
# File 'lib/puppet/util/command_line/trollop.rb', line 73
def leftovers
@leftovers
end
#specsObject (readonly)
The complete configuration hashes for each option. (Mainly useful for testing.)
77
78
79
# File 'lib/puppet/util/command_line/trollop.rb', line 77
def specs
@specs
end
Instance Method Details
Adds text to the help display. Can be interspersed with calls to #opt to build a multi-section help page.
270
# File 'lib/puppet/util/command_line/trollop.rb', line 270
def banner s; @order << [:text, s] end
#conflicts(*syms) ⇒ Object
Marks two (or more!) options as conflicting.
282
283
284
285
# File 'lib/puppet/util/command_line/trollop.rb', line 282
def conflicts *syms
syms.each { |sym| raise ArgumentError, _("unknown option '%{sym}'") % { sym: sym } unless @specs[sym] }
@constraints << [:conflicts, syms]
end
#depends(*syms) ⇒ Object
Marks two (or more!) options as requiring each other. Only handles undirected (i.e., mutual) dependencies. Directed dependencies are better modeled with Trollop::die.
276
277
278
279
# File 'lib/puppet/util/command_line/trollop.rb', line 276
def depends *syms
syms.each { |sym| raise ArgumentError, _("unknown option '%{sym}'") % { sym: sym } unless @specs[sym] }
@constraints << [:depends, syms]
end
#die(arg, msg) ⇒ Object
The per-parser version of Trollop::die (see that for documentation).
556
557
558
559
560
561
562
563
564
# File 'lib/puppet/util/command_line/trollop.rb', line 556
def die arg, msg
if msg
$stderr.puts _("Error: argument --%{value0} %{msg}.") % { value0: @specs[arg][:long], msg: msg }
else
$stderr.puts _("Error: %{arg}.") % { arg: arg }
end
$stderr.puts _("Try --help for help.")
exit(-1)
end
#educate(stream = $stdout) ⇒ Object
Print the help message to stream.
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'lib/puppet/util/command_line/trollop.rb', line 467
def educate stream = $stdout
width # just calculate it now; otherwise we have to be careful not to
# call this unless the cursor's at the beginning of a line.
left = {}
@specs.each do |name, spec|
left[name] = "--#{spec[:long]}" +
(spec[:short] && spec[:short] != :none ? ", -#{spec[:short]}" : "") +
case spec[:type]
when :flag; ""
when :int; " <i>"
when :ints; " <i+>"
when :string; " <s>"
when :strings; " <s+>"
when :float; " <f>"
when :floats; " <f+>"
when :io; " <filename/uri>"
when :ios; " <filename/uri+>"
when :date; " <date>"
when :dates; " <date+>"
end
end
leftcol_width = left.values.map(&:length).max || 0
rightcol_start = leftcol_width + 6 # spaces
unless @order.size > 0 && @order.first.first == :text
stream.puts "#{@version}\n" if @version
stream.puts _("Options:")
end
@order.each do |what, opt|
if what == :text
stream.puts wrap(opt)
next
end
spec = @specs[opt]
stream.printf " %#{leftcol_width}s: ", left[opt]
desc = spec[:desc] + begin
default_s = case spec[:default]
when $stdout; "<stdout>"
when $stdin; "<stdin>"
when $stderr; "<stderr>"
when Array
spec[:default].join(", ")
else
spec[:default].to_s
end
if spec[:default]
if spec[:desc] =~ /\.$/
_(" (Default: %{default_s})") % { default_s: default_s }
else
_(" (default: %{default_s})") % { default_s: default_s }
end
else
""
end
end
stream.puts wrap(desc, :width => width - rightcol_start - 1, :prefix => rightcol_start)
end
end
#opt(name, desc = "", opts = {}) ⇒ Object
Define an option. name is the option name, a unique identifier for the option that you will use internally, which should be a symbol or a string. desc is a string description which will be displayed in help messages.
Takes the following optional arguments:
:long
Specify the long form of the argument, i.e. the form with two dashes. If unspecified, will be automatically derived based on the argument name by turning the name option into a string, and replacing any _’s by -‘s.
:short
Specify the short form of the argument, i.e. the form with one dash. If unspecified, will be automatically derived from name.
:type
Require that the argument take a parameter or parameters of type type. For a single parameter, the value can be a member of SINGLE_ARG_TYPES, or a corresponding Ruby class (e.g. Integer for :int). For multiple-argument parameters, the value can be any member of MULTI_ARG_TYPES constant. If unset, the default argument type is :flag, meaning that the argument does not take a parameter. The specification of :type is not necessary if a :default is given.
:default
Set the default value for an argument. Without a default value, the hash returned by #parse (and thus Trollop::options) will have a nil value for this key unless the argument is given on the commandline. The argument type is derived automatically from the class of the default value given, so specifying a :type is not necessary if a :default is given. (But see below for an important caveat when :multi: is specified too.) If the argument is a flag, and the default is set to true, then if it is specified on the commandline the value will be false.
:required
If set to true, the argument must be provided on the commandline.
:multi
If set to true, allows multiple occurrences of the option on the commandline. Otherwise, only a single instance of the option is allowed. (Note that this is different from taking multiple parameters. See below.)
Note that there are two types of argument multiplicity: an argument can take multiple values, e.g. “–arg 1 2 3”. An argument can also be allowed to occur multiple times, e.g. “–arg 1 –arg 2”.
Arguments that take multiple values should have a :type parameter drawn from MULTI_ARG_TYPES (e.g. :strings), or a :default: value of an array of the correct type (e.g. [String]). The value of this argument will be an array of the parameters on the commandline.
Arguments that can occur multiple times should be marked with :multi => true. The value of this argument will also be an array. In contrast with regular non-multi options, if not specified on the commandline, the default value will be [], not nil.
These two attributes can be combined (e.g. :type => :strings, :multi => true), in which case the value of the argument will be an array of arrays.
There’s one ambiguous case to be aware of: when :multi: is true and a :default is set to an array (of something), it’s ambiguous whether this is a multi-value argument as well as a multi-occurrence argument. In this case, Trollop assumes that it’s not a multi-value argument. If you want a multi-value, multi-occurrence argument with a default value, you must specify :type as well.
Raises:
• (ArgumentError)
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/puppet/util/command_line/trollop.rb', line 148
def opt name, desc = "", opts = {}
raise ArgumentError, _("you already have an argument named '%{name}'") % { name: name } if @specs.member? name
## fill in :type
opts[:type] = # normalize
case opts[:type]
when :boolean, :bool; :flag
when :integer; :int
when :integers; :ints
when :double; :float
when :doubles; :floats
when Class
case opts[:type].name
when 'TrueClass', 'FalseClass'; :flag
when 'String'; :string
when 'Integer'; :int
when 'Float'; :float
when 'IO'; :io
when 'Date'; :date
else
raise ArgumentError, _("unsupported argument type '%{type}'") % { type: opts[:type].class.name }
end
when nil; nil
else
raise ArgumentError, _("unsupported argument type '%{type}'") % { type: opts[:type] } unless TYPES.include?(opts[:type])
opts[:type]
end
## for options with :multi => true, an array default doesn't imply
## a multi-valued argument. for that you have to specify a :type
## as well. (this is how we disambiguate an ambiguous situation;
## see the docs for Parser#opt for details.)
disambiguated_default =
if opts[:multi] && opts[:default].is_a?(Array) && !opts[:type]
opts[:default].first
else
opts[:default]
end
type_from_default =
case disambiguated_default
when Integer; :int
when Numeric; :float
when TrueClass, FalseClass; :flag
when String; :string
when IO; :io
when Date; :date
when Array
if opts[:default].empty?
raise ArgumentError, _("multiple argument type cannot be deduced from an empty array for '%{value0}'") % { value0: opts[:default][0].class.name }
end
case opts[:default][0] # the first element determines the types
when Integer; :ints
when Numeric; :floats
when String; :strings
when IO; :ios
when Date; :dates
else
raise ArgumentError, _("unsupported multiple argument type '%{value0}'") % { value0: opts[:default][0].class.name }
end
when nil; nil
else
raise ArgumentError, _("unsupported argument type '%{value0}'") % { value0: opts[:default].class.name }
end
raise ArgumentError, _(":type specification and default type don't match (default type is %{type_from_default})") % { type_from_default: type_from_default } if opts[:type] && type_from_default && opts[:type] != type_from_default
opts[:type] = opts[:type] || type_from_default || :flag
## fill in :long
opts[:long] = opts[:long] ? opts[:long].to_s : name.to_s.tr("_", "-")
opts[:long] =
case opts[:long]
when /^--([^-].*)$/
::Regexp.last_match(1)
when /^[^-]/
opts[:long]
else
raise ArgumentError, _("invalid long option name %{name}") % { name: opts[:long].inspect }
end
raise ArgumentError, _("long option name %{value0} is already taken; please specify a (different) :long") % { value0: opts[:long].inspect } if @long[opts[:long]]
## fill in :short
unless opts[:short] == :none
opts[:short] = opts[:short].to_s if opts[:short]
end
opts[:short] = case opts[:short]
when /^-(.)$/; ::Regexp.last_match(1)
when nil, :none, /^.$/; opts[:short]
else raise ArgumentError, _("invalid short option name '%{name}'") % { name: opts[:short].inspect }
end
if opts[:short]
raise ArgumentError, _("short option name %{value0} is already taken; please specify a (different) :short") % { value0: opts[:short].inspect } if @short[opts[:short]]
raise ArgumentError, _("a short option name can't be a number or a dash") if opts[:short] =~ INVALID_SHORT_ARG_REGEX
end
## fill in :default for flags
opts[:default] = false if opts[:type] == :flag && opts[:default].nil?
## autobox :default for :multi (multi-occurrence) arguments
opts[:default] = [opts[:default]] if opts[:default] && opts[:multi] && !opts[:default].is_a?(Array)
## fill in :multi
opts[:multi] ||= false
opts[:desc] ||= desc
@long[opts[:long]] = name
@short[opts[:short]] = name if opts[:short] && opts[:short] != :none
@specs[name] = opts
@order << [:opt, name]
end
#parse(cmdline = ARGV) ⇒ Object
Parses the commandline. Typically called by Trollop::options, but you can call it directly if you need more control.
throws CommandlineError, HelpNeeded, and VersionNeeded exceptions.
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
# File 'lib/puppet/util/command_line/trollop.rb', line 312
def parse cmdline = ARGV
vals = {}
required = {}
if handle_help_and_version
unless @specs[:version] || @long["version"]
opt :version, _("Print version and exit") if @version
end
opt :help, _("Show this message") unless @specs[:help] || @long["help"]
end
@specs.each do |sym, opts|
required[sym] = true if opts[:required]
vals[sym] = opts[:default]
vals[sym] = [] if opts[:multi] && !opts[:default] # multi arguments default to [], not nil
end
resolve_default_short_options if create_default_short_options
## resolve symbols
given_args = {}
@leftovers = each_arg cmdline do |arg, params|
sym = case arg
when /^-([^-])$/
@short[::Regexp.last_match(1)]
when /^--no-([^-]\S*)$/
@long["[no-]#{::Regexp.last_match(1)}"]
when /^--([^-]\S*)$/
@long[::Regexp.last_match(1)] || @long["[no-]#{::Regexp.last_match(1)}"]
else
raise CommandlineError, _("invalid argument syntax: '%{arg}'") % { arg: arg }
end
unless sym
next 0 if ignore_invalid_options
raise CommandlineError, _("unknown argument '%{arg}'") % { arg: arg } unless sym
end
if given_args.include?(sym) && !@specs[sym][:multi]
raise CommandlineError, _("option '%{arg}' specified multiple times") % { arg: arg }
end
given_args[sym] ||= {}
given_args[sym][:arg] = arg
given_args[sym][:params] ||= []
# The block returns the number of parameters taken.
num_params_taken = 0
unless params.nil?
if SINGLE_ARG_TYPES.include?(@specs[sym][:type])
given_args[sym][:params] << params[0, 1] # take the first parameter
num_params_taken = 1
elsif MULTI_ARG_TYPES.include?(@specs[sym][:type])
given_args[sym][:params] << params # take all the parameters
num_params_taken = params.size
end
end
num_params_taken
end
if handle_help_and_version
## check for version and help args
raise VersionNeeded if given_args.include? :version
raise HelpNeeded if given_args.include? :help
end
## check constraint satisfaction
@constraints.each do |type, syms|
constraint_sym = syms.find { |sym| given_args[sym] }
next unless constraint_sym
case type
when :depends
syms.each { |sym| raise CommandlineError, _("--%{value0} requires --%{value1}") % { value0: @specs[constraint_sym][:long], value1: @specs[sym][:long] } unless given_args.include? sym }
when :conflicts
syms.each { |sym| raise CommandlineError, _("--%{value0} conflicts with --%{value1}") % { value0: @specs[constraint_sym][:long], value1: @specs[sym][:long] } if given_args.include?(sym) && (sym != constraint_sym) }
end
end
required.each do |sym, _val|
raise CommandlineError, _("option --%{opt} must be specified") % { opt: @specs[sym][:long] } unless given_args.include? sym
end
## parse parameters
given_args.each do |sym, given_data|
arg = given_data[:arg]
params = given_data[:params]
opts = @specs[sym]
raise CommandlineError, _("option '%{arg}' needs a parameter") % { arg: arg } if params.empty? && opts[:type] != :flag
vals["#{sym}_given".intern] = true # mark argument as specified on the commandline
case opts[:type]
when :flag
if arg =~ /^--no-/ and sym.to_s =~ /^--\[no-\]/
vals[sym] = opts[:default]
else
vals[sym] = !opts[:default]
end
when :int, :ints
vals[sym] = params.map { |pg| pg.map { |p| parse_integer_parameter p, arg } }
when :float, :floats
vals[sym] = params.map { |pg| pg.map { |p| parse_float_parameter p, arg } }
when :string, :strings
vals[sym] = params.map { |pg| pg.map(&:to_s) }
when :io, :ios
vals[sym] = params.map { |pg| pg.map { |p| parse_io_parameter p, arg } }
when :date, :dates
vals[sym] = params.map { |pg| pg.map { |p| parse_date_parameter p, arg } }
end
if SINGLE_ARG_TYPES.include?(opts[:type])
if opts[:multi] # multiple options, each with a single parameter
vals[sym] = vals[sym].map { |p| p[0] }
else # single parameter
vals[sym] = vals[sym][0][0]
end
elsif MULTI_ARG_TYPES.include?(opts[:type]) && !opts[:multi]
vals[sym] = vals[sym][0] # single option, with multiple parameters
end
# else: multiple options, with multiple parameters
opts[:callback].call(vals[sym]) if opts.has_key?(:callback)
end
## modify input in place with only those
## arguments we didn't process
cmdline.clear
@leftovers.each { |l| cmdline << l }
## allow openstruct-style accessors
class << vals
def method_missing(m, *args)
self[m] || self[m.to_s]
end
end
vals
end
#parse_date_parameter(param, arg) ⇒ Object
:nodoc:
455
456
457
458
459
460
461
462
463
464
# File 'lib/puppet/util/command_line/trollop.rb', line 455
def parse_date_parameter param, arg # :nodoc:
begin
time = Chronic.parse(param)
rescue NameError
# chronic is not available
end
time ? Date.new(time.year, time.month, time.day) : Date.parse(param)
rescue ArgumentError => e
raise CommandlineError, _("option '%{arg}' needs a date") % { arg: arg }, e.backtrace
end
#stop_on(*words) ⇒ Object
Defines a set of words which cause parsing to terminate when encountered, such that any options to the left of the word are parsed as usual, and options to the right of the word are left intact.
A typical use case would be for subcommand support, where these would be set to the list of subcommands. A subsequent Trollop invocation would then be used to parse subcommand options, after shifting the subcommand off of ARGV.
296
297
298
# File 'lib/puppet/util/command_line/trollop.rb', line 296
def stop_on *words
@stop_words = [*words].flatten
end
#stop_on_unknownObject
Similar to #stop_on, but stops on any unknown word when encountered (unless it is a parameter for an argument). This is useful for cases where you don’t know the set of subcommands ahead of time, i.e., without first parsing the global options.
304
305
306
# File 'lib/puppet/util/command_line/trollop.rb', line 304
def stop_on_unknown
@stop_on_unknown = true
end
#version(s = nil) ⇒ Object
Sets the version string. If set, the user can request the version on the commandline. Should probably be of the form “<program name> <version number>”.
266
# File 'lib/puppet/util/command_line/trollop.rb', line 266
def version s = nil; @version = s if s; @version end
#widthObject
:nodoc:
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/puppet/util/command_line/trollop.rb', line 531
def width # :nodoc:
@width ||= if $stdout.tty?
begin
require 'curses'
Curses.init_screen
x = Curses.cols
Curses.close_screen
x
rescue Exception
80
end
else
80
end
end
#wrap(str, opts = {}) ⇒ Object
:nodoc:
547
548
549
550
551
552
553
# File 'lib/puppet/util/command_line/trollop.rb', line 547
def wrap str, opts = {} # :nodoc:
if str == ""
[""]
else
str.split("\n").map { |s| wrap_line s, opts }.flatten
end
end
|
__label__pos
| 0.882177 |
[contents] [checklist]
W3C
HTML Techniques for WCAG 2.0
W3C Working Draft 30 June 2005
This version:
http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-HTML-TECHS-20050630/
Latest version:
http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-HTML-TECHS/
Previous version:
http://www.w3.org/WAI/GL/WCAG20/WD-WCAG20-HTML-TECHS-20050211/
Editors:
Michael Cooper, Watchfire
Wendy Chisholm, W3C
Abstract
Editorial Note: The structure and presentation of the techniques documents will likely change as the WCAG WG determines the relationships between Guidelines, Techniques, and testing documents.
This document provides information to Web content developers who wish to satisfy the success criteria of "Web Content Accessibility Guidelines 2.0" [WCAG20] (currently a W3C Working Draft). The techniques in this document are specific to Hypertext Markup Language content [HTML4], [XHTML1] although some techniques contain Cascading Style Sheet [CSS1] and ECMAScript solutions. Use of the illustrative techniques provided in this document may make it more likely for Web content to demonstrate conformance to WCAG 2.0 success criteria (by passing the relevant tests in the WCAG 2.0 test suite - to be developed) than if these illustrative techniques are not used.
There may be other techniques besides those provided in this document that may be used to demonstrate conformance to WCAG 2.0; in that case, it is encouraged to submit those techniques to the WCAG WG for consideration for inclusion in this document, so that the set of techniques maintained by the WCAG WG is as comprehensive as possible. Deprecated examples illustrate techniques that the Working Group no longer recommends, but may be applicable in some cases.
Note: WCAG 2.0 is a Working Draft and the cross-references between success criteria and techniques are not fully established.
This document is part of a series of documents published by the W3C Web Accessibility Initiative (WAI) to support WCAG 2.0.
Editorial Note: As work on the technology-specific techniques documents and checklists progresses, we expect to clearly distinguish between techniques required for conformance versus those that are optional. That distinction is not made in this Working Draft. The issue is captured as Issue #772 -"How do we make it clear that there are some techniques that are sufficient and some that are optional?"
Status of this Document
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.
Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.
This document is prepared by the Web Content Accessibility Guidelines Working Group (WCAG WG) to show how HTML Techniques for WCAG 2.0 might read. This draft is not yet based on consensus of the WCAG Working Group nor has it gone through W3C process. This Working Draft in no way supersedes HTML Techniques for WCAG 1.0 published as a W3C Note September 2000. The WCAG WG intends to publish this as a Working Group Note at the same time or soon after WCAG 2.0 becomes a Recommendation.
This version of HTML techniques has not been significantly altered since the last publication. The Working Group has been investigating a number of issues but has not achieved resolution in time to implement changes to this document. This publication is primarily intended to parallel the publication of a new draft of WCAG 2.0. References to guidelines have been updated to reflect the major changes that have been made to that document.
Please refer to Issue tracking for WCAG 2.0 Techniques for HTML/XHTML for a list of open issues related to this Working Draft. The History of Changes to HTML Techniques for WCAG 2.0 Working Drafts is also available.
The Working Group welcomes comments on this document at [email protected]. The archives for the public comments list are publicly available.
This document has been produced as part of the W3C Web Accessibility Initiative (WAI). The goals of the WCAG WG are discussed in the Working Group charter. The WCAG WG is part of the WAI Technical Activity.
Table of Contents
Appendix
Introduction
This is the HTML Techniques for Web Content Accessibility Guidelines 2.0 (WCAG 2.0). The guidelines provide a generic description of the requirements for a Web site that is accessible to people with disabilities. The HTML techniques provide an interpretation of the guidelines as applied to HTML and XHTML. This interpretation represents the best thinking of the Web Content Accessibility Guidelines working group and as such is a good guide to achieve conformance to WCAG 2.0. The Working Group encourages authors to implement these techniques where appropriate. Additionally the Working Group strongly encourages manufacturers of authoring tools to support the process of authoring content that conforms to these techniques, and encourages manufacturers or user agents, including assistive technologies, to implement the behaviors described by these techniques. However, these techniques do not provide a final definition of WCAG conformance and it is possible to meet guideline requirements without following these techniques. As new methods of conforming to the guidelines come to the attention of the Working Group, these techniques will be updated.
These techniques are intended for use both with HTML 4.01 and with XHTML 1.0/1.1. To encourage migration to newer technologies, examples for techniques are XHTML unless there is a specific reason to present an HTML example. Some references have not yet been updated to point preferentially to XHTML. This will be adjusted in a future draft of this document.
Note: Techniques in this document are known to contain errors. Recommendations will be rendered obsolete by future drafts. The purpose of this document is to receive feedback about the content of the techniques to ensure that future drafts are more accurate and useful. These techniques should not be implemented by people attempting to attain WCAG conformance at this time.
Future Work
User agent support information is not included in this draft. In future drafts, the WCAG WG intends to provide this information to help authors decide which techniques to implement. Providing this information requires extensive user agent and assistive technology testing. The WCAG WG welcomes submissions of test result information that demonstrates user agent or assistive technology support (or lack of support) of existing techniques. Submissions of additional techniques are also welcome.
As work on the technology-specific checklists progresses, we expect to clearly distinguish between techniques required for conformance versus those that are optional. That distinction is not made in this Working Draft. The issue is captured as Issue #772 -"How do we make it clear that there are some techniques that are sufficient and some that are optional?"
Techniques need to identify how they should be applied in various baselines as discussed in the question of baseline. It is proposed that a set of baselines will be described and each technique indicate whether it is sufficient, optional, or not recommended in that baseline.
1. Metadata
This section discusses how to use metadata to increase the accessibility of Web content. Metadata is information about the content rather than the content itself. For example, the author, the creation date, expiration date, or primary language of the document. Metadata can be used by search engines to help users find content that has been made accessible or it can be used by the user agent (browser) to render the presentation in a way that fits the user's needs.
For more general information about Metadata refer to:
Editorial Note: The WCAG WG anticipates that a separate techniques document will focus on metadata, semantic web issues, and RDF and will be referenced from this section.
Test suite: Test files for Metadata
1.1 The !doctype statement
This technique relates to the following sections of the guidelines:
Task:
Use the !doctype statement to define the HTML or XHTML version of your document.
Validating to a published formal grammar and declaring that validation at the beginning of a document lets the user know that the structure of the document is sound. It also lets the user agent know where to look for semantics if it needs to. The W3C Validation Service validates documents against a whole list of published grammars.
It is preferable to validate to grammars that have been designed with accessibility in mind.
Example:
This is an example defining an English-language document as using the HTML 4.01 Transitional DTD.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
...
</head>
<body>
...
</body>
</html>
1.2 The title element
This technique relates to the following sections of the guidelines:
Task:
Use the title element to describe the document.
All documents, including individual frames in a frameset, should have a title element that defines in a simple phrase the purpose of the document. This helps users to orient themselves within the site quickly without having to search for orientation information in the body of the page.
Note that the (mandatory) title element, which only appears once in a document, is different from the title attribute, which may be applied to almost every HTML 4.01 element.
Example:
This example defines a document's title.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>The World Wide Web Consortium</title>
</head>
<body>
...
</body>
</html>
1.3 The address element
This technique relates to the following sections of the guidelines:
Task:
Use the address element to define a page's author.
Editorial Note: Describe how to use address to indicate contact information on the Web page.
Editorial Note: Question whether there is a particular accessibility benefit to this. If not, we should remove.
Editorial Note: Link to General technique about semantic markup.
Example:
This element can be used to provide information about the creator of the page.
<address>
This document was written by
<a href="mailto:[email protected]">Your Name</a>
</address>
This technique relates to the following sections of the guidelines:
Provide a reference to a glossary.
If your page uses terms that are defined in a glossary document, use link rel = "glossary" to reference the glossary of terms used on the page. This enables users to access the glossary quickly using user agent features.
Resources:
2. Navigational Supports
Test suite: Test files for Navigation
2.1 Meta redirect
This technique relates to the following sections of the guidelines:
Task:
Do not create a timed redirect.
meta http-equiv of "{timeout}; url=... " is often used to automatically redirect users. The meta element should be used to specify metadata for a document such as keywords and information about the author.
Editorial Note: MC: I think we should clearly separate out the "surprise" problem from the misuse of meta problem, which isn't actually a violation.
It is acceptable to use the meta element to create a redirect when the timeout is set to zero. However, it is preferable to use server-side methods to accomplish this.
Editorial Note: Refer to HTTP techniques here.
Deprecated Example:
This is a deprecated example which, using the meta element, forwards the user from one page to another after a timeout. However, this markup is non-standard, it disorients users, and it can disrupt a browser's history of visited pages.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Don't use this!</title>
<meta http-equiv="refresh"
content="5; url=http://www.example.com/newpage" />
</head>
<body>
<p>
If your browser supports Refresh, you'll be
transported to our
<a href="http://www.example.com/newpage">new site</a>
in 5 seconds, otherwise, select the link manually.
</p>
</body>
</html>
Example:
The meta element is used here to create an immediate redirect. Similar effects can be achieved using server-side techniques and are recommended over the use of the meta element.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Meta Redirect Example</title>
<meta http-equiv="refresh" content="0; url=http://www.example.com/newpage" />
</head>
<body>
<p>Please view our <a href="http://www.example.com/newpage">new site</a>.</p>
</body>
</html>
Example:
Editorial Note: Are there any examples we can use that are not deprecated? .htaccess is a server-side technique, perhaps point to that (after a server-side techniques document exists)
To be completed.
2.2 Meta refresh
This technique relates to the following sections of the guidelines:
Task:
Do not cause a page to refresh automatically.
meta http-equiv of "refresh" is often used to periodically refresh pages. If the time interval is too short, people who are blind will not have enough time to make their screen readers read the page before the page refreshes unexpectedly and causes the screen reader to begin reading at the top.
Deprecated Example:
This is a deprecated example that changes the user's page at regular intervals. Content developers should not use this technique to simulate "push" technology. Developers cannot predict how much time a user will require to read a page; premature refresh can disorient users. Content developers should avoid periodic refresh and allow users to choose when they want the latest information.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML Techniques for WCAG 2.0</title>
<meta http-equiv="refresh" content="60" />
</head>
<body>
...
</body>
</html>
Resources:
2.3 Site map
This technique relates to the following sections of the guidelines:
Task:
Provide a site map and a description of accessibility features of the site.
Site maps can help all users find a page more readily when they already have a general idea of what they are looking for. If your site is highly visual in nature, the structure might be harder to navigate if the user can't form a mental map of where they are going or where they have been. The site map will help users discover the navigation mechanisms you have provided. Site maps are often presented as outlines, composed of nested lists, showing the hierarchy of pages. It may help to provide a summary of the contents of each page in the outline.
Resources:
This technique relates to the following sections of the guidelines:
Task:
For collections of documents, use the link element to identify each document's position in the collection.
The link element in the head, used with the rel attribute, can provide metadata about the position of an HTML page within a collection of documents. The value of rel indicates what type of relation is being described, and the href provides a link to the document having that relation. Multiple link elements can provide multiple relationships. Several values of rel are useful:
• Start: Refers to the first document in a collection of documents.
• Next: Refers to the next document in a linear sequence of documents.
• Prev: Refers to the previous document in an ordered series of documents.
• Contents: Refers to a document serving as a table of contents.
• Index: Refers to a document providing an index for the current document.
3. Headings
Test suite: Test files for Headings
3.1 Section headings
This technique relates to the following sections of the guidelines:
Task:
Use HTML header elements h1 through h6 to define the structure of the document.
Since some users skim through a document by navigating its headings, it is important to use them appropriately to convey document structure. Users should order heading elements properly. For example, in HTML, h2 elements should follow h1 elements, h3 elements should follow h2 elements, etc. Content developers should not "skip" levels (e.g., h1 directly to h3).
Long documents are often divided into a variety of chapters, chapters have subtopics and subtopics are divided into various sections, sections into paragraphs, etc. These semantic chunks of information make up the structure of the document.
Sections should be introduced with the HTML heading elements (hx). Other markup may complement these elements to improve presentation (e.g., the hr element to create a horizontal dividing line), but visual presentation is not sufficient to identify document sections.
Editorial Note: Edit this section to clarify "semantic chunks," "other markup," "introducing sections," "navigating its headings," etc.
Editorial Note: There has been some discussion about requiring h1 to be the first header on a page. It seems undesirable to restrict the use of header elements so far but some people support strengthening the semantics of headers. This will need further discussion.
Some authors object to using the HTML header elements because the default presentation in many browsers is unattractive. The appropriate solution is to use CSS to achieve the desired visual effect. Combined with classes and ids, a variety of presentational styles can be achieved while retaining a logical outline in the semantic structure. See CSS fonts for more information.
Editorial Note: Link to General technique about semantic markup.
Example:
Note that in HTML, heading elements (H1 - H6) only start sections, they don't contain them as element content. This HTML markup shows how style sheets may be used to control the appearance of a heading and the content that follows:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Cooking techniques</title>
<style type="text/css">
/* Indent heading and following content */
div.section2 { margin-left: 5% }
</style>
</head>
<body>
<h1>Cooking techniques</h1>
<p>
... some text here ...
</p>
<div class="section2">
<h2>Cooking with oil</h2>
... text of the section ...
</div>
<div class="section2">
<h2>Cooking with butter</h2>
... text of the section ...
</div>
</body>
</html>
3.2 Header misuse
This technique relates to the following sections of the guidelines:
Task:
Do not user headers solely for visual effects.
Do not use headings to create font effects. Instead, use CSS to change font styles. See CSS fonts for more information.
Resources:
4. Language
This section explains how and why to mark changes in language as well as identifying the primary language used for content. Many assistive technologies handle a variety of languages. When the language is not identified, assistive technologies often make a best guess using the default language set by the user. This often results in confusing pronunciations or displays.
Editorial Note: Needs clarification. "handle languages" "default language set by user" "confusing pronunciations" Perhaps add some sound clips and transcripts of confusing pronunciations and displays.
Editorial Note: [#580] Note that RFC1766 has now been obsoleted by RFC3066
Test suite: Test files for Language
4.1 Identifying the primary language
This technique relates to the following sections of the guidelines:
Task:
Use the lang attribute of the html element to define the document's language.
It is good practice to identify the primary language of a document, either with markup (as shown in the example) or through HTTP headers. The lang attribute allows assistive technology to orient and adapt to the pronunciation and syntax that are specific to the language of the page. This attribute may also play a major role in the emerging global, multi-lingual, simultaneous translation web environment.
Editorial Note: Note the HTTP headers is not an HTML technique. But we should have some way of speaking to the effects of HTTP headers and the preference with respect to the lang attribute.
Example:
This example defines the content of an HTML document to be in the French language.
<html lang="fr" xmlns="http://www.w3.org/1999/xhtml">
<body>
...document écrit en français...
</body>
</html>
4.2 Identifying changes in language
This technique relates to the following sections of the guidelines:
Task:
Use the lang attribute to identify changes in the natural language.
If you use a number of different languages on a page, make sure that any changes in language are clearly identified by using the lang or xml:lang attribute according to the HTML or XHTML version you use.
Note that HTML only offers the use of the lang attribute, while XHTML (transitionally) allows both attributes or only xml:lang, respectively, since lang was removed in XHTML 1.1.
Identifying changes in language are important for a number of reasons:
• It will allow braille translation software to follow changes in language, e.g., substitute control codes for accented characters, and insert control codes necessary to prevent erroneous creation of Grade 2 braille contractions.
Editorial Note: We may want to put a glossary at the end of the document defining things like "Grade 2 braille contractions").
• Similarly, speech synthesizers that "support" multiple languages will be able to speak the text in the appropriate accent with proper pronunciation. If changes are not marked, the synthesizer will try its best to speak the words in the primary language it works in. Thus, the French word for car, "voiture" would be pronounced "voter" by a speech synthesizer that uses English as its primary language.
• Marking changes in language can benefit future developments in technology, for example users who are unable to translate between languages themselves will be able to use machines to translate unfamiliar languages.
Example:
This example uses the lang attribute of the span element to define one phrase as French and another as Italian.
<p>
And with a certain <span lang="fr">je ne sais
quoi</span>, she entered both the room, and his life,
forever. "My name is Natasha," she said.
"<span lang="it">Piacere,</span>" he
replied in impeccable Italian, locking the door.
</p>
Example:
This example demonstrates the use of the xml:lang attribute defining a quote written in German. This snippet could be included by an XHTML 1.1 document where lang is not allowed.
<blockquote xml:lang="de">
<p>Da dachte der Herr daran, ihn aus dem Futter zu schaffen,
aber der Esel merkte, daß kein guter Wind wehte, lief fort
und machte sich auf den Weg nach Bremen: dort, meinte er,
könnte er ja Stadtmusikant werden.</p>
</blockquote>
5. Text Markup
The techniques in this category demonstrate how to add structure to pieces of text. They refer to "inline" tags that allow control over the presentation of specific words and phrases in the document.
Test suite: Test files for Text Markup
5.1 Emphasis
This technique relates to the following sections of the guidelines:
Task:
Use the strong and em elements, rather than b and i, to denote emphasis.
The em and strong elements were designed to indicate structural emphasis that may be rendered in a variety of ways (font style changes, speech inflection changes, etc.). The b and i elements were deprecated in HTML 4.01 and XHTML because they were used to create a specific visual effect.
Editorial Note: Link to General technique about semantic markup.
Example:
This example shows how to use the em and strong elements to emphasize text.
...What she <em>really</em> meant to say was,
"This isn't ok, it is <strong>excellent</strong>!...
5.2 Abbreviations
This technique relates to the following sections of the guidelines:
Task:
Use the abbr element to expand abbreviations where they first occur.
Mark up abbreviations with abbr and use title to indicate the expansion.
Editorial Note: Issue 295 Where and when and how often to indicate the expansion is still under discussion.
This also applies to shortened phrases used as headings for table row or columns. If a heading is already abbreviated provide the expansion in abbr. If a heading is long, you may wish to provide an abbreviation as described in Terse substitutes for header labels (optional) .
Editorial Note: There are a number of questions about abbreviation and Acronym . Although these have undergone much discussion, there is not yet enough consensus to create solid techniques. These issues include: * uncertain whether these elements need to be marked up on the first occurrence on the page or for every instance, * unclear on the distinction between abbreviations and acronyms, in English and other languages, * the HTML Working group has proposed removing the acronym element in favor of a single abbreviation element for all cases, * how common must a word be before it need not be marked up this way.
Example:
This example shows how to use the abbr element properly.
<p>Welcome to the <abbr title="World Wide Web">WWW</abbr>!</p>
Example:
This example shows how to use the abbr attribute in a table heading.
<table>
<tr>
<th>First name</th>
<th abbr="SS#">Social Security Number</th>
</tr>
...
</table>
5.3 Acronym
This technique relates to the following sections of the guidelines:
Task:
Use the acronym element to expand acronyms where they first occur.
Mark up acronyms with acronym and use title to indicate the expansion.
Editorial Note: Issue 295 Where and when and how often to indicate the expansion is still under discussion.
Example:
This example shows how to use the acronym element.
<acronym title="Keep It Simple Stupid">KISS</acronym>
This technique relates to the following sections of the guidelines:
Do not create blinking content with the blink element.
Do not use the blink element. There are several reasons for this:
• Blinking content can provide accessibility problems.
• The blink element is not part of the HTML specification. Use CSS if you must have blinking content. Refer to the CSS Techniques for WCAG 2.0 Underlining, overlining, and blinking.
Resources:
5.5 Marquee
This technique relates to the following sections of the guidelines:
Task:
Do not create scrolling text with the marquee element.
Do not use the marquee element to create scrolling text. There are several reasons for this:
• Scrolling content can provide accessibility problems.
• The marquee element is not part of the HTML specification.
Editorial Note: Use script instead? If so, create and link to a technique in Client-side Scripting Techniques for WCAG 2.0.
Resources:
5.6 Short Quotations (future)
This technique relates to the following sections of the guidelines:
Task:
Use the q element to mark up short inline quotations.
The q element marks up inline quotations.
NOTE:The q element, though designed for semantic markup, is unsupported, or poorly-supported, in most browsers. So this is a future technique.
Editorial Note: Link to General technique about semantic markup.
5.7 Long quotations
This technique relates to the following sections of the guidelines:
Task:
Use the blockquote element to mark up block quotations.
The blockquote element marks up block quotations.
Editorial Note: Link to General technique about semantic markup.
Example:
This example marks up a longer quotation with blockquote:
<blockquote cite="http://www.example.com/loveslabourlost">
<p>
Remuneration! O! that's the Latin word for
three farthings. --- William Shakespeare
(Love's Labor Lost).
</p>
</blockquote>
5.8 Misuse of blockquote
This technique relates to the following sections of the guidelines:
Task:
Do not use the blockquote element for formatting effects such as indentation.
Only use blockquote to indicate a quotation. Do not use it to create an indented effect on the page. blockquote is a semantic element and using it improperly can confuse the user.
Editorial Note: We need to provide pointers to alternate ways to achieve the desired effect.
Resources:
5.9 Use of the title attribute
Task:
Use the title attribute where appropriate.
In general, one can provide supplementary information about elements using the title attribute. The attribute value contains the content. Refer to Conditional Content in the User Agent Accessibility Guidelines for information on how this information may be presented to the user.
Note that while the title attribute is permitted and can be used as supplemental content for most elements in HTML, there are some elements for which particular usages are recommended for accessibility purposes. Refer to:
There are also situations in which accessibility requirements are that title should not be used, even though it is permitted by HTML. Refer to:
Editorial Note: It is expected that the General Techniques will define what "supplementary information" is and how it should be used.
Editorial Note: Refer to Issue 229: we are uncertain about what user agent support is, or should be, for title. Resolution of that issue will impact the recommendations we make here.
5.10 Supplemental meaning cues
This technique relates to the following sections of the guidelines:
Task:
Use the span element with the title attribute to provide generic meaning cues.
Words that may have ambiguous meanings, because they are unfamiliar terms, idioms, contractions, or have multiple meanings can be clarified with the title attribute. If there is not a special element for the type of disambiguation to be performed, apply this to a span element.
5.11 CSS instead of presentational markup
This technique relates to the following sections of the guidelines:
Task:
Use structural markup instead of presentational markup, and use CSS for presentation.
Avoid using the following HTML elements, and use the appropriate CSS instead.
• b
• i
• tt
• big
• small
• strike
• s
• u
• font
• basefont
These elements are not prohibited, but it is recommended to either use other semantic elements or use CSS when feasible. Refer to discussion at Strongly emphasizing semantics.
Editorial Note: Include a list of each HTML element that should be replaced, and the CSS property/value(s) that can be used. Talk about structural markup a bit too, and/or cross reference.
5.12 Use non-deprecated presentational markup
This technique relates to the following sections of the guidelines:
Task:
If you must use HTML elements to control font information, use big and small, which are not deprecated.
Editorial Note: Placeholder.
5.13 Inline structural elements to identify citations, code fragments, deleted text, etc.
This technique relates to the following sections of the guidelines:
Task:
Use structural elements as needed.
The HTML 4.01 specification defines the following structural elements for miscellaneous markup needs:
cite
Contains a citation or a reference to other sources.
dfn
Indicates that this is the defining instance of the enclosed term.
code
Designates a fragment of computer code.
samp
Designates sample output from programs, scripts, etc.
kbd
Indicates text to be entered by the user.
var
Indicates an instance of a variable or program argument.
ins
Indicates text inserted into a document.
del
Indicates text deleted from a document.
Editorial Note: How often are these elements used? Are they supported by assistive technologies? The code element is used often in W3C documents, what about elsewhere? Should we keep this section? Perhaps keep it but make it clear it is for completeness and information?
Editorial Note: This is about several elements so perhaps should be split up. But it's really just a list of structural elements. Do we need that list in techniques? Can we point to some resource (e.g., HTML spec) in a single technique and say "use structural elements per the HTML spec"? Or do we have to list every possible structural element we want people to use - including the obvious ones like p?
Editorial Note: Link to General technique about semantic markup.
5.14 Color
This technique relates to the following sections of the guidelines:
Task:
Ensure that color contrast is sufficient.
Ensure that color contrasts sufficiently.
Note that it is preferred to use CSS for color, see CSS instead of presentational markup .
Editorial Note: Provide a list of HTML color attributes.
Resources:
5.15 Relative size
This technique relates to the following sections of the guidelines:
Task:
Use relative size instead of absolute.
Editorial Note: From Issue 1066: The issue of relative size (or scalable content) isn't dealt with yet in WCAG 2.0. In part it seems the belief is this should be a user agent issue, not an authoring issue. However, in reality it is currently also an authoring issue. Anyway Web Content guidelines should specify that content should be scalable regardless of whose responsibility it is to fulfill the guideline. Issue 1012 deals with CSS size, and the questions raised there also affect this issue. In particular, there is no home in the guidelines for this technique. Nevertheless the technique should exist in the next draft as a hook for discussion.
Resources:
6. Lists
The HTML list elements dl, ul, and ol should only be used to create lists. Do not use lists for formatting effects such as indentation. Refer to information on CSS and tables for layout in the CSS Techniques.
Until either CSS2 is widely supported or user agents allow users to control rendering of lists through other means, authors should consider providing contextual clues in unnumbered nested lists. Non-visual users may have difficulties knowing where a list begins and ends and where each list item starts. For example, if a list entry wraps to the next line on the screen, it may appear to be two separate items in the list. This may pose a problem for legacy screen readers.
Editorial Note: Do we still need this note? How is current support for nested lists? Which versions of which screen readers handle nested lists well?
Editorial Note: From 2003-07-30 teleconference: We need techniques for UL, OL, DL, examples that don't rely on CSS, and technique for older AT that don't support nested lists well
Test suite: Test files for Lists
6.1 Ordered lists
This technique relates to the following sections of the guidelines:
Task:
Format ordered lists so their items can be followed logically.
Ordered lists help non-visual users navigate. Non-visual users may "get lost" in lists, especially in nested lists and those that do not indicate the specific nest level for each list item. Until user agents provide a means to identify list context clearly (e.g., by supporting the ':before' pseudo-element in CSS2), content developers should include contextual clues in their lists.
For numbered lists, compound numbers are more informative than simple numbers. Thus, a list numbered
1
1.1
1.2
1.2.1
1.3
2
2.1
provides more context than the same list without compound numbers, which might be formatted as follows:
1.
1.
2.
1.
3.
2.
1.
and would be spoken as "1, 1, 2, 1, 2, 3, 2, 1", conveying no information about list depth.
[CSS1] and [CSS2] allow users to control number styles (for all lists, not just ordered) through user style sheets.
Editorial Note: As above, how well do current screen readers support nested lists? How well is the support for CSS control of list styles?
Example:
The CSS2 style sheet in this example shows how to specify compound numbers for nested lists created with either UL or OL elements. Items are numbered as "1", "1.1", "1.1.1", etc.
<style type="text/css">
li {
display: block;
}
li:before {
content: counters(item, ".");
counter-increment: item;
}
ul, ol {
counter-reset: item;
}
</style>
6.2 Abuse of list markup
This technique relates to the following sections of the guidelines:
Task:
Do not use list elements for presentational effects.
Do not use list elements, such as the ul and ol elements, to achieve indentation effects when a list is not indicated. The most common example of this misuse is to use list container elements without li children. li elements are sometimes used outside the context of list containers, which also presents an unclear semantic.
Editorial Note: We need to provide pointers to alternate ways to achieve the desired effect.
Resources:
7. Data Tables
This section discusses the accessibility of tables and elements that one can put in a table element.
Editorial Note: The resolution of issue 248 will effect this section. Include definition of "data table" here and "layout table" in the next section.
Editorial Note: Describe how to determine if a table is a data table or a layout table. Discuss why it is so important to mark up data tables correctly. Show bad example (e.g., Matt's W3N stock table) and the issues created by bad markup. Use real examples or create derivatives.
Tables should not be used to position elements graphically. Tables used in this way, known as "layout tables", do not observe the implication of tabular data inherent in the term "table", and can create particular accessibility problems as described in the section Layout Tables. Generally, display technologies such as [CSS2] can achieve the desired layout effect with improved accessibility.
Test suite: Test files for Data Tables
7.1 The caption element (optional)
This technique relates to the following sections of the guidelines:
Task:
Use the caption element to describe the nature of data tables.
Provide a caption via the caption element. A table caption describes the nature of the table in one to three sentences. Two examples:
1. "Cups of coffee consumed by each senator."
2. "Who spends the most on pollution cleanup?"
An optional method is to use the title attribute on the table element, but the caption is preferred because of the semantics of the element.
7.2 Summarizing data tables (optional)
This technique relates to the following sections of the guidelines:
Task:
Use the summary attribute to describe the purpose and structure of data tables.
It is rare to use both the caption element and the summary attribute since one or the other should be enough to provide a description.
Summaries are useful for non-visual readers. A summary may also describe how the table fits into the context of the current document. Two examples:
1. "This table charts the number of cups of coffee consumed by each senator, the type of coffee (decaf or regular), and whether taken with sugar."
2. "Total required by pollution control standards as of January 1, 1971. Commercial category includes stores, insurance companies and banks. The table is divided into two columns. The left-hand column is 'Total investment required in billions of dollars'. The right--hand column is 'Spending' and is divided into three sub-columns. The first sub-column is titled '1970 actual in millions of dollars', the second is '1971 planned in millions of dollars', and the third is 'Percent change, 1970 versus 1971.' The rows are industries." [NBA, 1996].
An optional method is to use the title attribute on the table element, but the summary attribute is preferred because of the semantics of the attribute.
Editorial Note: There is still not consensus about the ideal use of summaries for tables. A discussion about summaries began but there is still need for more review and comments on this. See also Summaries of layout tables .
7.3 Terse substitutes for header labels (optional)
Task:
Use the abbr attribute on th elements to provide terse substitutes for header labels.
When supported, short heading labels will decrease repetition and reading time when tables are read aloud.
7.4 Identifying groups of rows (optional)
This technique relates to the following sections of the guidelines:
Task:
Use thead to group repeated table headers, tfoot for repeated table footers, and tbody for other groups of rows.
Editorial Note: Describe the use and benefits of row structure elements. Clearly explain when it is a good idea to use these. Use Joe's example of tbody.
7.5 Identifying groups of columns (optional)
This technique relates to the following sections of the guidelines:
Task:
Use the colgroup and col elements to group columns.
Editorial Note: Describe the use and benefits of column structure elements. Much of this may be theoretical.
7.6 Specifying the set of data cells for which each header cell provides header information
This technique relates to the following sections of the guidelines:
Task:
Use the scope attribute to specify the set of data cells for which each header cell provides header information.
When browsers and assistive technologies know which headers apply to which data cells, the header information is available for each cell and can be displayed or read in association with the data.
Editorial Note: Need support information for scope, headers, and axis techniques. Provide information to help determine which technique (scope, headers, or axis) to use.
7.7 Associating header cells with data cells
This technique relates to the following sections of the guidelines:
Task:
Use the headers attribute on each data cell to associate a list of header cells that provide header information.
For more complicated tables (where the scope attribute can not be applied because the relationship applies to more than two headers), the headers attribute allows you to associate more than two headers with each data cell.
7.8 Categorizing data cells
This technique relates to the following sections of the guidelines:
Task:
Use the axis attribute to place a cell into a conceptual category.
Conceptual categories can be used to group data that might be similar but fall under different headings. For example, "meals" is a category that could be applied to numbers that fall under both the "San Jose" and "Seattle" headings.
Editorial Note: Andrew Kirkpatrick asks what specific accessibility benefits axis brings. Although testing shows assistive technology support for this, it is unclear how this brings equivalency to non-disabled people, since in fact people who are not using AT currently do not have access to the axis information. We need to know more about how axis is intended to be used in the general case, and how using it benefits accessibility.
7.9 Misuse of the pre element
This technique relates to the following sections of the guidelines:
Task:
Do not use the pre element to create tabular layout.
The pre element is not used to create tabular layout; the table elements is used. Watch out for pre markup within a table.
Editorial Note: Is using br a separate issue or included in the pre issue? Perhaps make this more general? i.e., use tables appropriately, don't use pre or br to format data?
7.10 Row and column headings
This technique relates to the following sections of the guidelines:
Task:
Use the th element to indicate which cells in data tables contain header information.
For information about table headers, refer to the table header algorithm and discussion in the HTML 4.01 Recommendation [HTML4], section 11.4.3
Example:
This example shows how to associate data cells (created with td) with their corresponding headers by means of the headers attribute. The headers attribute specifies a list of header cells (row and column labels) associated with the current data cell. This requires each header cell to have an id attribute.
A speech synthesizer might render this tables as follows:
Caption: Cups of coffee consumed by each senator Summary: This table charts the number of cups of coffee consumed by each senator, the type of coffee (decaf or regular), and whether taken with sugar. Name: T. Sexton, Cups: 10, Type: Espresso, Sugar: No Name: J. Dinnen, Cups: 5, Type: Decaf, Sugar: Yes
Editorial Note: Link to General technique about semantic markup.
<table border="1" summary="This table charts the number of
cups of coffee consumed by each senator, the type of coffee
(decaf or regular), and whether taken with sugar.">
<caption>Cups of coffee consumed by each senator</caption>
<tr>
<th id="header1">Name</th>
<th id="header2">Cups</th>
<th id="header3" abbr="Type">Type of Coffee</th>
<th id="header4">Sugar?</th>
</tr>
<tr>
<td headers="header1">T. Sexton</td>
<td headers="header2">10</td>
<td headers="header3">Espresso</td>
<td headers="header4">No</td>
</tr>
<tr>
<td headers="header1">J. Dinnen</td>
<td headers="header2">5</td>
<td headers="header3">Decaf</td>
<td headers="header4">Yes</td>
</tr>
</table>
Example:
This example associates the same header (th) and data (td) cells as the previous example, but this time uses the scope attribute rather than headers. scope must have one of the following values: "row", "col", "rowgroup", or "colgroup". Scope specifies the set of data cells to be associated with the current header cell. This method is particularly useful for simple tables. It should be noted that the spoken rendering of this table would be identical to that of the previous example. A choice between the headers and scope attributes is dependent on the complexity of the table. It does not affect the output so long as the relationships between header and data cells are made clear in the markup.
<table border="1" summary="This table charts ...">
<caption>Cups of coffee consumed by each senator</caption>
<tr>
<th scope="col">Name</th>
<th scope="col">Cups</th>
<th scope="col" abbr="Type">Type of Coffee</th>
<th scope="col">Sugar?</th>
</tr>
<tr>
<td>T. Sexton</td>
<td>10</td>
<td>Espresso</td>
<td>No</td>
</tr>
<tr>
<td>J. Dinnen</td>
<td>5</td>
<td>Decaf</td>
<td>Yes</td>
</tr>
</table>
Example:
This example shows how to create categories within a table using the axis attribute.
This table lists travel expenses at two locations: San Jose and Seattle, by date, and category (meals, hotels, and transport). The following image shows how a visual user agent might render it. [Description of travel table]
Travel Expense Report table as rendered by a visual user agent.
<table border="1">
<caption>Travel Expense Report</caption>
<tr>
<th></th>
<th id="header2" axis="expenses">Meals</th>
<th id="header3" axis="expenses">Hotels</th>
<th id="header4" axis="expenses">Transport</th>
<td>subtotals</td>
</tr>
<tr>
<th id="header6" axis="location">San Jose</th>
<th></th>
<th></th>
<th></th>
<td></td>
</tr>
<tr>
<td id="header7" axis="date">25-Aug-97</td>
<td headers="header6 header7 header2">37.74</td>
<td headers="header6 header7 header3">112.00</td>
<td headers="header6 header7 header4">45.00</td>
<td></td>
</tr>
<tr>
<td id="header8" axis="date">26-Aug-97</td>
<td headers="header6 header8 header2">27.28</td>
<td headers="header6 header8 header3">112.00</td>
<td headers="header6 header8 header4">45.00</td>
<td></td>
</tr>
<tr>
<td>subtotals</td>
<td>65.02</td>
<td>224.00</td>
<td>90.00</td>
<td>379.02</td>
</tr>
<tr>
<th id="header10" axis="location">Seattle</th>
<th></th>
<th></th>
<th></th>
<td></td>
</tr>
<tr>
<td id="header11" axis="date">27-Aug-97</td>
<td headers="header10 header11 header2">96.25</td>
<td headers="header10 header11 header3">109.00</td>
<td headers="header10 header11 header4">36.00</td>
<td></td>
</tr>
<tr>
<td id="header12" axis="date">28-Aug-97</td>
<td headers="header10 header12 header2">35.00</td>
<td headers="header10 header12 header3">109.00</td>
<td headers="header10 header12 header4">36.00</td>
<td></td>
</tr>
<tr>
<td>subtotals</td>
<td>131.25</td>
<td>218.00</td>
<td>72.00</td>
<td>421.25</td>
</tr>
<tr>
<th>Totals</th>
<td>196.27</td>
<td>442.00</td>
<td>162.00</td>
<td>800.27</td>
</tr>
</table>
8. Tables for layout
Editorial Note: Depending on the baseline discussion, this discussion of layout tables could move to the list of fallback/repair techniques.
Editorial Note: Refer to section (to be written) at beginning of "Data Tables" that provides information about deciding if a table is used for data or layout.
Tables should not be used to position elements graphically. Tables used in this way, known as "layout tables", do not observe the implication of tabular data inherent in the term "table", and can create particular accessibility problems as described in the techniques that follow. Generally, display technologies such as [CSS2] can achieve the desired layout effect with improved accessibility.
Editorial Note: Furthermore "layout tables" are not defined in the HTML specification. This interacts with Technique @@doctype and validating code.
However, when it is necessary to use a table for layout, the table must linearize in a readable order. When a table is linearized, the contents of the cells become a series of paragraphs (e.g., down the page) one after another. Cells should make sense when read in row order and should include structural elements (that create paragraphs, headings, lists, etc.) so the page makes sense after linearization.
Also, when using tables to create a layout, do not use structural markup to create visual formatting. For example, the TH (table header) element, is usually displayed visually as centered, and bold. If a cell is not actually a header for a row or column of data, use style sheets or formatting attributes of the element.
Test suite: Test files for Layout Tables
8.1 Layout tables (deprecated)
This technique relates to the following sections of the guidelines:
Task:
Avoid layout tables.
Authors should consider using style sheets for layout and positioning. This technique deprecates the use of layout tables. It is recommended that authors not use the table element for layout purposes unless the desired effect absolutely cannot be achieved using CSS.
8.2 Table structure in layout tables
This technique relates to the following sections of the guidelines:
Task:
Only use the td, table, and tr elements and the border, cellspacing, and cellpadding attributes in layout tables. Do not use th, tbody, caption, colgroup, tfoot, and thead in layout tables.
The th element is used to create header information for data cells. When the th element is used, user agents and assistive technologies might try to associate the contents of the cell with others in the same column or row. If a user knows the table is used for layout, they can use different navigation strategies to make sense of the table.
Editorial Note: The HTML 4.01 spec seems to preclude using the td element for anything except data. The HTML WG has said that tables are only for data (full stop). We need to solicit HTML WG feedback about this section.
Editorial Note: A discussion was started about what other elements are required, allowed, or forbidden in layout tables (excluding the HTML WG philosophy against layout tables) but further review and comment is needed. Note that in HTML 4 tbody is technically a required element for all tables.
8.3 Summaries of layout tables
This technique relates to the following sections of the guidelines:
Task:
If the summary is used on a layout tables, the value must be null (summary="").
Using a null summary is similar to a null alt-text; the author is indicating that the table is used for presentation purposes.
Editorial Note: There is still not consensus about the ideal use of summaries for tables. A discussion about summaries began but there is still need for more review and comments on this. See also Summarizing data tables (optional) .
8.4 Linear reading order of tables
This technique relates to the following sections of the guidelines:
Task:
Create a logical reading order of cells in layout tables.
Editorial Note: Instead of providing a linear text alternative, ensure that the table can be linearized.
Tables used to lay out pages where cell text wraps pose problems for older screen readers that do not interpret the source HTML or browsers that do not allow navigation of individual table cells. These screen readers will read across the page, reading sentences on the same row from different columns as one sentence.
For example, if a table is rendered like this on the screen:
There is a 30% chance of Classes at the University
rain showers this morning, of Wisconsin will resume
but they should stop before on September 3rd.
the weekend.
This might be read by a screen reader as:
There is a 30% chance of Classes at the University rain showers this morning, of Wisconsin will resume but they should stop before on September 3rd. the weekend.
Screen readers that read the source HTML will recognize the structure of each cell, but for older screen readers, content developers may minimize the risk of word wrapping by limiting the amount of text in each cell. Also, the longest chunks of text should all be in the last column (rightmost for left-to-right tables). This way, if they wrap, they will still be read coherently. Content developers should test tables for wrapping with a browser window dimension of "640x480".
Editorial Note: See issue 251 for internationalization issue (not much).
Since table markup is structural, and we suggest separating structure from presentation, we recommend using style sheets to create layout, alignment, and presentation effects. Thus, the two columns in the above example could have been created using style sheets. Please refer to the section on style sheets for more information.
It is usually very simple to linearize a table used to layout a page - simply strip the table markup from the table. There are several tools that do this, and it is becoming more common for screen readers and some browsers to linearize tables.
However, linearizing data tables requires a different strategy. Since data cells rely on the information provided by surrounding and header cells, the relationship information that is available visually needs to be translated into the linear table. See also 7. Data Tables .
For example, specify the column layout order. The natural language writing direction may affect column layout and thus the order of a linearized table. The dir attribute specifies column layout order (e.g., dir="rtl" specifies right-to-left layout).
Editorial Note: also the case for layout tables?
Editorial Note: Provide an example
Editorial Note: again, there are tools to help produce linearized versions of data tables. We will provide a link
This markup will also help browsers linearize tables (also called table "serialization"). A row-based linear version may be created by reading the row header, then preceding each cell with the cell's column header. Or, the linearization might be column-based. Future browsers and assistive technologies will be able to automatically translate tables into linear sequences or navigate a table cell by cell if data is labeled appropriately. The WAI Evaluation and Repair Tools Working Group maintains a list of tools some of which help authors determine if tables will linearize in a readable order. Refer to [WAI-ER].
9. Links
This section explains how to create hyperlinks that are compatible and comprehensible to users of assistive technologies.
Test suite: Test files for Links
9.1 Link Text
This technique relates to the following sections of the guidelines:
Task:
Provide useful link text.
Links in HTML should follow the guidance in General Techniques for WCAG 2.0 for good link text.
Editorial Note: These General techniques have not yet been incorporated into a public Working Draft.
Resources:
9.2 Supplement link text with the title attribute
This technique relates to the following sections of the guidelines:
Task:
Where appropriate, use the title attribute of the a element to clarify links.
Editorial Note: We're not sure how the title attribute should relate to the link text.
This technique relates to the following sections of the guidelines:
Use text alternatives for images which are used as links.
When an image is used as the content of a link, specify a text alternative for the image. The text alternative should describe the function of the link.
Example:
This example uses the alt attribute of the img element to describe a graphical link.
<a href="routes.html">
<img src="topo.gif" alt="Current routes at Boulders Climbing Gym" />
</a>
Example:
If you provide link text, use empty quotes as the alt attribute value of the img element. (e.g.: alt="") Note that this text will appear on the page next to the image.
Editorial Note: Need more clarification that this is null alt-text and not a space? Point to a section in images that describes null alt-text in more detail.
Editorial Note: Issue 226 asks what to do about the case where the image and text link serve the same function but are in separate table cells. Perhaps the answer is "don't do that" but we should figure it out.
<a href="routes.html">
<img src="topo.gif" alt="" />
Current routes at Boulders Climbing Gym
</a>
This technique relates to the following sections of the guidelines:
Combine adjacent image and text links that point to the same resource.
Many kinds of links have both a text and iconic link adjacent to each other. Often the text and the icon link are rendered in separate links, in part to create a slight visual separation from each other. Visually they appear to be the same link, but they are experienced by many people as two identical links and can be confusing. To avoid this, some authors omit alternative text from the image, but then there is a link with an unclear destination. The preferred method to address this is to put the text and image together in one link, and provide null alternative text on the image to eliminate duplication of text.
Editorial Note: Issue 226 We need to make a recommendation about what to do if a text and image link are adjacent to each other but in separate table cells.
Example:
An icon and text link are side by side. The alt text for the image is the same as the text link beside it, leading to a "stutter" effect as the link is read twice.
<a href="products.html">
<img src="icon.gif" alt="Products page" />
</a>
<a href="products.html">
Products page
</a>
Deprecated Example:
An icon and text link are side by side. In an attempt to remove the "stutter" the alt text for the image is null. However, now one of the links has an unknown destination, which is its own link text problem.
<a href="products.html">
<img src="icon.gif" alt="" />
</a>
<a href="products.html">
Products page
</a>
Example:
An icon and text are within the same link. The icon has null alt text and the text beside it describes the link.
<a href="products.html">
<img src="icon.gif" alt="" />
Products page
</a>
9.5 Link groups
This technique relates to the following sections of the guidelines:
Task:
Group links structurally and identify the group with the title attribute.
Group links via one of the following mechanisms (in descending order of preference):
• ul or ol
• div
• map
When links are grouped into logical sets (for example, in a navigation bar that appears on every page in a site) they should be marked up as a unit. Navigation bars are usually the first thing someone encounters on a page. People who are sighted are often able to ignore navigation parts and start reading the content of the page. Someone using a screen reader must first listen to the text of each link in the navigation bar before reading the interesting content. There are several ways to mark up content so that a user with a screen reader can jump over the navigation bar and avoid reading all of the links.
Although graphical menus and link groups are accessible when alt attributes are used, there are advantages to creating navigation menus that are completely text-based. Graphical text is not easily scalable. The size of graphical text cannot be increased easily by those who may need a larger font. Alternatively, text-based menus allow for relative font sizes to be used on menu links. Relative font sizes can be easily increased in most browsers without the use of assistive technology.
Editorial Note: The above paragraph outlines benefits for using text-based navigation. It may be appropriate to expand these ideas into an optional technique in a future draft.
9.6 tabindex to skip link groups (future)
This technique relates to the following sections of the guidelines:
Task:
Use the HTML 4.01 tabindex attribute to allow users to jump to an anchor after the set of navigation links. This attribute is not yet widely supported.
Editorial Note: This creates user agent problems, this technique needs to say don't do it.
9.7 Skipping link groups
This technique relates to the following sections of the guidelines:
Task:
Include a link that allows users to skip over grouped links.
If there are five or more navigation links and/or other content that comes before the main content of the page then the skip navigation technique should probably be used. If there are twenty links and other elements before the main content, one of these techniques definitely should be used. The link should be at or very near the top of the page; it is a link with a local target just before the beginning of the main content.
Editorial Note: Issue 241 describes user agent issues and workarounds for this.
Example:
In this example, the map element groups a set of links, the title attribute identifies it as a navigation bar, tabindex is set on an anchor following the group, and a link at the beginning of the group links to the anchor after the group. Also, note that the links are separated by non-link, printable characters (surrounded by spaces).
<map title="Navigation Bar">
<p>
[<a href="#how">Bypass navigation bar</a>]
[<a href="home.html">Home</a>]
[<a href="search.html">Search</a>]
[<a href="new.html">New and highlighted</a>]
[<a href="sitemap.html">Site map</a>]
</p>
</map>
<h1>
<a id="how" name="how" tabindex="1">How to use our site</a>
</h1>
<!-- content of page -->
9.8 Hide link groups
This technique relates to the following sections of the guidelines:
Task:
Provide a style sheet that allows users to hide the set of navigation links.
Some designers would prefer not to have the skip link visible to all users. There are several techniques used to hide the skip link.
• Use an image that otherwise needs no text alternative and place the link text as alt text on that image. When using the tab key the link text will be heard by a screen reader and without a screen reader the href can be observed in the status bar of IE. E.g., <a href="#main"><img src="spacer.gif" width="1" height="1" alt="Skip Navigation"></a>
• Use the same foreground and background colors on the link text (assume back text on white background in code example). When using the tab key the link text will be heard by a screen reader and without a screen reader the href can be observed in the status bar of IE. It may be useful to consider making the link visible when the mouse is moved over the link or the link receives focus with the tab key.
• Hide the skip link by positioning it off screen with CSS, e.g., a.skip {position: absolute; left: -1000em; width: 20em;}. When using the tab key the link text will be heard by a screen reader and without a screen reader the href can be observed in the status bar of IE.
Do not hide the skip link using the display property; either display:none or display:hidden. Screen readers will not speak text with display:none and sometimes will not speak text with display:hidden.
Resources:
9.9 Keyboard access
This technique relates to the following sections of the guidelines:
Task:
Use the accesskey attribute of navigational elements to allow rapid keyboard access.
Keyboard access to active elements of a page is important for many users who cannot use a pointing device. User agents may include features that allow users to bind keyboard strokes to certain actions. HTML 4.01 allows content developers to specify keyboard shortcuts in documents via the accesskey attribute.
Note: Until user agents provide an overview of which key bindings are available, provide information on the key bindings.
Editorial Note: The Protocols and Formats working group has suggested that the accesskey attribute needs to be re-engineered. Threads discussing this are at AccessKey Behavior based on media and Accesskey again.
Example:
In this example, if the user activates Alt + C (in most user agents), the link will be followed.
<a accesskey="C" href="doc.html">XYZ company home page</a>
Example:
This example assigns "U" as the accesskey (via accesskey). Typing the access key modifier plus the key, e.g., Alt + U, gives focus to the label, which in turn gives focus to the input control, so that the user can input text.
<form action="submit" method="post">
<p>
<label for="user" accesskey="U">name</label>
<input type="text" name="user" id="user" />
</p>
</form>
This technique relates to the following sections of the guidelines:
Do not cause pop-ups or other windows to appear and do not change the current window without informing the user.
Links created with the a and area elements can use the target attribute. This directs the result of following the link to a particular window or frame. Values of target other than "_self", "_parent", and "_top" generally cause a new window to open when the link is followed. Values of "_blank" and "_new" always create a new window.
Other values refer to a named window. In a frameset, this may be the name of a frame (identified by the name attribute of a frame element, in which case the named frame will load the document identified by the link. Although the target is a different frame, this is an acceptable use of target. But if a window does not exist with the name provided, a new window will open as if a value of "_blank" had been provided. This window will have that name attached to it and future links with the same value will be directed to that window. Although a new window is no longer created after the first link with that name is followed, the change of window may still be unexpected. This practice should therefore not be used unless the user is warned.
Example:
This example demonstrates two ways to inform users that a new window will be opened when the link is selected.
<a href="page2.html" target="_blank">
More detail (opens in a new window)
</a>
OR
<a href="page2.html" target="_blank">
More detail
<img src="newwindow.gif" alt="(opens in a new window)" />
</a>
9.11 Using frame targets (deprecated)
This technique relates to the following sections of the guidelines:
Task:
Do not cause pop-ups or other windows to appear and do not change the current window without informing the user.
Content developers should avoid specifying a new window as the target of a frame with target="_blank".
Editorial Note: This should be relaxed to fit current WCAG 2.0 thinking. i.e., "extreme changes in context are identified before they occur so the user can determine if they wish to proceed or so they can be prepared for the change" Thus, pop-ups are allowed as long as the user is notified before the pop-up appears. Also, more and more user agents may be configured to not display pop-ups or display them in the background, thus no change in context effects the user.
9.12 Opening new windows
This technique relates to the following sections of the guidelines:
Task:
Use the target attribute to open new windows, not scripts.
Resources:
This technique relates to the following sections of the guidelines:
Use the link element to describe the structure of your document.
Content developers should use the link element and link types (refer to [HTML4] section 6.12) to describe document navigation mechanisms and organization. This allows user agents to implement standardized navigation tools for your site, or allow ordered printing of a set of documents.
Editorial Note: It would be good to provide more information on the exact benefit here. Screen shots or something.
Example:
The following link elements might be included in the head of chapter 2 of a book:
Editorial Note: Include screen shots from iCab here.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="Next" href="chapter3.html" />
<link rel="Prev" href="chapter1.html" />
<link rel="Start" href="cover.html" />
<link rel="Glossary" href="glossary.html" />
<title>Chapter 2</title>
</head>
<body>
...
</body>
</html>
This technique relates to the following sections of the guidelines:
Use the link element to refer to accessible alternative documents.
The link element may be used to designate alternative documents. Browsers should load the alternative page automatically based on the user's browser type and preferences.
Example:
User agents that support link will load the alternative page for those users whose browsers may be identified as supporting "aural","braille", or "tty" rendering.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Welcome to the Virtual Mall!</title>
<link title="Text-only version" rel="alternate"
href="text_only.html" media="aural, braille, tty" />
</head>
<body>
...
</body>
</html>
10. Images
This section discusses accessibility of images (including simple animations such as GIF animations) and image maps.
For information about math represented as images, refer to the section on Markup and style sheets rather than images: the example of math .
Test suite: Test files for Images
10.1 Short text alternatives for img elements ("alt-text")
This technique relates to the following sections of the guidelines:
Task:
Use the alt attribute of the img element to provide a text alternative for images.
When using the img element, specify a short text alternative with the alt attribute. Note. The value of this attribute is referred to as "alt-text".
Example:
The image contains alt text that plays the same function on the page as the image. Note that it does not necessarily describe the visual characteristics of the image itself.
<img src="companylogo.gif" alt="Company Name">
10.2 Spacer images
This technique relates to the following sections of the guidelines:
Task:
Use null alternative text for decorative or spacer images.
If content developers cannot use style sheets and must use invisible or transparent images (e.g., with IMG) to lay out images on the page, they should use null alt text, alt="". This indicates to assistive technology that the image can be safely ignored.
Example:
Do not use or the text "spacer" as the text alternative for images.
my poem requires a big space<IMG src="10pttab.gif" alt="&nbsp;&nbsp;&nbsp;">here
<IMG src="spacer.gif" alt="spacer">
<IMG src="colorfulwheel.gif" alt="The wheel of fortune">
Resources:
10.3 Misuse of alternative text
This technique relates to the following sections of the guidelines:
Task:
Do not use alt for any purpose other than to provide a meaningful text alternative.
Alternative text is sometimes used to provide textual information that is not an appropriate text alternative of the image. Most often this is used to affect search engine results. This alt text can present major barriers to users of text views of the document.
10.4 Short text alternatives for object elements (future)
This technique relates to the following sections of the guidelines:
Task:
Use the body of the object element to provide a text alternative for image objects.
When using object, specify a text alternative in the body of the object element.
Editorial Note: There is the possibility that we may either replace this technique or provide a supplementary technique based on what Gez outlines in Object Paranoia.
User Agent Notes:
JAWS5.0
Doesn't present when embedded objects loaded by IE
Example:
The image object has content that provides a brief description of the function of the image.
<object data="companylogo.gif" type="image/gif">
Company Name
</object>
10.5 Non-explicit text alternatives for object
This technique relates to the following sections of the guidelines:
Task:
Provide text alternatives for object elements in the page.
In theory, it is best to associate text alternatives for the object element as in Short text alternatives for object elements (future) . User agent problems make this technique ineffective at this time.
Instead, provide text alternatives in the document body. This text should label or describe the content loaded by the object element. You may also link to an external description, similar to D links (deprecated) .
Resources:
• Test suite:
10.6 Long descriptions of images
This technique relates to the following sections of the guidelines:
Task:
For images using the img element, describe detailed information in a separate file, and use the longdesc attribute to direct users to that file.
When a short text alternative does not suffice to adequately convey the function or role of an image, provide additional information in a file designated by the longdesc attribute.
Editorial Note: Link to information that describes how to write descriptions, e.g., Excerpts from the NBA Tape Recording Manual, Third Edition.
Example:
This example directs users to a file called "2001sales.html" to describe the sales data for 2001.
Here are the contents of 2001sales.html:
In sales97.html:
A chart showing how sales in 1997 progressed. The chart is a bar-chart showing percentage increases in sales by month. Sales in January were up 10% from December 1996, sales in February dropped 3%, ..
<img src="97sales.gif" alt="Sales for 1997" longdesc="sales97.html">
10.7 Long description of objects
This technique relates to the following sections of the guidelines:
Task:
For images using the object element, describe detailed information in the body of the tag, providing links to other content where appropriate.
When using object, specify longer text alternative within the element's content.
Note that object content, unlike "alt text", can include markup. Thus, content developers can provide a link to additional information from within the OBJECT element.
Example:
This example presents a long description of the image inside the object element.
<object data="97sales.gif" type="image/gif">
Sales in 1997 were down subsequent to our
<a href="anticipated.html">anticipated purchase</a> ...
</object>
Example:
This example presents a link to a long description inside the object element.
<object data="97sales.gif" type="image/gif">
Chart of our Sales in 1997. A
<a href="desc.html">textual description</a>
is available.
</object>
This technique relates to the following sections of the guidelines:
Provide a visible description link for user agents that don't support longdesc.
For user agents that don't support longdesc, provide a description link as well next to the graphic.
Deprecated Example:
This example uses a descriptive link to provide a description link to the document sales.html.
<img src="97sales.gif" alt="Sales for 1997" longdesc="sales.html">
<a href="sales.html" title="Description of 1997 sales figures">[D]</a>
Resources:
10.9 Describe images without longdesc
This technique relates to the following sections of the guidelines:
Task:
Describe images in document text as needed.
Editorial Note: We hope to make this optional in the future, when support for longdesc improves, but right now felt it is useful.
10.10 ASCII art
This technique relates to the following sections of the guidelines:
Task:
Provide a means to skip over multi-line ASCII art.
Avoid ASCII art (character illustrations) and use real images instead since it is easier to supply a text alternative for images. However, if ASCII art must be used provide a link to jump over the ASCII art.
If the ASCII art is complex, ensure that the text alternative adequately describes it.
Example:
A link, placed before ASCII art, targets a named anchor after the ASCII art.
<a href="#post-art">skip over ASCII art</a>
<!-- ASCII art goes here -->
<a id="post-art" name="post-art">caption for ASCII art</a>
Example:
ASCII art may also be marked up as follows [skip over ASCII figure or consult a description of chart]:
<pre title="Plot of age and scores.">
% __ __ __ __ __ __ __ __ __ __ __ __ __ __
100 | * |
90 | * * |
80 | * * |
70 | @ * |
60 | @ * |
50 | * @ * |
40 | @ * |
30 | * @ @ @ * |
20 | |
10 | @ @ @ @ @ |
0 5 10 15 20 25 30 35 40 45 50 55 60 65 70
Age (years)
</pre>
Audio rendering of the example as read in a screen reader
Transcript:
% 100 star 90 star star 80 star star 70 at star 60 at star 50 star at star 40 at star 30 star at at at star 20 10 at at at at at 0 5 10 15 20 25 30 35 40 45 50 55 60 65 70 Age years
Resources:
10.11 Emoticons
Task:
Use emoticons and other ASCII symbols judiciously.
Another way to replace ASCII art is to use human language substitutes. For example, <wink>might substitute for a winking smiley: ;-). Or, the word "therefore" can replace arrows consisting of dashes and greater than signs (e.g., -->), and the word "great" for the uncommon abbreviation "gr8".
Editorial Note: The RDF / Server-side / transcoding techniques are expected to describe a way to convert emoticons into images with appropriate alt text. Reference that when ready.
Example:
Another option for smaller ascii art is to use an span element with title.
<span title="smiley in ASCII art">:-)</span>
10.12 Text in images
This technique relates to the following sections of the guidelines:
Task:
Use HTML-structured text plus CSS to achieve styled text, not text in images.
Present text as HTML rather than in a bitmap images. There are several reasons for this:
• Text is directly available to assistive technologies without requiring text alternatives
• Text can contain HTML structure elements
• Color contrast can be adjusted by the user
• Size can be adjusted by the user
Editorial Note: This should also map to resizing when that is added to guidelines.
Resources:
10.13 Background images
This technique relates to the following sections of the guidelines:
Task:
Do not use background images.
Do not use the background attribute to display a background image.
Resources:
11. Image Maps
An image map is an image that has "active regions". When the user selects one of the regions, some action takes place -- a link may be followed, information may be sent to a server, etc. To make an image map accessible, content developers must ensure that each action associated with a visual region may be activated without a pointing device.
Test suite: Test files for Image Maps
11.1 Use client side image map
This technique relates to the following sections of the guidelines:
Task:
Provide client-side image maps instead of server-side image maps except where the regions cannot be defined with an available geometric shape.
Image maps are created with the map element. HTML allows two types of image maps: client-side (the user's browser processes a URI) and server-side (the server processes click coordinates). For all image maps, content developers must supply a text alternative.
Content developers should create client-side image maps (with usemap) rather than server-side image maps (with ismap) because server-side image maps require a specific input device.
Editorial Note: We may want to combine this technique with the following, Text links for server side image maps. .
Resources:
This technique relates to the following sections of the guidelines:
Provide redundant text links for each active region of a server-side image map.
If server-side image maps must be used (e.g., because the geometry of a region cannot be represented with values of the shape attribute), authors must provide the same functionality or information in an alternative accessible format. One way to achieve this is to provide a textual link for each active region so that each link is navigable with the Keyboard access . If you must use a server-side image map, please consult the section on 11. Image Maps .
When a server-side image map must be used, content developers should provide an alternative list of image map choices. There are three techniques:
• Include the alternative links within the body of an object element (refer to the previous example illustrating links in the object element).
• If img is used to insert the image, provide an alternative list of links after it and indicate the existence and location of the alternative list (e.g., via that alt attribute).
• If other approaches don't make the image map accessible, create an alternative page that is accessible.
Example:
A server side image map with duplicate text links provided on the page.
<a href="http://www.example.com/cgi-bin/imagemap/my-map">
<img src="welcome.gif" alt="Welcome! (Text links follow)"
ismap="ismap" />
</a>
<p>
[<a href="reference.html">Reference</a>]
[<a href="media.html">Audio Visual Lab</a>]
</p>
This technique relates to the following sections of the guidelines:
Provide redundant text links for each active region of a client-side image map.
In addition to providing a text alternative for client side image map regions, provide redundant textual links. For each area, provide an a on the page with the same href and the same link text as the alt of the area. If the a element is used instead of area, the content developer may describe the active regions and provide redundant links at the same time.
Editorial Note: The last sentence describes a practices that works inconsistently if at all. See Roberto Scano's post. Should we remove it?
Editorial Note: In WCAG 1 this is an "until user agents" requirement. What should we do with it?
Resources:
11.4 Text alternatives for client-side image maps
This technique relates to the following sections of the guidelines:
Task:
Provide alternative text for the area element.
Provide text alternative for image maps since they convey visual information. As with other links, the link text should make sense when read out of context. Refer to the section on 9. Links for information on writing good link text. Users may also want keyboard shortcuts to access frequently followed links. Refer to Keyboard access .
If area is used to create the map, use the alt attribute.
Editorial Note: We need to adjust the above to match whatever we end up saying about clear link text, above.
Example:
This example uses the alt attribute of the area element to provide text alternatives of image map links.
<img src="welcome.gif" usemap="#map1"
alt="Image map of areas in the library" />
<map id="map1" name="map1">
<area shape="rect" coords="0,0,30,30"
href="reference.html" alt="Reference" />
<area shape="rect" coords="34,34,100,100"
href="media.html" alt="Audio visual lab" />
</map>
12. Programmatic objects and applets
The object element in HTML allows authors to embed programmatic code written in other languages, such as Java or Macromedia Flash. However, not all user agents are able to process these objects. Many users of assistive technologies are not able to access the content in programmatic objects. This section explains how to ensure that the content you provide is accessible to those users.
Test suite: Test files for programmatic objects and applets
12.1 Markup and style sheets rather than images: the example of math
This technique relates to the following sections of the guidelines:
Task:
Wherever possible, use markup rather than images to convey information.
Editorial Note: Does this section fit best here or with images or on its own? Perhaps pull bit about ascii art from images and combine with this into a separate section called "Markup and Style Sheets" ? or perhaps create a more general section in General Techniques that would discuss benefits of marking text as text rather than developing raster images.
Using markup (and style sheets) where possible rather than images (e.g., a mathematical equation, link text instead of image button) promotes accessibility for the following reasons:
• Text may be magnified or interpreted as speech or braille.
• Search engines can use text information.
As an example, consider these techniques for putting mathematics on the Web:
• Ensure that users know what variables represent, for example, in the equation "F = m * a", indicate that F= Force, m = mass, a = acceleration.
• For straightforward equations, use characters, as in "x + y = z"
• For more complex equations, mark them up with MathML [MATHML] or TeX. Note. MathML can be used to create very accessible documents but currently is not as widely supported or used as TeX.
• Provide a text description of the equation and, where possible, use character entity references to create the mathematical symbols. A text alternative must be provided if the equation is represented by one or more images.
TeX is commonly used to create technical papers that are converted to HTML for publication on the Web. However, converters tend to generate images, use deprecated markup, and use tables for layout. Consequently, content providers should:
1. Make the original TeX (or LaTeX) document available on the Web. There is a system called "AsTeR" [ASTER] that can create an auditory rendition of TeX and LaTeX documents. Note. These tools work primarily in the English environment and may not work so well with speech synthesizers whose primary language is not English.
2. Ensure that the HTML created by the conversion process is accessible. Provide a single description of the equation (rather than "alt" text on every generated image as there may be small images for bits and pieces of the equation).
Editorial Note: Link to General technique about semantic markup.
12.2 Programmatic object fallbacks
This technique relates to the following sections of the guidelines:
Task:
Ensure that pages are usable when programmatic objects are disabled.
Ensure that pages are usable when programmatic objects, such as applets, scripts, and plugins, do not operate.
Editorial Note: As a "technology not supported" technique this depends on the outcome of our discussion on baseline. This also should not in principle be needed if authors follow Direct accessibility of programmatic objects .
12.3 Alternative content for programmatic objects
This technique relates to the following sections of the guidelines:
Task:
Create text alternatives for programmatic objects that actually work.
Placeholder
Editorial Note: The problem with some of the following techniques for text alternatives is they don't actually help the user because of user agent issues. We may want to suggest additional approaches, such as using CSS to "force-render" the alt value or element content, using a title, providing a d-link type of link to a description of the object.
12.4 Text and non-text alternatives for object
This technique relates to the following sections of the guidelines:
Task:
Provide a text alternative inside the object element.
If object is used, provide a text alternative in the content of the element:
Example:
This example shows a text alternative for a Java applet using the object element.
<object classid="java:Press.class" width="500" height="500">
As temperature increases, the molecules in the balloon...
</object>
Example:
This example takes advantage of the fact the object elements may be nested to provide for alternative representations of information.
<object classid="java:Press.class" width="500" height="500">
<object data="Pressure.mpeg" type="video/mpeg">
<object data="Pressure.gif" type="image/gif">
As temperature increases, the molecules in the balloon...
</object>
</object>
</object>
12.5 Alternative content for applet
This technique relates to the following sections of the guidelines:
Task:
Provide alternative content inside the applet element.
If applet is used, provide a text alternative in the content of the element:
Example:
This example shows a text alternative for a Java applet using the applet element.
<applet code="Press.class" width="500" height="500">
As temperature increases, the molecules in the balloon...
</applet>
12.6 Alt text for applet
This technique relates to the following sections of the guidelines:
Task:
Use the alt attribute to label an applet.
Use the alt attribute to label an applet.
Example:
This example shows a text alternative for a Java applet using the applet element.
<applet alt="Balloon inflation example" code="Press.class" width="500" height="500">
</applet>
Resources:
12.7 Alternative content for embed
This technique relates to the following sections of the guidelines:
Task:
Provide alternative content for embed with noembed.
Provide alternative content for the embed element in a noembed element. The noembed is rendered only if the embed is not supported. While it can be positioned anywhere on the page, the best location is beside or as a child of embed.
Editorial Note: Is it true that noembed can go either beside or inside embed? Is there a preference?
Example:
noembed is provided beside an embed.
<embed src="moviename.swf" width="100" height="80"
pluginspage="http://example.com/shockwave/download/" />
<noembed>
<img alt="Still from Movie" src="moviename.gif"
width="100" height="80" />
</noembed>
12.8 Alt text for embed
This technique relates to the following sections of the guidelines:
Task:
Provide alt for embed.
Provide alternative content for the embed element in the alt attribute.
Example:
alt is provided for embed.
<embed src="moviename.swf" width="100" height="80"
pluginspage="http://example.com/shockwave/download/"
alt="Still from Movie" />
Resources:
12.9 Embedding multimedia objects
This technique relates to the following sections of the guidelines:
Task:
Use the embed element within the object element for backward compatibility.
Some objects, such as those requiring a plug-in, should also use the object element. However, for backward compatibility with Netscape browsers, use the proprietary embed element within the object element as follows:
For more information refer to [MACROMEDIA].
Deprecated Example:
This example demonstrates how to use embed with the object element to preserve backward compatibility.
<object classid="clsid:A12BCD3F-GH4I-56JK-xyz"
codebase="http://example.com/content.cab"
width="100" height="80">
<param name="Movie" value="moviename.swf" />
<embed src="moviename.swf" width="100" height="80"
pluginspage="http://example.com/shockwave/download/" />
<noembed>
<img alt="Still from Movie" src="moviename.gif"
width="100" height="80" />
</noembed>
</object>
12.10 Plugin viewers
This technique relates to the following sections of the guidelines:
Task:
Provide a link to download accessible plugin viewers
Plugin content, by definition, requires a browser plugin for it to be viewed. If the user has not encountered a particular content type before they may not have the appropriate plugin, or know where to get it. Provide a link to download an accessible plugin. It is important to link to an accessible plugin; an inaccessible plugin, while it may render content to average users, may not render content to users with disabilities. Also, it is necessary to actively use the accessibility features of the plugin to result in accessible content.
Note this requirement does not apply to applets and common image formats such as .gif and .jpeg, which are considered universally supported.
Resources:
13. CSS Techniques
This section includes techniques for CSS that are somewhat specific to HTML. It is unclear whether these techniques should remain as part of the HTML techniques or should become part of the CSS techniques. It is desirable to maintain a clean separation of technologies. But it may not be helpful to put these techniques in a general-purpose CSS document if they are too HTML-specific.
Test suite: Test files for CSS.
13.1 CSS styling
This technique relates to the following sections of the guidelines:
Task:
Use CSS, not HTML, to style documents.
General technique about using CSS instead of HTML elements to style documents.
Editorial Note: Link to General technique about semantic markup.
Resources:
14. Frames
For visually enabled users, frames may organize a page into different zones. For non-visual users, relationships between the content in frames (e.g., one frame has a table of contents, another the contents themselves) must be conveyed through other means.
Frames as implemented today (with the frameset, frame, and iframe elements) are problematic for several reasons:
• Without scripting, they tend to break the "previous page" functionality offered by browsers.
• It is impossible to refer to the "current state" of a frameset with a URI; once a frameset changes contents, the original URI no longer applies.
• Opening a frame in a new browser window can disorient users.
Test suite: Test files for Frames
14.1 Frame titles
This technique relates to the following sections of the guidelines:
Task:
Use the title attribute of the frame element.
Use the title attribute of the frame element to describe the contents of each frame. This provides a label for the frame so users can determine which frame to enter and explore in detail.
Note that the title attribute labels frames, and is different from the title element which labels documents. Both should be provided, since the first facilitates navigation among frames and the second clarifies your current location.
The title attribute is not interchangeable with the name attribute. The title labels the frame for users; the name labels it for scripting and window targeting. The name is not presented to the user, only the title is.
Example:
This example shows how to use the title attribute with frame.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>A simple frameset document</title>
</head>
<frameset cols="10%, 90%">
<frame src="nav.html" title="Navigation bar" />
<frame src="doc.html" title="Documents" />
<noframes>
<body>
<a href="lib.html" title="Library link">Select to
go to the electronic library</a>
</body>
</noframes>
</frameset>
</html>
14.2 Frame name
This technique relates to the following sections of the guidelines:
Task:
Provide a meaningful name to identify frames.
Provide a name for frames in addition to title. it is useful to have a name attribute that is at least meaningful to benefit technologies that do not support title, and a title attribute that takes advantage of the fact that you can have several words in it.
Resources:
14.3 Describing frame relationships (deprecated)
This technique relates to the following sections of the guidelines:
Task:
Using the longdesc attribute of the frame element, describe the purpose of frames and how frames relate to each other if it is not obvious by frame titles alone.
The use of longdesc (long description) in frames is not recommended because the longdesc attribute in frames is currently not well supported by user agents.
Editorial Note: Note that if the a frame's contents change, the text alternative will no longer apply. Also, links to descriptions of a frame should be provided along with other alternative content in the noframes element of a frameset.
Deprecated Example:
This example uses the longdesc attribute of the frame element to link to a document called "frameset-desc.html", which contains this copy:
#Navbar - this frame provides links to the major sections of the site: World News, National News, Local News, Technological News, and Entertainment News.
#Story - this frame displays the currently selected story.
#Index - this frame provides links to the day's headline stories within this section.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Today's news</title>
</head>
<frameset cols="10%,*,10%">
<frameset rows="20%,*">
<frame src="promo.html" name="promo"
title="promotions" />
<frame src="sitenavbar.html" name="navbar"
title="Sitewide navigation bar"
longdesc="frameset-desc.html#navbar" />
</frameset>
<frame src="story.html" name="story"
title="Selected story - main content"
longdesc="frameset-desc.html#story" />
<frameset rows="*,20%">
<frame src="headlines.html" name="index"
title="Index of other national headlines"
longdesc="frameset-desc.html#headlines" />
<frame src="ad.html" name="adspace"
title="Advertising" />
</frameset>
<noframes>
<body>
<p>
<a href="noframes.html">No frames version</a>
</p>
<p>
<a href="frameset-desc.html">Descriptions of
frames.</a>
</p>
</body>
</noframes>
</frameset>
</html>
14.4 Writing for browsers that do not support FRAME
This technique relates to the following sections of the guidelines:
Task:
Use the noframes element to support user agents that don't support frames.
Provide meaningful content in the noframes element. noframes follows the frameset and contains a body element.
Meaningful content can include a version of the entire content of the frames in the frameset, or it can consist of instructions and links for users to find the content. Often the links point to the frame documents, outside their frames context. noframes content must not consist of instructions for users to switch to a frames-capable browser.
Example:
In this example, the user will receive a link to table_of_contents.html, which would allow him or her to navigate through the site without using frames.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>This is top.html</title>
</head>
<frameset cols="50%, 50%" title="Our big document">
<frame src="main.html" title="Where the content is displayed" />
<frame src="table_of_contents.html" title="Table of Contents" />
<noframes>
<body>
<a href="table_of_contents.html">Table of
Contents.</a>
<!-- other navigational links that are available in main.html
are available here also. -->
</body>
</noframes>
</frameset>
</html>
14.5 Frame sources
This technique relates to the following sections of the guidelines:
Task:
Use only HTML documents as frame sources.
Content developers must provide text alternatives of frames so that their contents and the relationships between frames make sense. Note that as the contents of a frame change, so must change any description. This is not possible if an image or other object is inserted directly into a frame. Thus, content developers should always make the source (src) of a frame an HTML file. Images may be inserted into the HTML file and their text alternatives will evolve correctly.
Editorial Note: This is worded as if there are no exceptions. Isn't it possible to design an accessible frameset that uses non-html resources as the frame source?
Example:
This example shows a frameset linking to HTML documents.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>A correct frameset document</title>
</head>
<frameset cols="100%" title="Evolving frameset">
<frame name="goodframe" src="apples.html" title="Apples" />
</frameset>
<!-- In apples.html -->
<p><img src="apples.gif" alt="Apples" /></p>
</html>
Example:
This incorrect example links directly to an image. Note that if, for example, a link causes a new image to be inserted into the frame: the initial title of the frame ("Apples") will no longer match the current content of the frame ("Oranges").
<p>Visit a beautiful grove of
<a target="badframe" href="oranges.gif" title="Oranges">oranges</a>
</p>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>A bad frameset document</title>
</head>
<frameset cols="100%" title="Static frameset">
<frame name="badframe" src="apples.gif" title="Apples" />
</frameset>
</html>
Resources:
This technique relates to the following sections of the guidelines:
Links to frames that load inaccessible formats are sufficiently descriptive.
If the source of a frame is not accessible, provide a link to a description with the longdesc attribute of the frame element.
14.7 Alternative content for iframe
This technique relates to the following sections of the guidelines:
Task:
Provide accessible alternative content for the iframe element.
Provide alternative content for iframe by providing meaningful and accessible content between the start and end tags.
14.8 Longdesc for iframe
This technique relates to the following sections of the guidelines:
Task:
Don't use longdesc on iframe.
Editorial Note: We just want to say that while HTML permits longdesc, it isn't meaningful to provide.
Resources:
15. Forms
This section discusses the accessibility of forms and form controls that one can put in a form element.
Test suite: Test files for Forms
15.1 Explicit form labels
Task:
Use the label element to associate form elements with their labels.
For each form control, provide an explicit label in a label element. A label is attached to a specific form control through the use of the for attribute. The value of the for attribute must be the same as the value of the id attribute of the form control.
Reset and submit buttons (<input type="reset"/> or <input type="submit"/>), image buttons (<input type="img"/>), and script buttons (<button></button>) do not need explicit labels since they have labels implicitly associated via their value or alt attributes or via element content for button.
Example:
The following text field has the explicit label of "First name:". Note that the label for matches the id attribute. The id sometimes shares the same value as the name but both must be provided, and the id must be unique on the page.
<label for="firstname">First name:</label>
<input type="text" name="firstname" id="firstname" tabindex="1" />
15.2 Implicit labels for form controls (deprecated)
Task:
Do not use the label element implicitly.
According to the HTML 4.01 specification, the label element can be wrapped around both the form control and its label text to create an "implicit label", as in
<label>First name: <input type="text" name="firstname" /></label>
. In practice this is not supported by user agents and should not be used. Use explicit labels as described in Explicit form labels .
15.3 Label form controls with the title attribute
Task:
Use title to label form controls that can't be individually labeled.
Form controls that cannot have an individual label associated with the label element (see Explicit form labels ) can be labeled with the title attribute.
Editorial Note: This relates to bugs 243 and 273.
15.4 Grouping form controls
Task:
Use the fieldset and legend elements in HTML 4 to group form controls logically.
Content developers should group information where natural and appropriate. When form controls can be grouped into logical units, use the fieldset element and label those units with the legend element.
Editorial Note: Try to make this less subjective, i.e. replace "natural," "appropriate," and "logical units" with something more objective.
Radio button and checkbox groups that provide multiple value choices for a single field name should in particular be grouped this way. This indicates the relationship of the elements, separates them from other groups of radio buttons or checkboxes, and is consistent with form design conventions.
Example:
This example uses the fieldset element to group a user's personal information together, and labels that grouping with the legend element.
<form action="http://example.com/adduser" method="post">
<fieldset>
<legend>Personal information</legend>
<label for="firstname">First name:</label>
<input type="text" id="firstname" tabindex="1" />
<label for="lastname">Last name:</label>
<input type="text" id="lastname" tabindex="2" />
...more personal information...
</fieldset>
<fieldset>
<legend>Medical History</legend>
...medical history information...
</fieldset>
</form>
Example:
Use fieldset to group radio buttons and checkboxes.
to be completed
15.5 Grouping options of select elements
Task:
Use the optgroup to group options logically under the select element.
Content developers should group information where natural and appropriate. For long lists of menu selections (which may be difficult to track), content developers should group select items (defined by option) into a hierarchy using the optgroup element. Specifies a label for the group of options with the label attribute on optgroup.
Editorial Note: In practice, following this technique may create problems for some user agents. We need to provide user agent support information, and possibly mark this as a future technique.
Example:
This example uses the optgroup element to logically group several options (using the option element) into categories labeled "PortMaster 3", "PortMaster 2", and "IRX".
<form action="http://example.com/prog/someprog" method="post">
<select name="ComOS">
<optgroup label="PortMaster 3">
<option label="3.7.1" value="pm3_3.7.1">
PortMaster 3 with ComOS 3.7.1
</option>
<option label="3.7" value="pm3_3.7">
PortMaster 3 with ComOS 3.7
</option>
<option label="3.5" value="pm3_3.5">
PortMaster 3 with ComOS 3.5
</option>
</optgroup>
<optgroup label="PortMaster 2">
<option label="3.7" value="pm2_3.7">
PortMaster 2 with ComOS 3.7
</option>
<option label="3.5" value="pm2_3.5">
PortMaster 2 with ComOS 3.5
</option>
</optgroup>
<optgroup label="IRX">
<option label="3.7R" value="IRX_3.7R">
IRX with ComOS 3.7R
</option>
<option label="3.5R" value="IRX_3.5R">
IRX with ComOS 3.5R
</option>
</optgroup>
</select>
</form>
15.6 Tab order in forms
This technique relates to the following sections of the guidelines:
Task:
Create a logical tab order through links, form controls, and objects.
Editorial Note: Describe use of accesskey. Indicate whether links, form controls, and objects have their own "tabspaces" or whether they share a common one.
Editorial Note: It is often preferable to keep the default tab order than to create one according to this technique. We should speak to that, here or in General techniques.
Example:
In this example, we specify a tabbing order among elements (in order, "field2", "field1", "submit") with tabindex:
<form action="#" method="post">
<p>
<input tabindex="2" type="text" name="field1" />
<input tabindex="1" type="text" name="field2" />
<input tabindex="3" type="submit" name="submit" />
</p>
</form>
15.7 Text alternatives for submit buttons
Task:
Provide a text alternative for images used as "submit" buttons.
For image submit buttons, use the alt attribute of the input element to provide a functional label. This label should indicate the button's nature as a submit button, not attempt to describe the image. The label is especially important if there are multiple submit buttons on the page that each lead to different results.
The input element is used to create many kinds of form controls. Although the HTML DTD permits the alt attribute on all of these, it should be used only on image submit buttons. User agent support for this attribute on other types of form controls is not well defined, and other mechanisms should be used to label these controls.
Example:
This example uses the alt attribute of an image submit button to label it as a "submit" button.
<form action="http://example.com/prog/text-read" method="post">
<input type="image" name="submit" src="button.gif" alt="Submit" />
</form>
15.8 Tabular forms
Task:
Label tabular form elements with title when a unique form label is not possible.
See [#300]
Resources:
16. Script techniques
This is a placeholder for certain techniques that will need to appear in the script techniques and / or have a home in HTML techniques because of the tight relationship between script and HTML.
Test suite: Test files for Scripts
16.1 Text alternatives for scripts
This technique relates to the following sections of the guidelines:
Task:
Use noscript when using script.
Placeholder for noscript.
Editorial Note: It is unclear whether noscript should always be required, even if script failure does not present an accessibility problem, such as with most image rollovers. As a "technology not supported" technique this depends on the outcome of our discussion on baseline.
16.2 JavaScript URLs
This technique relates to the following sections of the guidelines:
Task:
Do not use the javascript URL protocol.
Links that use the Javascript protocol, e.g., <a href="javascript:dosomething();">Javascript link</a>, are unusable by browsers that do not support scripts, and it is not possible to provide fallbacks with this method.
Instead of using the javascript protocol in links, the link should target a page providing fallback functionality. Event handlers on the link provide the script functionality. Be sure to return false from the event handler to cancel the fallback action of following the link. Be sure to follow the guidance in Device dependent event handlers regarding the use of event handlers.
Deprecated Example:
The following link uses the javascript protocol and cannot be used by user agents that do not support scripts.
<script type="text/javascript">
<!--
function dosomething() {
...
return false;
}
// -->
</script>
<a href="javascript:dosomething()">Scripted link</a>
Example:
The following link refers to a fallback page with the href attribute, and uses an onclick event handler to activate scripts.
<script type="text/javascript">
<!--
function dosomething() {
...
return false;
}
// -->
</script>
<a href="fallback.html" onclick="dosomething(); return false;">Scripted link with fallback</a>
The event handler can also return false directly, e.g.,
<a href="fallback.html" onclick="return dosomething();">Scripted link with fallback</a>
Resources:
16.3 Scripted form submission
This technique relates to the following sections of the guidelines:
Task:
Do not require script support to submit forms
HTML forms are often submitted with scripts, e.g., by an event handler on the button element or a link. These forms can't be submitted when client-side scripting is not enabled. Forms should have a genuine submit button, either a standard submit button (<input type="submit" value="Submit" />) or an image submit button (<inut type="image" alt="Submit" />). Any scripting desired can still be triggered on event handlers of those buttons, or the onsubmit event handler for the form.
16.4 Keyboard shortcuts for directly accessible scripts
This technique relates to the following sections of the guidelines:
Task:
???
See [#257].
16.5 Device dependent event handlers
This technique relates to the following sections of the guidelines:
Task:
When device dependent event handlers are used, provide another device-dependent fallback.
Provide redundant input mechanisms (i.e., specify two handlers for the same element, both of which have the same code associated with them):
Device Handler Correspondences
Mouse handler Keyboard handler
onmousedown onkeydown
onmouseup onkeyup
onclick onkeypress
onmouseover onfocus
onmouseout onblur
Note that there is no keyboard equivalent to double-clicking (ondblclick) or mouse movement (onmousemove) in HTML 4.0. Avoid using these elements.
Editorial Note: Note that onclick is now effectively device independent (bug 490).
16.6 Abstract event handlers
This technique relates to the following sections of the guidelines:
Task:
Use abstract, not device-specific, event handlers.
Avoid device-dependent, particularly mouse-dependent, event handlers. Use logical event handlers such as onfocus, onactivate, etc. Provide fallbacks to keyboard or logical event handlers for mouse event handlers.
16.7 Auto submit combo boxes
This technique relates to the following sections of the guidelines:
Task:
Do not use auto submit combo boxes.
Select menus that open a new page with more than one option must use the submit button instead of triggering with the onchange event because they cannot be used with the keyboard.
If some design principle demands the use of onChange, a title attribute can clarify the issue, like this: title="Use alt down arrow to open a list of languages."
Editorial Note: See [#272] and Jim Thatcher's post on auto-submit combo boxes for more background content that we might want to incorporate here.
17. References
ASTER
For information about ASTER, an "Audio System For Technical Readings", consult T. V. Raman's home page .
CSS1
"Cascading Style Sheets, level 1," B. Bos, H. Wium Lie, eds., W3C Recommendation 17 Dec 1996, revised 11 Jan 1999. Available at http://www.w3.org/TR/REC-CSS1.
CSS2
"Cascading Style Sheets, level 2," B. Bos, H. Wium Lie, C. Lilley, and I. Jacobs, eds., W3C Recommendation 12 May 1998. Available at http://www.w3.org/TR/REC-CSS2.
HTML4
"HTML 4.01 Specification," D. Raggett, A. Le Hors, I. Jacobs, eds., W3C Recommendation 24 December 1999. Available at http://www.w3.org/TR/html401/
IBMJAVA
IBM Guidelines for Writing Accessible Applications Using 100% Pure Java are available from IBM Special Needs Systems.
JAVAACCESS
Information about Java Accessibility and Usability is available from the Trace Research and Development Center.
MACROMEDIA
Flash OBJECT and EMBED Tag Syntax from Macromedia.
MATHML
"Mathematical Markup Language 1.0", P. Ion and R. Miner, eds., W3C Recommendation 7 April 1998, revised 7 July 1999. Available at http://www.w3.org/TR/REC-MathML.
TRACE
The Trace Research and Development Center . Consult this site for a variety of information about accessibility, including a scrolling Java applet that may be frozen by the user .
WAI-ER
The Evaluation and Repair Tools Working Group
WCAG10-CSS-TECHNIQUES
"CSS Techniques for Web Content Accessibility Guidelines 1.0," W. Chisholm, G. Vanderheiden, and I. Jacobs, eds. W3C Note 6 November 2000. Available at: http://www.w3.org/TR/WCAG10-CSS-TECHS/.
WCAG20
"Web Content Accessibility Guidelines 2.0," B. Caldwell, W. Chisholm, J. White, and G. Vanderheiden, eds., W3C Working Draft 19 November 2004. This W3C Working Draft is available at http://www.w3.org/TR/2004/WD-WCAG20-20041119. The latest version of WCAG 2.0 is available at http://www.w3.org/TR/WCAG20/
XHTML1
"XHTML 1.0 The Extensible HyperText Markup Language (Second Edition)," S. Pemberton, et al., W3C Recommendation 26 January 2000, revised 1 August 2002. Available at: http://www.w3.org/TR/xhtml1/.
Appendix 1 Fallback Techniques
The following is a list of techniques that we feel should be included in the HTML Techniques for WCAG 2.0 for backward compatibility with WCAG 1.0. However, the techniques are no longer recommended in WCAG 2.0. It is not yet clear how these techniques should be incorporated into the WCAG 2.0 materials, so we are collecting them in an appendix for the time being.
This technique relates to the following sections of the guidelines:
Task:
Separate links with printable characters
Include non-link, printable characters (surrounded by spaces) between adjacent links.
Editorial Note: We are unsure whether to deprecate this technique, but we believe we should. Nevertheless the technique needs to appear to bridge from WCAG 1.0 Checkpoint 10.5.
2 Direct accessibility of programmatic objects
This technique relates to the following sections of the guidelines:
Task:
Make plugin content directly accessible.
Make programmatic elements such as scripts and applets directly accessible or compatible with assistive technologies.
Also ensure that programmatic objects do not cause:
• Flicker
• Color contrast issues
Editorial Note: This is transition support for WCAG 1.0 Checkpoint 8.1, WCAG 1.0 Checkpoint 7.1, and WCAG 1.0 Checkpoint 2.2. Really it just means "plugins have to follow guidelines too". It's important to note that plugin viewers have to follow UAAG for it to count.
Editorial Note: The technique should point to techniques documents or other resources for making common formats accessible, e.g., scripts, Java, Flash.
3 CSS fallback
This technique relates to the following sections of the guidelines:
Task:
Organize documents so they may be read without style sheets.
Include much of the content from CSS techniques for positioning.
Editorial Note: This technique needs to be present to transition from WCAG 1.0 Checkpoint 6.1. As a "technology not supported" technique it depends on the outcome of our discussion on baseline. In practicality, this is just another test for linearization, e.g., Linear reading order of tables and Guideline 2.4 L3 SC 1.
4 Label positioning
Task:
Ensure labels for form controls are properly positioned.
The label must immediately precede its control on the same line (allowing more than one control/label per line) or be in the line preceding the control (with only one label and one control per line).
Editorial Note: This techniques comes from WCAG 1.0 Checkpoint 10.2. It is unclear if we want to continue to require it or how it relates to other label techniques.
5 Place-holding characters in empty controls (deprecated)
Task:
Until user agents handle empty controls correctly, include default, place-holding characters in edit boxes and text areas.
Editorial Note: This is a negative technique, an example of something you shouldn't do. This technique corresponds to a WCAG 1.0 checkpoint. There is a proposal for an erratum that states the until user agents clause is met and this checkpoint (and thus technique) are no longer necessary.
Deprecated Example:
This example fills a textarea element with code so that legacy assistive technologies will recognize it.
<textarea name="yourname" rows="20" cols="80">
Please enter your name here.
</textarea>
|
__label__pos
| 0.78717 |
Geocoding
a point on a street level mapGeocoding is the process of assigning location to information. In the context of a Geographic Information System (GIS), it means assigning geographic point coordinates to a street address.
More generically, it can mean taking any data with textual descriptions of town, zip code, or country, for example, and making it mappable. Relating county data to the geographic boundaries describing counties is a form of geocoding, but geocoding usually implies mapping more specific location information, such as residential addresses.
Geocoding is important to public health tracking because it tells us where disease, select populations, environmental problems, or other health-related factors concentrate geographically.
Geocoding childhood lead poisoning data, for example, tells us what areas of the state have the highest rates of lead poisoning. Public health professionals at Maine CDC and its partners use addresses of lead poisoned children to identify specific neighborhoods in need of further resources to prevent lead poisoning.
Another example is mapping household well water tests in order to locate hotspots of arsenic, uranium, radon or other water contamination issues.
The most reliable reference source for geocoding in Maine is "E911", or Enhanced 911 data. These are geographic files of streets and addresses generated by each town to support 911 emergency services.
The Maine CDC Environmental Public Health Tracking Program funded an effort to create direct access to these data for the purpose of geocoding. Large lists of addresses can be processed efficiently by this service on behalf of Maine CDC employees, without the need for running or configuring complex GIS software.
The geocoding service is publicly available at Maine GeoLibrary.
In Maine, every town has a state-assigned 5-digit code called a "Geocode". This is neither a zipcode, nor is it related to the process of geocoding. Beware the difference between data that "has a Geocode" (a town code) and data that are geocoded (has point coordinates, in the form of latitude/longitude).
|
__label__pos
| 0.921812 |
14
\$\begingroup\$
According to Digital Design and Computer Architecture by Harris and Harris, there are several ways to implement a MIPS processor, including the following:
The single-cycle microarchitecture executes an entire instruction in one cycle. (...)
The multicycle microarchitecture executes instructions in a series of shorter cycles. (...)
The pipelined microarchitecture applies pipelining to the single-cycle microarchitecture.
Architectures are often classified as either RISC or CISC. From RISC vs. CISC:
RISC processors only use simple instructions that can be executed within one clock cycle.
Since MIPS is RISC architecture, I am a litte confused by the above definitions and wonder if there isn't some sort of contradiction between them. More specifically:
1. If a RISC instruction can be split into shorter cycles (Fetch, Decode, ...), how can we say that it only takes one clock cycle to execute the whole instruction? Doesn't it take one clock cycle to execute each of the steps?
2. Does it really take one clock cycle to execute one RISC instruction? What happens, for example, if a cache miss occurs and the processor has to wait for slow DRAM? Shouldn't this prolong the execution of the instruction by quite a bit?
3. What exactly is one instruction cycle? Is it the time that it takes for one instruction to finish (i.e. one/multiple clock cycles)?
4. How long does one CISC instruction take in clock/instruction cycles?
\$\endgroup\$
1
• 2
\$\begingroup\$ Usually not less than one :-). \$\endgroup\$ – Russell McMahon May 20 '15 at 2:15
22
\$\begingroup\$
The practical definitions of RISC and CISC are so muddied and blurred now they are almost meaningless. Now it is best to think of them as more about "philosophy", in the sense that a CISC architecture has a richer instruction set with more powerful individual instructions (e.g. DIV and the like) while a RISC instruction set is bare bones and fast, and leaves it to the compiler to implement complex operations. Even purportedly CISC instruction sets (like x86) are translated into internal instructions in both Intel and AMD chips and implemented more like RISC processors. To answer your questions:
1. The original academic RISC processors (and I think maybe the very first commercial versions) did indeed execute one instruction per cycle, including fetch and decode. This was possible because the datapaths were super clean because the operations of each stage were simple and well defined. (the tradeoff here is only very simple instructions can be implemented this way). Once it hit the real world things got blurred. Things like pipelining and superscalar architecture make a simple RISC/CISC dichotomy impossible.
2. The original RISC chips attempted to execute one instruction per cycle and they could if the data was available in the register file. Of course if the processor had to go to DRAM it would take a (lot) longer. RISC is about "attempting" to execute an instruction per cycle.
3. One instruction cycle is the time it takes between fetches.
4. In depends enormously on the instruction and the instruction set architecture. Even in a CISC architecture some instructions could execute very quickly (like a shift left or right for example). Some executed very slowly (10s of cycles or more). The VAX architecture (probably the pinnacle of the CISC philosophy) had instructions that were really complex. Incidentally, a CISC architecture is usually easier to program in assembly than a RISC architecture because it is almost like a high-level language!
\$\endgroup\$
1
• \$\begingroup\$ > in the sense that a CISC architecture has a richer instruction set. No, many risc have richer instructions than cisc \$\endgroup\$ – 陳 力 Feb 15 at 6:46
5
\$\begingroup\$
The short answer
1. The steps in decoding and executing the instruction are executed in parallel with the next step of the previous instruction. This technique is known as pipelining. See On RISC Processors below.
2. A single-issue RISC architecture will typically average slightly less than one instruction per cycle due to wait states and time taken for load/store operations that hit memory rather than just being register to register. Delay slots give you an architectural hook that may allow you to get some of this time back. See On RISC processors below.
3. An instruction cycle is the length of time needed to execute an instruction. This will vary with architecture and (in some cases) instructions. For example, most instructions on something like a MIPS R2000/3000 take one cycle. Instructions involving memory access (load/store, branch) take more than one cycle, although the delay slots mean you may be able execute something else (possibly just a NOP) in the delay slot. Non-pipelined architectures can have instruction cycles of several clock cycles, often varying with the addressing mode. See On RISC processors, Traditional CISC architecures and Hardwired Architectures below.
Multiple-issue designs can blur this concept somewhat by executing more than one instruction in parallel.
4. CISC processors can have instructions that take varying lengths of time. The exact number of clock cycles depends on the architecture and instructions. The varying number of clock cycles taken on CISC ISAs is one of the reasons they are hard to build into heavily pipelined architectures. See Traditional CISC architectures below.
The longer answer
For a single issue MIPS, SPARC or other CPU, all (for a first approximation) instructions issue in one cycle, although they can have something known as a 'delay slot.'
On RISC Processors
In this context, a single issue CPU is one where the CPU doesn't do any on-the-fly dependency analysis and parallel issuance of instructions in the way that modern CPUs do, i.e. they have just one execution unit that executes the instructions in the order they are read from memoty. More on this later.
Most older RISC processors are single-issue designs, and these types are still widely used in embedded systems. A 32-bit single-issue integer RISC core can be implemented in around 25,000-30,000 gates, so CPU cores of this type have very low power consumption and very small footprints. This makes them easy and cheap to integrate into SOC (system-on-chip) products.
RISC CPU designs are pipelined - processing the instruction is done in several stages, with each instruction being passed down the pipeline to the next stage every clock cycle. In most cases a single-issue pipelined CPU will execute something close to one instruction per clock cycle.
Some architectures have instructions like branching or load/store from memory where the additional cycle taken by the memory access is visible to the code.
For example, in a SPARC V7/V8 design the next instruction after a branch is actually executed before the branch itself takes place. Typically you would put a NOP into the slot after the branch but you could put another instruction into it if you could find something useful to do.
The MIPS R2000/R3000 architecture had a similar delay slot in the load/store instructions. If you loaded a value from memory, it would not actually appear in the register for another cycle. You could put a NOP in the slot or do something else if you could find something useful to do that was not dependent on the load operation you just issued.
If the memory was slower than the CPU, which was often the case, you might get additional wait states on memory accesses. Wait states freeze the CPU for one or more clock cycles until the memory access is completed. In practice, these wait states and extra time for memory accesses mean that single-issue CPU designs average slightly less than one instruction per clock cycle. Delay slots give you some possible opportunities to optimise code by executing some other instruction while a memory operation takes place.
Traditional CISC processors
CISC processors were designs that could have instructions taking varying lengths of time. Often they had more complex instructions implemented directly in hardware that would have to be done in software on a RISC CPU.
Most mainframe architectures and pretty much all PC designs up to the M68K and intel 386 were traditional microcoded CISC CPUs. These designs proved to be slower per-clock and used more gates than RISC CPUs.
Microcode
An example of a microcoded architecture (MOS 6502) can be seen in emulation here. The microcode can be seen at the top of the image.
Microcode controls data flows and actions activated within the CPU in order to execute instructions. By looping through the steps in the microcode you can activate the parts of a CPU, moving data through ALUs or carrying out other steps. Re-usable components in the CPU can be co-ordinated over multiple clock cycles to execute an instruction. In the case of the 6502 some pipelined actions could also be executed by the microcode.
Microcoded designs used less silicon than hard-wired chips at the expense of potentially taking several clock cycles to complete an instruction. Depending on the design, these CPUs would take varying lengths of time per instruction.
Hardwired architectures
Hardwired designs (not necessarily mutually exclusive with microcode) execute an instruction synchronously, or may have their own coordinators to do something across multiple clock cycles. They are typically faster at the expense of more dedicated hardware and are thus more expensive to implement than a microcoded design of equivalent functionality.
A famous example of this was the original Amdahl 470/6 CPU, which was a drop-in replacement for the CPU on certain IBM System/370 models. The Amdahl CPU was a hardwired design at a time when IBM's 370 CPUs were heavily based on microcode. The Amdahl CPU was about 3 times faster than the IBM CPUs they replaced.
Needless to say, IBM was not amused and this resulted in a court battle that ended up forcing IBM to open their mainframe architecture until the consent decree expired a few years ago.
Typically, a hardwired design of this type was still not as fast clock-for-clock as a RISC CPU as the varying instruction timings and formats didn't allow as much scope for pipelining as a RISC design does.
Multiple-issue designs
Most modern CPUs are multiple issue architectures that can process more than one instruction at a time within a single thread. The chip can do a dynamic dependency analysis on the incoming instruction stream and issue instructions in parallel where there is no dependency on the result of a previous computation.
The throughput of these chips depends on how much parallelism can be achieved in the code but most modern CPUs will average several instructions per cycle on most code.
Modern Intel and other x86/X64 ISA CPUs have a layer that interprets the old-school CISC instruction set into micro instructions that can be fed through a pipelined RISC-style multiple issue core. This adds some overhead that is not present on CPUs with ISAs that are designed for pipelining (i.e. RISC architectures such as ARM or PowerPC).
VLIW designs
VLIW designs, of which the Intel Itanium is perhaps the best known, never took off as mainstream architectures, but IIRC there are a number of DSP architectures that use this type of design. A VLIW design makes multiple-issue explicit with an instruction word containing more than one instruction that is issued in parallel.
These were dependent on good optimising compilers, which identified dependencies and opportunities for parallelism, dropping instructions into the multiple slots available on each instruction word.
VLIW architectures work quite well for numerical applications as matrix/array ops tend to offer opportunities for extensive parallelism. The Itanium had a niche market in supercomputing applications for a while, and there was at least one supercomputer architecture - the Multiflow TRACE - was produced using an ISA of this type.
Memory and caching
Modern CPUs are much, much faster than memory, so direct reads from memory can generate hundreds of wait states which block the CPU until the memory access completes. Caching, now done in multiple layers, holds the most recently used memory locations in the cache. As CPUs typically spend the vast majority of time executing code in loops this means you get good hit rates of re-using memory locations that you've used recently. This property is called 'locality of reference.'
Where you get locality of reference the CPU can operate at close to optimum speed. Cache misses down to the next level incur a number of wait states; cache misses down to main memory can incur hundreds.
Thus, the actual throughput of CPU chips can be heavily dependent on the efficiency of memory access patterns. Whole books have been written on optimising code for this, and it's a complex topic in its own right.
\$\endgroup\$
3
\$\begingroup\$
It's a simplification for students.
Every non-trivial processor is pipelined. There is a prefetch unit shovelling instructions in one end, a number of execution units in the middle doing actual work, and an issue unit responsible for declaring instructions completed after the write to register or memory has finished. If there are multiple execution units (say, an integer ALU, a floating point ALU, and vector unit) it may be possible to issue (sometimes called "retire") multiple instructions per clock cycle. How can a CPU deliver more than one instruction per cycle? goes into lots more detail on this.
As you say, what if there is a cache miss delay? Intel Hyperthreading is a novel solution to this: two lots of CPU state registers, one lot of control logic and issue units. As soon as one virtual CPU stalls, swap to the other's state. (this is a gross oversimplification itself)
The result of this is that modern CPU manuals give much vaguer instruction timings, and it's much harder to write cycle-accurate timing code, if for example you're trying to output video in real time from hardware that should not be capable of it.
(Specific answer to "How long does one CISC instruction take in clock/instruction cycles?" is "look in the manufacturer's reference manual and it will have timings per instruction")
\$\endgroup\$
0
\$\begingroup\$
The other guys have written a lot of good material, so I'll keep my answer short: In the old days, (1980's here), the 8 bit processors of the day (6800, 6502, Z80, 6809 and others) were considered CISC. Some instructions could execute in 2 clock cyles but these were simple instuctions such as setting/clearing flag bits in a processor status register. Other instructions could take anywhere from 2-6 and even up to 9 clock cycles to execute. These processors had some fairly powerful instructions, the Z80 had some memory block clearing instructions which would write the same value in to a series of bytes in memory, effectively clearing a large block in a single instruction, just set up a few registers and execute the LDIR instruction (load, increment and repeat).
The 6502 processor (from memory) had 56 instructions but 13 addressing modes creating a powerful instruction set.
RISC came a long and adopted a different approach, have a handful instructions which all execute in a single clock cycle. The programs tend to be longer and occupy more memory because the instructions are simple in what operations they carry out so you need more of them.
If I recall correctly the first attempt at a RISC architecture was either the transputer or Acorn Risc processor?
\$\endgroup\$
6
• \$\begingroup\$ Arguably the first pipelined RISC-type architecture was the CDC 6600 designed by Seymour Cray. That was a couple of decades before the term RISC got into widespread usage. MIPS, ARM and a few other RISC microprocessor designs go back to the 1980-1985 period with the first commercial hardware using these chips coming out around the mid-1980s. \$\endgroup\$ – ConcernedOfTunbridgeWells May 15 '15 at 15:48
• \$\begingroup\$ Individual transputer chips were quite fast, but weren't the same type of architecture as one normally associates with a RISC chip. en.wikipedia.org/wiki/Transputer#Architecture \$\endgroup\$ – ConcernedOfTunbridgeWells May 15 '15 at 15:58
• \$\begingroup\$ I've got a couple of transputers in a anti-static case, just part of an historical microprocessor collection. Never used them, would have been a lot of fun in those days to experiment with them. \$\endgroup\$ – Dean May 15 '15 at 16:35
• \$\begingroup\$ @ConcernedOfTunbridgeWells I just had a look at the CDC 6600 instruction set. While the design seems to embody (and anticipate) some of the principles of RISC the floating point divide instruction takes 29 cycles to execute! And the very inclusion of a divide instruction is against typical RISC principles, but thanks for the very interesting comment! \$\endgroup\$ – crgrace May 16 '15 at 0:22
• \$\begingroup\$ The main RISC-ish attributes were the pipelined instruction fetch/decode/execute mechanism and load-store architecture (i.e. no addressing modes with implicit memory accesses to calculate address). In fact, some RISC instruction sets (e.g. the IBM POWER) are actually quite large but still use the load/store approach to ensure consistent execution times. \$\endgroup\$ – ConcernedOfTunbridgeWells May 17 '15 at 21:45
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
|
__label__pos
| 0.891464 |
Anuncios
martes, 16 de marzo de 2010
Powershell – trabajar con archivos
En esta ocasión voy a mostrar:
· Cómo mostrar una lista de archivos en powershell y guardar en un archivo de texto ?
· Cómo mostrar el nombre de los archivos y el tamaño ordenados por tamaño en powershell ?
· Cómo mostrar el nombre de los archivos y el tamaño cuyo tamaño sea 79 bytes en powershell ?
· Cómo mostrar una lista de archivos en powershell y guardar en un archivo de texto
gci >lista.txt
· Cómo mostrar el nombre de los archivos y el tamaño ordenados por tamaño
gci |select name,length |sort length –desc
Donde gci es la lista de archivos, select name, length son las columnas a mostrar y sort length significa ordenar los archivos por tamaño. Desc significa ordenar en orden descendente.
· Cómo mostrar el nombre de los archivos y el tamaño cuyo tamaño sea 79 bytes en powershell ?
gci |select name,length | where {$_.length -eq 76}
where {$_.length -eq 76} significa mostrar archivos cuyo tamaño sea equivalente a 76 bytes.
Si tienes más dudas, escribe a este blog.
People who read this post also read :
|
__label__pos
| 0.937009 |
Announcing the Appwrite OSS Fund, Learn More! 🤑
Docs
Debugging
Appwrite comes with a few built-in tools and methods that easily debug and investigate issues on your Appwrite stack environment.
Doctor CLI available from >= v0.7
The doctor CLI helps you validate your server health and best practices. Using the Doctor CLI, you can verify your server configuration for best practices, validate your Appwrite stack connectivity and storage read and write access, and available storage space.
To run the Doctor check, simply run the following command from your terminal. You might need to replace ‘appwrite’ with your Appwrite Docker container ID. To find out what’s your container ID, you can run `docker ps` command (more on that, in the next section).
docker exec appwrite doctor
Logs
Checking your Appwrite containers can be a great way to pinpoint where and what exactly happens inside your Appwrite services. You can list your Appwrite containers using the following command in your terminal:
docker ps
The output of this command will show you a list of all your running Docker containers, their ID's, uptime, and open ports. You can use each container ID to get a list of all the container `stdout` and `stderr` logs by using the following command:
docker logs [CONTAINER-ID]
Status Codes
Appwrite uses conventional HTTP response codes to indicate the success or failure of an API request. In general: Codes in the 2xx range indicate success. Codes in the 4xx range indicate an error that failed given the information provided (e.g., a required parameter was omitted, invalid input, etc.). Codes in the 5xx range indicate an error with the Appwrite server, but these are rare.
Learn more about Appwrite status codes
Dev Mode
When moving to dev mode, your server will produce much more verbose error messages. Instead of getting a general 500 error, you’ll be able to view the exact error that happened on the server, debug the issue further or report it to the Appwrite team.
To change your dev environment, edit your server _APP_ENV environment variable from ‘production’ to ‘development’ in your Appwrite docker-compose.yml file located in the `appwrite` directory in the location where you first installed Appwrite.
...
- influxdb
- telegraf
environment:
- _APP_ENV=development
- _APP_OPENSSL_KEY_V1=your-secret-key
- _APP_DOMAIN=localhost
...
After you completed the change in the docker-compose.yml file, save it and run the following command to restart Appwrite with your new settings:
docker-compose up -d
|
__label__pos
| 0.994678 |
Ejercicios resueltos de Python - Página 1
Ejercicios resueltos de Python
Aquí tienes todos los ejercicios resueltos del curso de Python. Si te quedan dudas o tienes un resultado diferente, déjame un comentario, ya que a veces, un ejercicio puede tener muchas posibles soluciones.
Soluciones de ejercicios Python - Página 1
Capítulo 1
Este capítulo no tiene ejercicios.
Capítulo 2
1. En este ejercicio, solo tenías que escribir una variable con el nombre que quisieras y ponerle un mensaje:
2. mensaje = "Este es un mensaje cualquiera."
3. Se crean dos variables y se les da un valor numérico a cada una.
4. numero1 = 10
numero2 = 15
5. Aquí, mediante las dos variables creadas en el segundo ejercicio, tenías que intentar sumar sus valores y almacenarlo en una tercera variable. No te preocupes si no lo has sabido hacer, tal y como he dicho en el enunciado, todavía no te he mostrado a hacerlo, es un ejercicio para pensar.
6. numero1 = 10
numero2 = 15
resultado = numero1 + numero2
7. En este último ejercicio del primer capítulo, tenías que imprimir el valor de la variable resultado en la consola solo si conseguiste realizar el tercer ejercicio.
En caso contrario, solo tenías que imprimir el valor de texto de la variable del primer ejercicio.
8. Solución con el ejercicio 3
numero1 = 10
numero2 = 15
resultado = numero1 + numero2
print(resultado)
Solución sin el ejercicio 3
mensaje = "Este es un mensaje cualquiera."
print(mensaje)
Capítulo 3
9. En este ejercicio tenías que crear dos variables con valores string y escribir uno con comillas simples '' y otro con dobles"".
10. texto1 = 'Este es el string en comillas simples.'
texto2 = "Este es el string en comillas dobles."
11. Había que almacenar una frase que te escribí en el enunciado e imprimirla en la consola. Para ello, debes utilizar print().
12. frase = '"print()" se utiliza para imprimir valores en la consola.'
print(frase)
Capítulo 4
13. Con el operador + podemos concatenar estos dos strings dentro de una variable.
14. concatena = "Esta es una " + "sola frase."
print(concatena)
15. En este caso, hemos hecho lo mismo con la diferencia, que en lugar de concatenar solo strings, estamos concatenando los strings de dos variables en una tercera.
16. palabra1 = "Programación "
palabra2 = "Fácil"
nombre = palabra1 + palabra2
17. Aquí debías concatenar el valor string de una variable y un valor string.
18. palabra1 = "Programación "
print(palabra1 + "Fácil")
19. En este ejercicio tenías que crear primero, tres variables con tu nombre y tus apellidos. En una cuarta variable, tenías que concatenar estos valores con los respectivos espacios para separar las palabras.
20. nombre = "Enrique"
apellido1 = "Barros"
apellido2 = "Fernández"
nombre_completo = nombre + " " + apellido1 + " " + apellido2
print(nombre_completo)
21. Te pongo tres posibles soluciones para este ejercicio:
22. # Solución 1
numero1 = "40"
numero2 = "60"
numero3 = numero1 + numero2
# Solución 2
numero = "40" + "60"
# Solución 3
print("40" + "60")
Capítulo 5
23. Lo podemos conseguir gracias a title().
24. nombre = "enrique barros fernández".title()
25. Lo podemos conseguir gracias a lower().
26. nombre = "Esta Es Una Frase Para Ser Formateada.".lower()
27. Con upper() podemos transformar los strings a mayúsculas.
28. nombre = "Esta Es Una Frase Para Ser Formateada.".upper()
Capítulo 6
29. Para conseguir realizar este ejercicio tenías que utilizar los saltos de línea y las tabulaciones.
30. print("-Python.\n-JavaScript.\n-Java.\n-PHP.\n-TypeScript.\n-SQL.\n-COBOL.")
Capítulo 7
31. Los números que hayas utilizado pueden ser diferentes a los míos. Solo se pide que el resultado sea 87 incluyendo en la operación los números 20 y 23.
32. suma = 20 + 23 + 44
33. Los números que hayas utilizado pueden ser diferentes a los míos. Solo se pide que el resultado sea -87 incluyendo en la operación los números 20 y 23.
34. resta = 20 - 23 - 84
35. Los números que hayas utilizado pueden ser diferentes a los míos. Solo se pide que el resultado sea 870 incluyendo en la operación el número 10.
36. multiplicacion = 10 * 87
37. Los números que hayas utilizado pueden ser diferentes a los míos. Solo se pide que el resultado sea 10 con o sin decimales incluyendo en la operación los números 5000 y 230.
38. # El resultado es 10.869565217391305
division = 5000 / 230 / 2
39. Con este orden, te da como resultado el valor de 0.
40. operacion = 10 / 5 + 15 - 17
Capítulo 8
41. Este ejercicio está pensado para que puedas apreciar el valor de los exponentes. Ya ves lo difícil que es operar con números elevados sin utilizar exponentes.
42. mil_veinticuatro = 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 * 2
Capítulo 9
43. En este ejercicio debías darle un valor de 5 al segundo parámetro del round()
44. numero = round(17.567383292929200234, 5).
Capítulo 10
45. El color de la posición 3 es:
46. 'amarillo'
47. El color 'rojo' está en la posición número 0 y el 'rosa' en la 7.
48. La lista debe quedar así:
49. numeros = ["tres", "dos", "cinco", "cuatro", "uno"]
Páginas
Suscríbete a mi canal de YouTube para apoyarme
Si te ha gustado este curso y crees que el trabajo merece la pena, te agradeceré eternamente que te suscribas a mi canal de YouTube para apoyarme y que pueda seguir haciendo cursos gratuitos.
Además, si te encanta la programación, tienes un montón más de cursos gratuitos para ver.
No solo eso, podrás participar enviándome comentarios con tus sugerencias para temas específicos o cursos completos o incluso las dudas que tengas y las intentaré ir resolviendo en los cursos que estén todavía abiertos.
Comentarios
Si te quedan dudas sobre el temario, sobre JavaScript, o cualquier otra cosa relacionada o simplemente quieres agradecer, aquí tienes tu sitio para dejar tu granito de arena. Gracias por tus comentarios y por darle vida a este sitio web.
|
__label__pos
| 0.899304 |
Title:
SYSTEM AND METHOD FOR BRAILLE ASSISTANCE
Kind Code:
A1
Abstract:
A braille teaching/autocorrecting system includes a camera configured to detect image data corresponding to at least one braille character. The braille teaching/autocorrecting system also includes a processor coupled to the camera and configured to identify the at least one braille character based on the image data and determine feedback data based on the identification of the at least one braille character.
Inventors:
Djugash, Joseph M. A. (San Jose, CA, US)
Application Number:
14/618950
Publication Date:
08/11/2016
Filing Date:
02/10/2015
Assignee:
Toyota Motor Engineering & Manufacturing North America, Inc. (Erlanger, KY, US)
Primary Class:
International Classes:
G09B21/02; G09B21/00
View Patent Images:
Related US Applications:
20060286516Method for ensuring employees safe work readinessDecember, 2006Michels et al.
20050019737Evaluation system, method and program for evaluating abilityJanuary, 2005Iida et al.
20090197233Method and System for Test Administration and ManagementAugust, 2009Rubin et al.
20080026349BEHAVIOR CARD GAME METHOD AND APPARATUSJanuary, 2008Verona
20090111073SYSTEM AND METHOD FOR ELEVATED SPEED FIREARMS TRAININGApril, 2009Stanley
20050026128Print media apparatus for young childrenFebruary, 2005Wood et al.
20070026371Personal electronic text library system patentFebruary, 2007Wood
20030198927Interactive computer system with doll characterOctober, 2003Campbell
20070243515System for facilitating the production of an audio output trackOctober, 2007Hufford
20050148283Interactive displayJuly, 2005Schwalm
20050287501Method of aural rehabilitationDecember, 2005Sweetow et al.
Foreign References:
JP4727352B22011-07-20
Other References:
Diallo, "Apple iOS 8: Top New Features", 18 of September 2014, Forbes, http://www.forbes.com/sites/amadoudiallo/2014/09/18/apple-ios-8-top-new-features/#780ea24d6c7e
Zhang, Shanjun; Yoshino, Kazuyoshi; A Braille Recognition System by the Mobile Phone with Embedded Camera; 2007; IEEE
Diallo, Amadou; September 18, 2014; Apple iOS8: Top New Features, Forbes Magazine
N. Kalar, T. Lawers, D. Dewey, T. Stepleton, M.B. Dias; Iterative Designe of A Braille Writing Tutor to Combat Illiteracy; August 30, 2007; IEEE
Claims:
What is claimed is:
1. A braille teaching/autocorrecting system comprising: a camera configured to detect image data corresponding to at least one braille character; and a processor coupled to the camera and configured to identify the at least one braille character based on the image data and determine feedback data based on the identification of the at least one braille character.
2. The braille teaching/autocorrecting system of claim 1 wherein the processor is further configured to determine a word to be written and the feedback data includes whether the at least one braille character corresponds to a correct spelling of the word.
3. The braille teaching/autocorrecting system of claim 1 wherein the processor is further configured to: determine whether the at least one braille character corresponds to a misspelling of a word or an incorrectly-written braille character; determine a correct spelling of the word or a correctly-written braille character; and replace the at least one braille character with the correct spelling of the word or replace the incorrectly-written braille character with the correctly-written braille character in response to determining that the at least one braille character corresponds to the misspelling of the word or the incorrectly-written braille character.
4. The braille teaching/autocorrecting system of claim 1 further comprising an input device coupled to the processor and configured to transmit an input to the processor, wherein the processor is further configured to: determine a potential word based on the at least one braille character; and autocomplete the at least one braille character with remaining characters of the potential word in response to receiving a first input indicating that the potential word is a desired word.
5. The braille teaching/autocorrecting system of claim 1 further comprising two elongate members and wherein the camera is capable of detecting a position of the two elongate members and the processor is further configured to determine a size of a braille cell based on the position of the two elongate members.
6. The braille teaching/autocorrecting system of claim 1 wherein the image data includes at least one of hand positions of a user's hand, stylus positions of a stylus or indentions on a substrate over a period of time and the processor is configured to identify the at least one braille character based on the hand positions, the stylus positions or the indentions.
7. The braille teaching/autocorrecting system of claim 1 wherein the at least one braille character is reverse-oriented.
8. The braille teaching/autocorrecting system of claim 7 wherein the at least one braille character is written in a reverse direction.
9. The braille teaching/autocorrecting system of claim 1 further comprising: an upper portion having a first end and a second end and configured to rest on a user's neck; a first lower portion coupled to the first end of the upper portion and configured to rest on a user's first shoulder; and a second lower portion coupled to the second end of the upper portion and configured to rest on a user's second shoulder, wherein the camera is positioned on a front surface of the first lower portion or the second lower portion.
10. A braille teaching/autocorrecting system comprising: a sensor configured to detect braille data corresponding to at least one reverse-oriented braille character; and a processor coupled to the sensor and configured to identify the at least one reverse-oriented braille character based on the braille data and determine feedback data based on the identification of the at least one reverse-oriented braille character.
11. The braille teaching/autocorrecting system of claim 10 further comprising two elongate members and wherein the sensor is a camera capable of detecting a position of the two elongate members and the processor is further configured to determine a size of a braille cell based on the position of the two elongate members.
12. The braille teaching/autocorrecting system of claim 10 wherein the sensor is a camera and the braille data includes at least one of a hand position of a user's hand, a stylus position of a stylus or indentions on a substrate and the processor is configured to identify the at least one reverse-oriented braille character based on the hand position, the stylus position or the indentions.
13. The braille teaching/autocorrecting system of claim 10 wherein the at least one reverse-oriented braille character is written in a reverse direction.
14. The braille teaching/auto correcting system of claim 10 further comprising: an upper portion having a first end and a second end and configured to rest on a user's neck; a first lower portion coupled to the first end of the upper portion and configured to rest on a user's first shoulder; and a second lower portion coupled to the second end of the upper portion and configured to rest on a user's second shoulder, wherein the sensor is positioned on a front surface of the first lower portion or the second lower portion.
15. The braille teaching/autocorrecting system of claim 10 further comprising: an input/output port coupled to the processor; and a computing device such that the processor and the input/output port are positioned on the computing device, wherein the sensor is a camera positioned remote from the computing device and coupled to the computing device via the input/output port.
16. The braille teaching/autocorrecting system of claim 10 wherein the sensor is a touchscreen including six locations that correspond to a braille cell and the braille data includes selected locations of the six locations.
17. A braille teaching/autocorrecting system comprising: a sensor configured to detect braille data corresponding to at least one braille character; and a processor coupled to the sensor and configured to: determine a direction in which the at least one braille character is being written based on the braille data, determine an orientation in which the at least one braille character is being written based on the braille data, identify the at least one braille character based on the braille data, and determine feedback data based on the direction, orientation and identification of the at least one braille character.
18. The braille teaching/autocorrecting system of claim 17 further comprising two elongate members and wherein the sensor is a camera capable of detecting a position of the two elongate members and the processor is further configured to determine a size of a braille cell based on the position of the two elongate members.
19. The braille teaching/autocorrecting system of claim 17 wherein the sensor is a camera and the braille data includes image data corresponding to at least one of a hand position of a user's hand, a stylus position of a stylus or indentions on a substrate and the processor is configured to identify the at least one braille character based on the hand position, the stylus position or the indentions.
20. The braille teaching/autocorrecting system of claim 17 further comprising: an upper portion having a first end and a second end and configured to rest on a user's neck; a first lower portion coupled to the first end of the upper portion and configured to rest on a user's first shoulder; and a second lower portion coupled to the second end of the upper portion and configured to rest on a user's second shoulder, wherein the sensor is positioned on a front surface of the first lower portion or the second lower portion.
Description:
BACKGROUND
1. Field
The present disclosure relates to a method and a system for autocorrecting and/or teaching braille.
2. Description of the Related Art
Many systems have been developed to help sighted individuals with the task of writing and learning to write. The number of these systems has been increasing with the advance of technology. For example, autocorrect functions have been added to many applications such as word processing, email, calendar events and the like. These autocorrect functions may detect when a typed word is incorrectly spelled and may automatically correct the spelling within the application. Some autocorrect functions may also perform autofill functions such that the system predicts what a user is writing as the user types and automatically completes the word for the user.
Other systems include aids to help a student learn to write. These systems may observe the student typing and detect when a word is incorrectly spelled. In response to the detected incorrect spelling, the system may provide feedback including the correct way to spell the word.
These tools are useful but unfortunately cannot help blind individuals in the same manner that they can help sighted individuals. Blind individuals read and write using braille which is designed such that the individual can read using his sense of touch instead of vision. Braille includes various combinations of protrusions within a 3 by 2 cell with each combination of protrusions corresponding to a letter of the alphabet. Thus, in order to write braille, the user may write with the reading/writing substrate upside down (so the characters are reverse-oriented as written) so that the user can “poke” the protrusions into the paper and flip the substrate over in order to feel them. Some blind people start at the right side of the page and write in a forward direction (first letter of each word written first) or in a reverse direction (last character of each word written first). Because blind people comprise a minority of the population and because braille can be written in various manners, less time and effort has been spent developing systems for autocorrecting and/or teaching braille.
Thus, there is a need for systems and methods for teaching and/or autocorrecting braille.
SUMMARY
What is described is a braille teaching/autocorrecting system. The braille teaching/autocorrecting system includes a camera configured to detect image data corresponding to at least one braille character. The braille teaching/autocorrecting system also includes a processor coupled to the camera and configured to identify the at least one braille character based on the image data and determine feedback data based on the identification of the at least one braille character.
Also described is a braille teaching/autocorrecting system. The braille teaching/autocorrecting system includes a sensor configured to detect braille data corresponding to at least one reverse-oriented braille character. The braille teaching/autocorrecting system also includes a processor coupled to the sensor and configured to identify the at least one reverse-oriented braille character based on the braille data and determine feedback data based on the identification of the at least one reverse-oriented braille character.
Also described is a braille teaching/autocorrecting system. The braille teaching/autocorrecting system includes a sensor configured to detect braille data corresponding to at least one braille character. The braille teaching/autocorrecting system also includes a processor coupled to the sensor. The processor is configured to determine a direction in which the at least one braille character is being written based on the braille data. The processor is also configured to determine an orientation in which the at least one braille character is being written based on the braille data. The processor is also configured to identify the at least one braille character based on the braille data. The processor is further configured to determine feedback data based on the direction, orientation and identification of the at least one braille character.
BRIEF DESCRIPTION OF THE DRAWINGS
Other systems, methods, features, and advantages of the present invention will be or will become apparent to one of ordinary skill in the art upon examination of the following figures and detailed description. It is intended that all such additional systems, methods, features, and advantages be included within this description, be within the scope of the present invention, and be protected by the accompanying claims. Component parts shown in the drawings are not necessarily to scale, and may be exaggerated to better illustrate the important features of the present invention. In the drawings, like reference numerals designate like parts throughout the different views, wherein:
FIG. 1A illustrates a braille cell;
FIG. 1B illustrates the braille alphabet;
FIG. 2A illustrates a slate and a stylus that are designed for writing braille;
FIG. 2B illustrates a reverse-oriented braille cell;
FIG. 3A illustrates a phrase “the car” written using braille;
FIG. 3B illustrates one example of how an individual would write the phrase “the car” in braille;
FIG. 3C illustrates another example of how an individual would write the phrase “the car” in braille;
FIG. 4A illustrates a braille teaching/autocorrecting device capable of auto correcting a user who is writing braille and/or teaching braille to a user according to an embodiment of the present invention;
FIG. 4B illustrates a block diagram of a processor of the device of FIG. 4A including multiple modules according to an embodiment of the present invention;
FIG. 5 illustrates a smart necklace which can be used for teaching and/or autocorrecting braille according to an embodiment of the present invention;
FIG. 6 illustrates a smart mobile device, such as a tablet or a mobile telephone, which can be used for teaching and/or autocorrecting braille according to an embodiment of the present invention;
FIG. 7 illustrates a laptop which can be used for teaching and/or autocorrecting braille according to an embodiment of the present invention;
FIG. 8 illustrates another system for teaching and/or autocorrecting braille including a camera remote from a smart device according to an embodiment of the present invention;
FIG. 9 illustrates a method to be performed by a processor of a device for teaching and/or autocorrecting braille according to an embodiment of the present invention;
FIG. 10A illustrates a phrase written using reverse-orientation braille characters;
FIG. 10B illustrates an exemplary use of the teaching mode blocks of the method of FIG. 9 for reverse-oriented braille written in a reverse direction according to an embodiment of the present invention;
FIG. 10C illustrates an exemplary use of the autocorrect mode blocks of the method of FIG. 9 for reverse-oriented braille written in a reverse direction according to an embodiment of the present invention; and
FIG. 10D illustrates an exemplary use of the autocorrect mode blocks of the method of FIG. 9 for reverse-oriented braille written in a forward direction according to an embodiment of the present invention.
DETAILED DESCRIPTION
The systems and methods described herein provide autocorrecting and teaching functionality to individuals writing using braille. The systems and methods described herein provide several benefits and advantages such as being able to detect braille that is written by a user as the user is writing the braille and determine which braille character the user has written. The systems and methods also provide the advantage of assisting an individual in the learning of braille by providing feedback to the user as the user is writing the braille as well as autocompleting and autocorrecting braille as the user is writing it in order to save the user time while writing the braille. For example, a potential word determination may be made based on detected written characters, a number or percentage of times each word has been written by the user, which word or words fit contextually, whether a character of a misspelled word has locations selected that are similar to another character that is a potential word, whether the user uses a different pattern of writing to write different words or the like. Additionally, the processor is capable of determining feedback, autocompleting and autocorrecting braille when written in a forward or reverse-orientation and a forward or reverse direction, which provides the advantage of being usable by any braille writer regardless of their writing style.
An exemplary system includes a sensor that is capable of detecting braille as it is being written, such as a camera for detecting the location of a user's hand, stylus, etc. or a touchscreen for detecting contact corresponding to locations within a braille cell. The system also includes a memory for storing braille characters and words in reverse or forward-orientations. The system also includes a processor for determining which characters are being written by the user, determining a direction and an orientation of the braille writing and determining feedback to provide to the user based on the determined characters and the direction and orientation of the braille. The system also includes an output device for providing the feedback, such as speakers or a vibration unit.
FIG. 1A illustrates a braille cell 100. The braille cell 100 includes three rows and two columns forming 6 locations: 1, 2, 3, 4, 5 and 6. Some of the locations may be selected (i.e., contain raised protrusions) such that different patterns of locations having protrusions correspond to different characters of the alphabet. A vision impaired individual can place one or more fingers on a braille cell and determine which character the braille cell corresponds to based on the pattern of raised locations.
FIG. 1B illustrates the braille alphabet 150. Referring to FIGS. 1A and 1B, the letter “A” corresponds with a braille cell having only location 1 selected, the letter “B” corresponds with a braille cell having location 1 and location 2 selected, etc. Each selected location should include a protrusion extending away from the reading surface of the substrate towards the user. In other words, the braille reader should feel the protrusion of each selected location when reading rather than feeling an indention at the selected locations.
Most vision impaired individuals are taught to both read and write braille. When writing using braille, multiple braille characters may be positioned adjacent to each other such that the multiple braille characters correspond to a word. A space may be left between words to indicate the separation of words. It is preferable for each braille cell 100 to have the same size so that a reader can quickly scan his finger or fingers over the text without having to adjust for different sized cells.
Special tools have been developed to simplify the process and to improve the quality of written braille. FIG. 2A illustrates a slate 200 and a stylus 202 that are designed for writing braille. The braille slate 200 includes a first plate 210 and a second plate 212. The plates are coupled together by a hinge 208. The stylus 202 includes a handle 205 coupled to a tip 203.
Before writing braille using the slate 200 and the stylus 202, a piece of paper or other substrate is placed between the first plate 210 and the second plate 212. The plates are then pushed together and may be coupled such that the paper or other substrate cannot easily become removed from the slate 200. The second plate 212 may define rectangular or other shaped holes 204 that correspond with a cell and define the cell size. The first plate 210 includes a plurality of indentions 206 such that six indentions 206 corresponding to the locations of a braille cell align with each rectangular hole 204.
In order to write the braille once the substrate is coupled to the slate 200, an individual may grasp the stylus 202 at the handle 205 and form indentions in the substrate by pressing the tip 203 through each rectangular hole 204 into each indention 206. By repetitively applying this method, a user may write multiple braille characters and multiple words using the slate 200 and the stylus 202.
When writing braille using the slate and stylus method, each braille character should be written in a reverse-orientation (i.e., reversing each location of the braille cell) as indicated in FIG. 2B, which illustrates a reverse-oriented braille cell 250. The reverse-orientation is required because the user is forming the raised location by pushing the tip 203 into the substrate such that the substrate must be flipped over to feel the selected locations.
Additionally, the braille should be written such that the first letter of the word begins on the far right of the line and the last letter is positioned on the far left of the line. As the substrate will be turned over before being read, this ensures that the braille can be read from left to right.
FIG. 3A illustrates a phrase “the car” written using braille. Six braille cells 300, 302, 304, 306, 308 and 310 are used to write this phrase. In FIG. 3A, the selected locations of each cell will extend away from the page such that each raised location will be felt by placing a finger over the cell.
As mentioned above, braille may be written such that each line starts on the right and ends on the left. FIG. 3B illustrates one example of how an individual would write the phrase “the car.” As illustrated in FIG. 3B, the orientation of each braille cell is reversed and the phrase is written from right to left. Some individuals writing braille twill write in a reverse direction (i.e., begin at the left of the substrate with the last letter of the line), as illustrated in FIG. 3B. Some individuals will write in a forward direction (i.e., begin at the right of the substrate with the first letter of the line, as illustrated in FIG. 3C).
FIG. 4A illustrates a braille teaching/autocorrecting device 400 capable of auto correcting braille as a user is writing it and/or teaching braille to a user. The teaching/autocorrecting device 400 can be a mobile device such as a laptop, a tablet, a wearable smart device, a stationary device such as a desktop computer or the like. The teaching/autocorrecting device 400 includes a processor 402, a memory 404, a sensor 406, an input device 408, an output device 410 and an I/O port 412. Each component may be in electrical communication with one another, as illustrated. The teaching/autocorrecting device 400 may include any combination of the above components and/or may include additional components not illustrated.
The processor 402 may include a computer processor such as an ARM processor, DSP processor, distributed processor or other form of central processing. The processor 402 may be local (i.e., positioned in/on the teaching/autocorrecting device 400), may be remote (i.e., positioned remote from the teaching/autocorrecting device 400), or it may be a pairing of a local and a remote processor. The processor 402 may be capable of determining braille characters that have been and/or are being written by a user based on data detected by the sensor 406. The processor 402 may also be capable of determining feedback to provide to the user based on the determined braille characters.
The memory 404 may include one or any combination of a RAM or other volatile or nonvolatile memory, a non-transitory memory or a data storage device, such as a hard disk drive, a solid state disk drive, a hybrid disk drive or other appropriate data storage. The memory 404 may store machine-readable instructions which may be executed by the processor 402. As with the processor 402, the memory 404 may be local, remote or a pairing of local and remote.
The sensor 406 may include any sensor capable of detecting braille writing over a period of time. For example, the sensor 406 may include a camera capable of detecting the position of a tip of a stylus, the position of a user's hand, indentions in a substrate or the like in order to determine each location selected by a user.
Detection of indentions in a substrate includes different techniques than detection of typical characters on a substrate using an optical character recognition (OCR) system. Typical OCR systems are designed to ignore small marks on a page. This removal would not work for braille, as each indention may be detected and ignored as a small mark. Accordingly, in order to detect indentions, a preferable method may include magnifying the small marks and ignore the larger marks.
In some embodiments, the sensor 406 may include a touchscreen having different areas corresponding to locations of a braille cell, an electronic circuit having areas corresponding to each location of a braille cell such that a touch in each location closes a circuit and indicates a selection of the location, or the like.
The input device 408 may include any input device such as a mouse, a track pad, a microphone, one or more buttons, a pedal, a touchscreen and/or the like. The input device 408 may be adapted to receive input from a user corresponding to a function of the teaching/autocorrecting device 400. For example, a user may toggle between an autocorrect mode or a teaching mode using the input device 408.
The output device 410 may include a speaker, a vibration unit, a display, a touchscreen and/or the like. The output device 410 may output data indicating one or more options for autocorrecting as a user begins to write braille, it may output data indicating whether a user is writing braille correctly, it may output data indicating potential improvements to a user's writing or the like.
Using the teaching/autocorrecting device 400, a user may write braille and the sensor 406 may detect the braille as the user is writing it such that the sensor 406 may detect each selected location of each braille cell as it is selected by the user, it may detect each portion of a braille character, each braille character, each word or group of words or any combination of the above after they are completed. As the user is writing, the processor 402 may predict one or more potential autocorrect words based on what the user has already written. Using the output device 410, the teaching/auto correcting device 400 may output the one or more potential words after the user has written at least one character. Using the input device 408, the user may inform the teaching/autocorrecting device 400 whether a potential word is the correct word. Based on the user's response, the processor 402 completes the word for the user.
The I/O port 412 may include one or more ports adapted to allow communications between the teaching/autocorrecting device 400 and another device. For example, the I/O port 412 may include a headphone jack, a data port, a wireless antenna, a 3G or LTE chip or the like. In some embodiments, one or more of the components of the teaching/autocorrecting device 400 may be positioned remote from the teaching/autocorrecting device 400. These components may communicate with one another and with the onboard components via the I/O port 412. For example, the teaching/autocorrecting device 400 may have an onboard processor and a memory. A camera, a wireless mouse and a speaker may be remote from the teaching/autocorrecting device 400 and coupled to each other and the processor and the memory via the I/O port 412.
In some embodiments, the I/O port 412 may allow communications between a computing device and the teaching/autocorrecting device 400 such that the teaching/autocorrecting device 400 may determine characters, words, sentences or the like and transmit them via the I/O port 412 to the computing device. The computing device may then cause the characters, words, sentences, etc. to become inserted into an application such as email, web browser, word processing or the like.
FIG. 4B illustrates a block diagram of the processor 402 including multiple modules. The processor 402 includes a braille recognition module 450, a direction determination module 452, a potential word determination module 454, a feedback determination module 456 and a braille cell size determination module 458. Each module may be in electrical communication with one another, as illustrated in FIG. 4B. The processor 402 may include any combination of the above modules and/or may include additional modules not illustrated.
The braille recognition module 450 is adapted to recognize braille characters as they are being written. The sensor 406 may detect data that corresponds to braille data, such as a set of indentions corresponding to braille cell locations, the location of a user's hand and/or the location of a tip of a stylus, and transmit the detected data to the processor 402. In some embodiments, the braille recognition module 450 may determine selected characters and/or locations by the user simply tapping a stylus on the desired location. The braille recognition module 450 may receive this detected data from the sensor 406 and determine which characters are being written based on the received data. The braille recognition module 450 may be adapted to identify braille characters written in a reverse-orientation, as they would be written by a user, or characters written in a forward-orientation, as they would be read by a user.
The direction determination module 452 may receive the data detected by the sensor 406 and/or the data generated by the braille recognition module 450 and determine whether the characters are being written as forward-oriented or reverse-oriented. The direction determination module 452 may also determine in which direction the braille is being written based on the received data (i.e., if reverse-oriented, whether the braille is being written in a forward direction from right to left or a reverse direction from left to right).
The potential word determination module 454 may be adapted to determine potential words that a user is writing and/or has written. The potential word determination module 454 may receive data including recognized characters from the braille recognition module 450 and/or a direction of the braille characters and/or the braille lines from the direction determination module 452. Based on the received data, the potential word determination module 454 may determine potential words based on partially written words and/or misspelled words.
In the example of FIG. 3B, the teaching/autocorrecting device 400 may detect the written braille characters in cells 304, 306, 308 and 310. The braille recognition module 450 may identify the written characters and the direction determination module 452 processor 402 may indicate that the braille is being written in a reverse-orientation and in a reverse direction. This data may be provided to the potential word determination module 454 which may determine that at least one potential word to be filled in cell 300, cell 302 and cell 304 might be the word “the” based on the letter “E” in cell 304.
If the same or a similar system detected the characters in FIG. 3C, the potential word determination module 454 may determine that the word to be written in cells 306, 308 and 310 of FIG. 3C may be “car” based on the letter “C” being written in cell 306. As writers of braille do not always write in the same directions, it is advantageous for the teaching/autocorrecting device 400 to be able to process detected braille characters and lines regardless of the orientation or direction as it can be used for all braille writers.
The potential word determination module 454 may be adapted to autocomplete a partially written word and/or correct misspelled words. The potential word determination module 454 may compare detected characters to a database of words to determine which word or words are potential words based on the determined characters. A module of the processor 402 may convert braille characters into other characters (i.e., the English alphabet) before processing (i.e., comparing the detected characters to words in a database) and/or the processor 402 may process the data without converting the braille characters. The potential word determination may be made based on detected written characters, a number or percentage of times each word has been written by the user, which word or words fit contextually, whether a character of a misspelled word has locations selected that are similar to another character that is a potential word, whether the user uses a different pattern of writing to write different words or the like.
In some embodiments, the potential word determination module 454 may predict a likelihood of each potential word being the correct word and rank the potential words based on the predicted likelihood. In some embodiments, the processor 402 may only output the highest ranked potential word. The user may then provide feedback via the input device 408 and/or the sensor 406 indicating whether the potential word is the correct word. In some embodiments, the potential word determination module 454 may output a plurality of potential words (such as the 3 highest ranked potential words, the 5 highest ranked potential words or the like). The user may select one of the potential words using the input device 408 and/or the sensor 406. For example, the user may tap the stylus, hold his hand in a certain position, click a mouse or the like in response to hearing the correct word to indicate that the most recent potential word is the correct word.
The feedback determination module 456 may be adapted to determine feedback to provide to the user based on data from the other modules. For example, if the user has selected a learning mode, the feedback determination module 456 may provide feedback every time a user writes a word correctly and/or incorrectly. The feedback may include a correct spelling of the word, correct dot placement within the cell for each character, an indication that the word is spelled wrong and the user should try again, that the sentence structure is incorrect, that incorrect punctuation is used or the like.
The feedback determination module 456 may also determine which, if any, potential words to provide to the user when the teaching/autocorrecting device 400 is in the autocorrect mode. For example, the feedback determination module 456 may include a user selectable setting (or a programmed setting) regarding a number of potential words (N) for the user to receive. The feedback determination module 456 may determine to output the N highest ranked potential words and provide data to the output device 410 causing the output device 410 to output the N highest ranked potential words.
The feedback determination module 456 may also determine a format in which the feedback will be provided to the user. The teaching/autocorrecting device 400 may include more than one output device 410, such as a speaker and/or a vibration unit. The feedback determination module 456 may determine whether to provide audio feedback and/or haptic feedback based on a number of factors. These factors may include which type of sensor 406 is being used, an ambient sound detected around the teaching/autocorrecting device 400, whether the user is in contact with the vibration unit, if the user has selected a preference or the like.
The braille cell size determination module 458 may be adapted to determine a size of the braille cells that the user is writing in based on data detected by the sensor. This determination may be made in different ways. For example, the teaching/autocorrecting device 400 may include two elongated members that the user may place together in an “L” shape that indicate the size of the braille cell. In some embodiments, the user may place two fingers together in an “L” shape to indicate the size of the braille cell. The sensor 406 may detect the “L” shape and the braille cell size determination module 458 may determine that the braille cell size is defined by a rectangle defined by an area within the “L” shape.
For example, the user may draw a rectangle using the stylus, a pen, a pencil or the like on a piece of paper to indicate the size of the braille cell. In embodiments where the sensor 406 is a touchscreen or an electronic circuit, the user may draw a rectangle and/or an “L” shape using a finger, a stylus, a pencil, a pen or the like indicating the size of the braille cell. In some embodiments, the user may begin to write and the processor 402 may determine the cell size based on the locations in which the user is selecting.
FIG. 5 illustrates a smart necklace 500 which is an exemplary embodiment of the teaching/autocorrecting device 400. The smart necklace 500 is designed to be worn around a user's neck. A top portion 520 is to be positioned behind the user's neck. A first side portion 522A may be adapted to cross over a user's shoulder and rest on the front of the user's shoulder. A second side portion 522B may be adapted to cross the user's other shoulder and rest in front of the user's other shoulder.
The smart necklace 500 may include a processor 502, a memory 504, a camera 506, a button 508, a first output unit 510A, a second output unit 510B and a battery 512. The smart necklace 500 may include any combination of the above components and/or may include additional components not illustrated. The processor 502 and the memory 504 may be similar to the processor 402 and the memory 404 of the teaching/autocorrecting device 400 and may be positioned on the smart necklace 500. The camera 506 may be any camera capable of detecting image data, such as the location of a user's hand, the location of a tip 556 of a stylus 554, an indentation on a substrate 550 or the like.
As an exemplary use of the smart necklace 500, a blind user wearing the smart necklace 500 may define a cell area on a substrate 550 by outlining a rectangle defining a cell 551 with the tip of the stylus 554. The camera 506 may detect this outline and the processor 502 may determine that the outline corresponds to a cell size. The processor may then divide the cell 551 into the 6 locations 552A, 552B, 552C, 552D, 552E and 552F of the cell 551.
The user may then begin to write in braille on the substrate 550 by touching the tip 556 of the stylus 554 to the substrate 550, by pushing the tip 556 of the stylus 554 into the substrate 550 causing indentions or the like. The substrate 550 may be a piece of paper, a sheet of metal or plastic or any other substrate. As the tip 556 of the stylus 554 approaches each location within the cell of the substrate 550, the processor 502 may determine that the location has been selected based on data detected by the camera 506. For example, the processor 502 may determine that a location has been selected when the image data received from the camera 506 indicates that the tip 556 is within a predetermined distance of the substrate 550. The tip 556 may be colored with a predetermined color so that the processor 502 can easily determine the location of the tip 556 relative to the substrate 550. In some embodiments, the processor 502 may determine that a location has been selected based on a detected position or location of the user's hand and/or detect indentions in the substrate 550 formed by the stylus 554.
The user and/or the processor 502 may define the cell size so that only one cell can fit on a surface 553 of the substrate 550 or so that many cells can fit on the surface 553 of the substrate 550. In FIG. 5, the cell size is defined such that only the cell 551 fits on the surface 553 of the substrate 550.
The processor 502 may store the character in the memory 504 in response to identifying the character. The processor 502 may be adapted to determine when the present character is complete based on detected data from the camera 506 such as a particular action being performed with the stylus 554, a tap of the user's finger, a selection of locations that corresponds with a character but cannot correspond to another character with additional selected locations or the like. The processor 502 may also be adapted to determine when a word is complete based on a detected space between cells, a particular action being performed with the stylus 554, a tap of the user's finger or the like. These features are particularly advantageous when the cell size is such that only one cell 551 can fit on the surface 553 so that the user can quickly proceed to the next cell and/or the next word.
The button 508 is an input device configured to receive an input from the user. The user may select an autocorrect mode or a teaching mode, may turn the smart necklace 500 on or off or further manipulate the functionality of the smart necklace 500 using the button 508. In some embodiments, the smart necklace 500 may include more than one button and/or a different input device, such as a toggle switch, a haptic strip, a touchscreen or the like.
The output units 510A and 510B may each include a speaker and/or a vibration unit. In some embodiments, the output units 510A and 510B may include both a speaker and a vibration unit. In some embodiments, the smart necklace 500 includes only one output unit which may provide audio and/or haptic output.
FIG. 6 illustrates a smart mobile device 600, such as a tablet or a mobile telephone. The smart mobile device 600 may include a processor 602, a memory 604, a touchscreen 606, a microphone 607 and a speaker 610. The processor 602 and the memory 604 may be similar to the processor 402 and the memory 404 of the teaching/autocorrecting device 400.
The touchscreen 606 may be adapted to receive user input via contact from a portion of a user's body, a stylus or another device. The touchscreen 606 may be divided into a location 612A, 612B, 612C, 612D, 612E and 612F that correspond to locations of a braille cell. Contact may be made with each location to indicating a selection of the location. After selecting desired locations, the user may indicate that he or she is finished with the character by performing an action, such as double tapping the touchscreen 606, swiping his finger in a particular manner or the like.
The microphone 607 may be an input device. A user may select between modes of the smart mobile device 600 by verbally speaking a command. A user may also indicate completion of a word, a desire to start a new sentence or another word processing request by verbally indicating the request. The microphone 607 may detect the speech data and transmit it to the processor 602, which may in turn determine the request and perform it.
The processor 602 may be adapted to determine a direction in which the user is writing and/or an orientation in which the user is writing. For example, a first user may write an F by selecting location 612A, location 612B and location 612D. In response, the processor 602 may determine that the user is writing in a forward-orientation. Another user may be used to writing braille as he would with a slate and stylus and instead write the letter F by selecting location 612A, 612D and 612E. The processor 602 may determine that this individual is writing in a reverse-orientation. After one or more characters have been entered by the user, the processor 602 may also determine in which direction the user is writing. The processor 602 may autocorrect and/or teach braille based on the detected input as well as the determined direction and orientation of the writing. The processor 602 may also determine feedback to be provided to a user via the speaker 610.
The memory 604 may store each selected location, character, finished word or the like as it is completed. The selected locations/characters/words/etc. may be displayed on a display, such as the touchscreen 606 or another display, or they may be later accessed by the processor 602 for printing, emailing, additional word processing or the like.
FIG. 7 illustrates a laptop 700 that may be used to teach and/or autocorrect braille. The laptop 700 includes a processor 702, a memory 704, a track pad 708 as an input device and a speaker 710 as an output device. The laptop 700 is coupled to a camera 706 by a cable 712. The cable 712 may be coupled to an I/O port of the laptop 700 such as a USB port, a Firewire port, a Bluetooth port or the like. The processor 702 and the memory 704 may be similar to the processor 402 and the memory 404 of the teaching/autocorrecting device 400. The camera 706 may be coupled to the processor 702 and adapted to detect image data including movement of a stylus 713, movement of a tip 714 of the stylus 713, movement of a user's hand, indentions left on a substrate 715 and/or the like.
The processor 702 may receive this detected image data and perform autocorrecting and/or teaching functions based on the detected image data. In the embodiment illustrated in FIG. 7, the tip 714 of the stylus 713 is colored with a special coloring. The processor 702 may be adapted to distinguish the color of the tip 714 from other colors so that the processor 702 can easily determine the location of the tip 714 relative to the substrate 715. In some embodiments, the camera 706 may include a special lens and/or filter that is adapted to detect the coloring of the tip 714 so that it can be detected more easily.
In the embodiment illustrated in FIG. 7, the substrate 715 is enclosed in a slate 750. The user is writing across the substrate 715 in a reverse direction and with reverse-oriented braille characters. The camera 706 will detect the characters and transmit the image data to the processor 702, which will determine that the user is writing in a reverse direction and with reverse-oriented characters. The processor 702 may perform autocorrecting and/or teaching functions based on the reverse direction and reverse-oriented characters. Had the user been writing in a forward direction and/or with forward-oriented characters, the processor 702 would perform autocorrect and/or teaching functions based on the forward direction and/or the forward-oriented characters. The processor 702 may also determine feedback data to be provided via the speakers 710.
A user may input data to the laptop 700 using the track pad 708 and/or the keyboard 709. In some embodiments, the user may be able to select modes of the laptop 700 using the track pad 708 and/or the keyboard 709. For example, a user may select between an auto correct mode and a teaching mode, between a basic teaching mode and an advanced teaching mode, etc.
The memory 704 may store selected locations, written characters and/or written words and the processor 702 may perform functions with the stored writing, such as send a message as an email or a text, cause the characters and/or words to be output by the display 711, etc. For example, as the user writes braille on the substrate 715, the laptop 700 may display the corresponding characters on the display 711 using a braille format and/or an alphabetical format.
A teacher or other observer may be able to observe the progress of a user via the display 711. For example, in a teaching mode, the display 711 may indicate how well the user is learning by displaying a percentage correct, a number of misspelled words and/or miswritten characters, etc.
FIG. 8 illustrates a system 800 for teaching/autocorrecting braille. The system 800 includes a mobile device 850 and an imaging unit 803. The mobile device 850 includes a processor 852, a memory 854, a display 870, a button 858, a speaker 860 and an antenna 851. The mobile device 850 may also be considered a computing device as it includes a processor and can perform computing functions. In that regard, any device capable of performing computing functions may be regarded as a computing device. The processor 852 and the memory 854 may be similar to the processor 402 and the memory 404.
The button 858 may be used as an input device for operation of the mobile device 850. The speaker 860 may be configured to provide audio data based on signals received from the processor 852. The display 870 may be adapted to output image data based on signals received from the processor 852. The antenna 851 may be coupled to the processor 852 and/or an I/O port and be capable of transmitting and receiving signals from another device having an antenna. The imaging unit 803 may include a camera 806, a connection means 801, a connector 805 coupling the camera 806 to the connection means 801 and an antenna 812.
The connection means 801 may be any connection means capable of connecting to a writing base such as a substrate, a clipboard, a notebook or the like. In some embodiments, the connection means 801 may be a clip, a bracket, a snap connector, a patch of Velcro or the like.
The connector 805 may couple the connection means 801 to the camera 806. In some embodiments, the connector 805 may be partially flexible such that the location and direction of focus of the camera 806 may be physically changed by repositioning the connector 805. When the camera 806 is in a desired position, the connector 805 may resist movement until a sufficient force is exerted on the connector 805. In this way, a user may place the camera 806 in a position in which the camera can optimally detect image data associated with a user writing braille. The processor 852 may detect image data and determine a preferred position of the camera 806. The processor 852 may then instruct the speaker 860 to output feedback instructing the user on the preferred position of the camera 806.
The antenna 812 may be capable of communicating with the antenna 851 as indicated by the connection 829. Image data detected by the camera 806 may be transmitted to the mobile device 850 via the antenna 812 and received at the mobile device 850 via the antenna 851.
In some embodiments, the camera 806 may have a relatively small field of view (FOV) 815. This may allow the camera 806 to more accurately detect image data within the field of view of the camera 806. In the embodiment illustrated in FIG. 8, the substrate 814 is positioned within the FOV 815. The FOV 815 may extend horizontally at an angle 811 and vertically at an angle 813. The angle 811 may be larger than the angle 813 so that a majority of the FOV 815 is directed to the top surface 831 of the substrate 814.
As illustrated, the FOV 815 includes the entire top surface 831 of the substrate 814. However, the FOV 815 does not include much space beyond the top surface 831 of the substrate 814. This allows the camera 806 to detect more detailed image data proximate the top surface 831 of the substrate 814.
The camera 806 may be positioned a distance 821 above the substrate 814. The distance 821 may be selected such that an angle 823 formed between a line perpendicular to the top surface 831 and a center of focus 825 of the camera 806 is relatively small. This allows the camera 806 to detect the location of a finger, a stylus or the like relative to the top surface 831 of the substrate 814 without obstructions, such as the user's hand, finger or the like.
The system 800 may also include a first longitudinal member 816 and a second longitudinal member 818. The longitudinal members 816 and 818 may be adapted to be altered such that a longitudinal distance 820 and a longitudinal distance 822 of the longitudinal members 816 and 818 may be changed. A user may place the longitudinal members 816 and 818 on the substrate 814 adjacent and perpendicular to each other. The camera 806 may detect the longitudinal members 816 and 818 and the processor 852 may determine the size of each cell 824 based on the longitudinal distance 820 and the longitudinal distance 822.
The cell 824 illustrates an area having a height 827 and a width 828 that corresponds to the longitudinal distance 820 and the longitudinal distance 822 of the longitudinal members 816 and 818. By setting the dimensions of the cell 824 using the longitudinal member 816 and the longitudinal member 818, a user may select any desirable cell size for the braille cells.
FIG. 9 illustrates a method 900 to be performed by a processor of a device, such as the processor 402 of the teaching/autocorrecting device 400. The method 900 starts in block 902 where the processor determines if the teaching mode or the auto correct mode is selected based on data received at an input device, such as a button, a microphone and/or a camera.
If the teaching mode is selected, the method 900 proceeds to block 904. In block 904, the processor may determine a word that a user is attempting to write in braille. In some embodiments, the processor may include a list of words associated with a particular learning level, such as basic, intermediate or advanced, and output a word or sentence from the list to the user via an output device so the processor knows which word the user is attempting to write. In some embodiments, a user may input a word or a group of words that he or she would like to write so that the processor knows which word the user is attempting to write. In some embodiments, the processor may not determine a word that a user is attempting to write before the user begins to write. For example, the user may wish to practice writing and start writing in braille. As the user is writing, the processor may determine the word that the user is attempting to write as the user is writing the word or after the user has written the word.
In block 906, the sensor detects data corresponding to at least one braille character. The sensor may then transmit the detected data to the processor which may determine which braille character is written based on the detected sensor data. In some instances, the processor may not be capable of determining which braille character has been written until at least two characters have been written, as one braille character written in a reverse-oriented manner may be the same as another braille character written in a forward-oriented manner. In these instances, the method 900 may proceed or it may remain at this block until the character can be determined.
In block 908, the processor may determine a direction that the word is being written and/or the orientation of the braille character. This may be determined based a known word (if the word the user is attempting to write is known), on a comparison of the written character to forward-oriented and/or reverse-oriented braille characters, on the location of the initial braille character or the like.
In some embodiments, the user may enter braille characters one at a time on a single cell (such as using the smart mobile device 600). The processor may determine the direction that the word is being written based on the orientation of the character and how the word is being spelled. For example, if the user is attempting to spell “car,” the processor may determine that the word is being written in a forward direction if the user writes the braille character for “C” first and may determine that the word is being written in a reverse direction if the user first writes the character for “R.” In other embodiments, the device may include a forward/reverse setting such that the user can select whether the writing will be in the forward or reverse direction and/or the forward or reverse orientation.
In block 910, the processor determines if the at least one braille character corresponds to the correct spelling of the word that the user is attempting to write. As the processor detects each braille character, it may compare the detected characters to the correct spelling of the word. This can be done in any writing style—forward or reverse writing and/or forward or reverse-oriented characters.
In order to determine if the word is misspelled, the processor needs to know the direction in which the word is being written and the orientation of the braille characters. In some embodiments, more than one braille character must be recognized before this determination can be made. With brief reference to FIG. 1B, some braille characters are mirror images of each other, such as the braille characters corresponding to “H” and “J”, so the processor may not know whether the user intended to write an “H” or a “J” until additional characters are detected in order to know a direction of writing.
The processor may also compare the selected locations of each written character to the correct locations corresponding to the correct writing of the character. The processor can determine if incorrect locations are selected and/or if correct locations are not selected for the character. This can be done in any writing style—forward or reverse writing and/or forward or reverse-oriented characters. If the user selects locations that do not match the correct locations, the processor may determine to provide feedback informing the user of the incorrect locations.
In block 912, the processor may determine feedback to be provided to the user based on whether the at least one braille character corresponds to the correct spelling of the word and/or the correct locations are selected for each character. In some embodiments, the output device may give a verbal indication of whether the spelling is correct or not, a verbal indication of whether one or more incorrect locations have been selected and/or feedback indicating correct locations that have not been selected. In some embodiments, the output device may provide haptic feedback indicating whether the at least one braille character corresponds to the correct spelling of the word. The processor may determine to provide feedback as each wrong letter is inserted or may determine to provide feedback after the entire word, phrase, sentence, etc. is written.
Returning to block 902, if it is determined that the auto correct mode has been selected, the method 900 proceeds to block 914. In block 914, the sensor may detect data corresponding to at least one braille character. This data may be transmitted to the processor which may then determine which character is being written.
In block 916, the processor may determine a direction that the selected word is being written based on the sensed data. This determination may be made based on the location of the at least one braille character and/or the orientation of the at least one braille character. Block 916 may function in a similar manner as the block 908.
In block 918, the processor may determine at least one potential word that the user may be trying to spell using the at least one braille character. This determination may be made based on a comparison of the detected at least one braille character to a database to determine a match. In some embodiments, the processor uses an algorithm to select the potential words that is based on a number of times each potential word has been used, whether a potential word fits contextually with previously-written words or sentences, whether a potential word fits grammatically (i.e., if the previous words refer to a plural subject, then the verb may be a plural verb) or any other suitable factors.
In some embodiments, the memory may include a database corresponding to both orientations of the braille characters. The memory may also include a database including forward and reverse spellings of words. Once the processor knows the orientation and direction in which the word is being written, it may compare the detected braille character to at least one of the databases to determine which character is being written and potentially which word is being written. In some embodiments, the memory may include only one database that corresponds to one direction of spelling and one orientation. In these embodiments, the processor may convert the at least one braille character to match the one direction of spelling and one orientation and then compare the converted at least one braille character to the database.
The processor may begin to select potential words after the first braille character has been recognized, after a predetermined number of characters have been recognized, whether a potential word has a high likelihood of being correct or the like. The processor may determine any number of potential words based the detected at least one braille character and it may rank the potential words based on the likelihood that they are the selected word.
In some embodiments, the processor may correct the spelling of words after they have already been written. For example, if the user spells “cars” as “caes,” the processor may compare the letters “caes” to a database to determine partial matches and the likelihood of each partial match being correct. The likelihood may be determined based on a number of matching characters, the location of each character within the word, the context of previous words written by the user, the similarity of dot patterns between the written characters and potential characters or the like.
In block 920, after the processor has determined at least one potential word, the processor may determine to provide feedback to the user based on the at least one potential word. In some embodiments, the feedback is provided based on the likelihood that at least one potential word is the correct word. For example, the processor may determine not to provide feedback until at least one potential word has a likelihood at or above a predetermined percentage. The processor may determine whether to only provide one potential word or multiple potential words based on the number of potential words, the likelihood of each potential word being the correct word, a user preference, another algorithm or the like. The processor may also determine whether to provide verbal feedback, haptic feedback or another type of feedback (such as visual feedback for a teacher or parent).
In some embodiments, a braille device capable of forming words and/or characters in braille (i.e., raising certain locations in at least one braille cell) is coupled to the processor. In these embodiments, the processor may generate one or more potential letters and/or words to be output by the braille device so that the user may touch the braille device and read the potential word or words.
In some embodiments, the processor may determine, based on user input or an algorithm, that the word should be autocorrected without user feedback. For example, if the likelihood that a potential word is the correct word is above a predetermined threshold, then the processor may determine to insert the word. In these embodiments, the processor may determine whether or not to provide feedback indicating that the word has been changed.
In block 922, the processor may receive an indication of whether one of the at least one potential words is the correct word. In some embodiments, the processor may provide only one word as feedback and the user may indicate whether it is the correct word by using the input device, by performing a gesture to be detected by the sensor, by speaking a “yes” or “no,” or the like. In some embodiments, the processor may determine to provide more than one word as feedback and provide them one at a time such that the user can select the correct word as it is being output.
In block 924, if the user indicated that a potential word is the correct word, the processor may complete and/or correct the selected word. For example, the memory may store each character and word that the user is writing and then store the additional letters that spell the selected word and/or replace the misspelled word with the correctly spelled word. The processor may also place the correct spelling in an email, text, word processing document or the like.
If the input by the user indicated that no potential word is the correct word, the method 900 may return to block 914. In some embodiments, the processor may continue to output potential words until a potential word is selected by the user.
FIG. 10A illustrates a phrase written using reverse-orientation braille characters. FIG. 10A includes six braille cells 1000, 1002, 1004, 1006, 1008 and 1010 corresponding to the letters “T H E C A R” in that order.
FIG. 10B illustrates an exemplary use of the teaching mode blocks of the method 900 for reverse direction and reverse-oriented braille writing. The device may output the phrase “the car” via a speaker or other output device and request that the user write the phrase in braille. In FIG. 10B, the user may be writing in reverse order with reverse-oriented braille characters. The user may begin in cell 1020 by correctly writing the braille character corresponding to a reverse-oriented “R.” In cell 1022, the user may again correctly write the braille character corresponding to a reverse-oriented “A”.
In cell 1024, the user may incorrectly write a reverse-oriented “E.” At this point, the processor may determine that the user has incorrectly spelled the word “CAR.” The processor may then indicate to the user that the user has incorrectly spelled the word and/or may indicate to the user that the user has written the braille character corresponding to a reverse-oriented “E” instead of “C.” In some embodiments, the processor may provide feedback to the user informing the user of the correct way to write the braille character corresponding to a reverse-oriented “C,” such as by generating feedback indicating the correct locations that correspond to the letter “C.”
FIG. 10C illustrates an exemplary use of the autocorrect mode blocks of the method 900 for reverse direction and reverse-oriented braille writing. In cells 1050 and 1052, the user may correctly write the letters corresponding to “R” and “A.” At this point, the processor may determine a list of potential words that include the word “CAR.” The processor may determine that “CAR” has the highest likelihood of being the correct word. The device may then provide feedback indicating that “CAR” is a potential word. In response, the processor may fill cell 1054 with the letter “C.”
Similarly, in blocks 1056 and 1058, the user may input the braille characters corresponding to the letters “E” and “H.” At this point, the processor may determine a list of potential words including the word “THE.” The device may then provide feedback indicating that a potential word is “THE.” In response, the user may provide an indication that “THE” is the correct word. The device may then input a reverse-oriented “T” into the cell 1060.
FIG. 10D illustrates an exemplary use of the autocorrect mode blocks of the method 900 for forward direction and reverse-oriented braille writing. The user may begin to write the braille characters corresponding to the letters “T” and “H” in cells 1070 and 1072. The processor may then determine that a potential word is “THE” and output feedback to the user indicating that “THE” is a potential word. The user may indicate that “THE” is the correct word and the processor may insert the braille character corresponding to “E” in cell 1074.
The user may then write the braille characters corresponding to the letters “C,” “A” and “W” in cells 1076, 1078 and 1080. In response, the processor may look up “C A W” in a database to determine if the letters correspond to a correct spelling of a word. The processor may determine that this string of characters does not correspond to a word in the database. In response, the processor may determine a potential word that the user could have meant instead of the letters “C A W.” The processor may determine that “CAR” is a potential word and generate feedback indicating that “CAR” is a potential word. The user may respond to the feedback with an indication that “CAR” is correct. In response, the processor may replace the braille character corresponding to the reverse-oriented “W” in cell 1080 with a braille character corresponding to a reverse-oriented “R.”
Exemplary embodiments of the methods/systems have been disclosed in an illustrative style. Accordingly, the terminology employed throughout should be read in a non-limiting manner. Although minor modifications to the teachings herein will occur to those well versed in the art, it shall be understood that what is intended to be circumscribed within the scope of the patent warranted hereon are all such embodiments that reasonably fall within the scope of the advancement to the art hereby contributed, and that that scope shall not be restricted, except in light of the appended claims and their equivalents.
|
__label__pos
| 0.940271 |
Why does this work?
Tell us what’s happening:
my code works
i was trying to test what an error would look like if i input the wrong type of input, but it compiled
why?
Your code so far
const Items = (props) => {
return <h1>Current Quantity of Items in Cart: {props.quantity}</h1>
};
// change code below this line
//import PropTypes from 'prop-types';
Items.propTypes = {quantity: PropTypes.number.isRequired};
// change code above this line
Items.defaultProps = {
quantity: 0
};
class ShoppingCart extends React.Component {
constructor(props) {
super(props);
}
render() {
return <Items quantity={'dude'}/>
}
};
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36.
Challenge: Use PropTypes to Define the Props You Expect
Link to the challenge:
https://www.freecodecamp.org/learn/front-end-libraries/react/use-proptypes-to-define-the-props-you-expect
It should “compile” (it isn’t really compiling anything, but I guess can treat is doing that)
a. The error warning only appears in the browser console
b. On a phone so can’t check this, but only appears using a development build in a development environment, and depending how the very specific test environment has been set up on FCC, it might not error anyway
|
__label__pos
| 0.999439 |
34
I have tried to include the header file bits/stdc++ in my C++ code, but it seems the compiler doesn't support it. Is there any way to make it work?
I use OS X Yosemite 10.10.2 and Xcode 6.1.1.
9
• 6
You aren't supposed to include this header directly. Why do you think you need it? Mar 11 '15 at 18:06
• 1
@Omar Except you´ll probably get notably increased compile time. Use the standard headers necessary for your used functions/classes, and not some internal G++ file
– deviantfan
Mar 11 '15 at 18:13
• 1
@Omar "I used to include it instead of ..." That's wrong. The headers appearing in the bits directory are meant to bind the c++ compiler implementation with your actual machine and OS environment. These are usually included by the higher level implementations of the c++ standard library headers, sometimes only under certain conditions (#ifdef's) Mar 11 '15 at 18:13
• 1
Recommended reading: Why should I not #include <bits/stdc++.h>? Jun 15 '19 at 13:35
• 1
tl;dr your requirement/need is wrong and this is why. No. Jun 15 '19 at 13:36
12 Answers 12
36
You can do it by copying stdc++.h file from here: https://gist.github.com/reza-ryte-club/97c39f35dab0c45a5d924dd9e50c445f
Then you can include the file in your c++ file like this:
//suppose the file is in your home folder, here my username is reza
#include "/Users/reza/stdc++.h"
1
• This is a bad advice, hash including the full path is an atrocious act Jun 16 at 10:02
24
Since, bits/stdc++ is a GNU GCC extension, whereas OSX uses the clang compiler.
You have to create bits directory inside /usr/local/include and then make a header file stdc++.h inside bits and paste the contents of this gist inside it. Then, it should compile as expected.
Since, /usr directory is hidden by default on Mac OSX.
1. Open Finder.
2. Click Go on menu bar then click Go to folder or Press Command+Shift+G directly.
3. Enter the path /usr/local/include
4. Now proceed as mentioned above.
(UPDATE: For latest OS X you need to make folder include inside local and make bits folder inside include folder and then copy paste the code inside bits folder.)
1
• 2
with the above path , not working for me. But with this path it is working "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/"
– GvSharma
Jul 22 '19 at 12:46
23
Mac OS X 10.9+ no longer uses GCC/libstdc++ but uses libc++ and Clang.
After the XCode 6.0.1 update the headers are now located here:
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1
so, get the stdc++.h file from here,then creat bits directory in the above long address, and copy the file stdc++.h to the bits directory.
1
• 1
At the very least, don't call it "bits/stdc++.h". That's the name of an implementation header in libstdc++. Call it "myHeaderWithAllOfTheStdlib" or something Jun 15 '19 at 13:38
10
You can't. X-Code uses LLVM Toolchain with Clang for the compiler, while <bits/stdc++> is specific to the GNU Compiler Toolchain.
Second, you shouldn't be using that header in the first place, as stated by everyone else.
1
• 3
But by creating a folder in "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/" named bits, i can add the stdc++.h and it worked Jun 9 '19 at 11:47
9
Before Adding the bits/stdc++.h to your mac os platform, the First things are to figure out where your include files are present. To figure out which include file is getting utilized within you mac environment.
• Run this command in terminal:
echo "" | gcc -xc - -v -E
This will provide the details of gcc environment in your platform
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.7.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
"/Library/Developer/......."
ignoring nonexistent directory
"/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/local/include"
ignoring nonexistent directory
"/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/Library/Frameworks"
#include "..." search starts here:
#include <...> search starts here:
/usr/local/include
/Library/Developer/CommandLineTools/usr/lib/clang/10.0.1/include
/Library/Developer/CommandLineTools/usr/include
/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include
/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks (framework directory)
End of search list.
# 1 "<stdin>"
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 361 "<built-in>" 3
# 1 "<command line>" 1
# 1 "<built-in>" 2
# 1 "<stdin>" 2
• Go to the include path. ex: /usr/local/include Create a bits folder and add stdc++.h file.
1
• 1
Thank you. This clearly helped. It's much needed for competitive programming to just import <bits/stdc++.h> Jun 19 at 18:34
1
1.Download the stdc++.h file from https://gist.github.com/eduarc/6....
2.In Finder CTRL + SHIFT +G and open /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/
3.Create the folder bits and copy the downloaded file here.
1
1
1. Open Finder.
2. Click Go on menu bar then click Go to folder or Press Command+Shift+G directly.
3. Enter the path or c/p this path directly
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1
1. Then create bits directory in the above long address.
2. Now, get the stdc++.h file from [here][1].
3. and copy the file stdc++.h to the bits directory.
1
The standard GNU compiler, G++ Does not directly support this header so we include it in the required location using the following steps :
1. cd /usr/local/include
2. mkdir bits
3. nano stdc++.h
then copy the code of the header file from here .
Hope that helps ! :D
1
Simply create a header file like bitsStdcpp.hpp file in your file directory, add the following code in that file and use #include "bitsStdcpp.hpp" instead of #include <bits/stdc++.h>
#include <stdio.h>
using namespace std;
#ifndef _GLIBCXX_NO_ASSERT
#include <cassert>
#endif
#include <cctype>
#include <cerrno>
#include <cfloat>
#include <ciso646>
#include <climits>
#include <clocale>
#include <cmath>
#include <csetjmp>
#include <csignal>
#include <cstdarg>
#include <cstddef>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#if __cplusplus >= 201103L
#include <ccomplex>
#include <cfenv>
#include <cinttypes>
#include <cstdbool>
#include <cstdint>
#include <ctgmath>
#include <cwchar>
#include <cwctype>
#endif
// C++
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#if __cplusplus >= 201103L
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#endif /* bitsStdcpp_hpp */
0
1. Open Finder.
2. Click Go on menu bar then click Go to folder or Press Command+Shift+G directly.
3. Enter the path /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1
Now, get the stdc++.h file from here, then create bits directory in the above long address, and copy the file stdc++.h to the bits directory.
1
• No, this is monumentally silly. That's a header from Linux GCC 4.8, not Mac Clang <whatever your version is>. Do not do this I cannot stress it enough. Jun 15 '19 at 13:37
0
1. Copy the content of this header file to clipboard from Link: https://gist.github.com/reza-ryte-club/97c39f35dab0c45a5d924dd9e50c445f
2. Run following in terminal :
• mkdir /usr/local/include/bits
• vim /usr/local/include/bits/stdc++.h
• Switch to insert mode (press i) and Paste clipboard content
• Save/Exit (Esc + : + w + q + Enter)
3. Try compliation of your source code
0
The reason for that as stated by others also is because Mac OS X 10.9+ no longer uses GCC/libstdc++ but uses libc++ and Clang.
So one alternative way to fix that is to make your default mac compiler from clang to gcc.
As you can see in this image, the default mac compiler is clang.
So, what we can do here is install gcc!
Step 1
Run the following command to install gcc (assuming homebrew is installed on your machine):
$ brew install gcc
Step 2
After gcc is installed note the version by running the following command
$ gcc --version
Step 3
So now when we run g++-version it will use the gcc compiler, but we want it to use gcc compiler when we run g++. For that we are going to create a symbolic link of g++ to gcc:
$ cd /usr/local/bin
Now create a symbolic link by running this command:
$ ln -s g++-[version] g++
(Replace version by your current installed.)
Now restart the terminal for the changes to take effect and run g++ , it will use gcc compiler. It should look like this.
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.913393 |
DependentTransaction Class
Describes a clone of a transaction providing guarantee that the transaction cannot be committed until the application comes to rest regarding work on the transaction. This class cannot be inherited.
Namespace: System.Transactions
Assembly: System.Transactions (in System.Transactions.dll)
System.Object
System.Transactions.Transaction
System.Transactions.DependentTransaction
[SerializableAttribute]
public sealed class DependentTransaction : Transaction
NameDescription
System_CAPS_pubpropertyIsolationLevel
Gets the isolation level of the transaction.(Inherited from Transaction.)
System_CAPS_pubpropertyPromoterType
Uniquely identifies the format of the byte[] returned by the Promote method when the transaction is promoted.(Inherited from Transaction.)
System_CAPS_pubpropertyTransactionInformation
Retrieves additional information about a transaction.(Inherited from Transaction.)
NameDescription
System_CAPS_pubmethodClone()
Creates a clone of the transaction.(Inherited from Transaction.)
System_CAPS_pubmethodComplete()
Attempts to complete the dependent transaction.
System_CAPS_pubmethodDependentClone(DependentCloneOption)
Creates a dependent clone of the transaction.(Inherited from Transaction.)
System_CAPS_pubmethodDispose()
Releases the resources that are held by the object.(Inherited from Transaction.)
System_CAPS_pubmethodEnlistDurable(Guid, IEnlistmentNotification, EnlistmentOptions)
Enlists a durable resource manager that supports two phase commit to participate in a transaction.(Inherited from Transaction.)
System_CAPS_pubmethodEnlistDurable(Guid, ISinglePhaseNotification, EnlistmentOptions)
Enlists a durable resource manager that supports single phase commit optimization to participate in a transaction.(Inherited from Transaction.)
System_CAPS_pubmethodEnlistPromotableSinglePhase(IPromotableSinglePhaseNotification)
Enlists a resource manager that has an internal transaction using a promotable single phase enlistment (PSPE). (Inherited from Transaction.)
System_CAPS_pubmethodEnlistPromotableSinglePhase(IPromotableSinglePhaseNotification, Guid)
Enlists a resource manager that has an internal transaction using a promotable single phase enlistment (PSPE).(Inherited from Transaction.)
System_CAPS_pubmethodEnlistVolatile(IEnlistmentNotification, EnlistmentOptions)
Enlists a volatile resource manager that supports two phase commit to participate in a transaction.(Inherited from Transaction.)
System_CAPS_pubmethodEnlistVolatile(ISinglePhaseNotification, EnlistmentOptions)
Enlists a volatile resource manager that supports single phase commit optimization to participate in a transaction.(Inherited from Transaction.)
System_CAPS_pubmethodEquals(Object)
Determines whether this transaction and the specified object are equal.(Inherited from Transaction.)
System_CAPS_pubmethodGetHashCode()
Returns the hash code for this instance.(Inherited from Transaction.)
System_CAPS_pubmethodGetPromotedToken()
Gets the byte[] returned by the Promote method when the transaction is promoted.(Inherited from Transaction.)
System_CAPS_pubmethodGetType()
Gets the Type of the current instance.(Inherited from Object.)
System_CAPS_pubmethodPromoteAndEnlistDurable(Guid, IPromotableSinglePhaseNotification, ISinglePhaseNotification, EnlistmentOptions)
[Supported in the .NET Framework 4.5.2 and later versions]
Promotes and enlists a durable resource manager that supports two phase commit to participate in a transaction.(Inherited from Transaction.)
System_CAPS_pubmethodRollback()
Rolls back (aborts) the transaction.(Inherited from Transaction.)
System_CAPS_pubmethodRollback(Exception)
Rolls back (aborts) the transaction.(Inherited from Transaction.)
System_CAPS_pubmethodSetDistributedTransactionIdentifier(IPromotableSinglePhaseNotification, Guid)
Sets the distributed transaction identifier generated by the non-MSDTC promoter.(Inherited from Transaction.)
System_CAPS_pubmethodToString()
Returns a string that represents the current object.(Inherited from Object.)
NameDescription
System_CAPS_pubeventTransactionCompleted
Indicates that the transaction is completed.(Inherited from Transaction.)
NameDescription
System_CAPS_pubinterfaceSystem_CAPS_privmethodISerializable.GetObjectData(SerializationInfo, StreamingContext)
Gets a SerializationInfo with the data required to serialize this transaction. (Inherited from Transaction.)
The DependentTransaction is a clone of a Transaction object created using the DependentClone method. Its sole purpose is to allow the application to come to rest and guarantee that the transaction cannot commit while work is still being performed on the transaction (for example, on a worker thread).
When the work done within the cloned transaction is finally complete and ready to be committed, it can inform the creator of the transaction using the Complete method. Thus you can preserve the consistency and correctness of data.
The DependentCloneOption enumeration is used to determine the behavior on commit. This behavior control allows an application to come to rest, as well as provides concurrency support. For more information on how this enumeration is used, see Managing Concurrency with DependentTransaction.
The following example shows you how to create a dependent transaction.
static void Main(string[] args)
{
try
{
using (TransactionScope scope = new TransactionScope())
{
// Perform transactional work here.
//Queue work item
ThreadPool.QueueUserWorkItem(new WaitCallback(WorkerThread), Transaction.Current.DependentClone(DependentCloneOption.BlockCommitUntilComplete));
//Display transaction information
Console.WriteLine("Transaction information:");
Console.WriteLine("ID: {0}", Transaction.Current.TransactionInformation.LocalIdentifier);
Console.WriteLine("status: {0}", Transaction.Current.TransactionInformation.Status);
Console.WriteLine("isolationlevel: {0}", Transaction.Current.IsolationLevel);
//Call Complete on the TransactionScope based on console input
ConsoleKeyInfo c;
while (true)
{
Console.Write("Complete the transaction scope? [Y|N] ");
c = Console.ReadKey();
Console.WriteLine();
if ((c.KeyChar == 'Y') || (c.KeyChar == 'y'))
{
//Call complete on the scope
scope.Complete();
break;
}
else if ((c.KeyChar == 'N') || (c.KeyChar == 'n'))
{
break;
}
}
}
}
catch (System.Transactions.TransactionException ex)
{
Console.WriteLine(ex);
}
catch
{
Console.WriteLine("Cannot complete transaction");
throw;
}
}
private static void WorkerThread(object transaction)
{
//Create a DependentTransaction from the object passed to the WorkerThread
DependentTransaction dTx = (DependentTransaction)transaction;
//Sleep for 1 second to force the worker thread to delay
Thread.Sleep(1000);
//Pass the DependentTransaction to the scope, so that work done in the scope becomes part of the transaction passed to the worker thread
using (TransactionScope ts = new TransactionScope(dTx))
{
//Perform transactional work here.
//Call complete on the transaction scope
ts.Complete();
}
//Call complete on the dependent transaction
dTx.Complete();
}
.NET Framework
Available since 2.0
This type is thread safe.
System.Transactions Namespace
Managing Concurrency with DependentTransaction
Return to top
Show:
|
__label__pos
| 0.530706 |
< prev index next >
src/hotspot/share/include/jvm.h
Print this page
154 JVM_LoadZipLibrary();
155
156 JNIEXPORT void * JNICALL
157 JVM_LoadLibrary(const char *name, jboolean throwException);
158
159 JNIEXPORT void JNICALL
160 JVM_UnloadLibrary(void * handle);
161
162 JNIEXPORT void * JNICALL
163 JVM_FindLibraryEntry(void *handle, const char *name);
164
165 JNIEXPORT jboolean JNICALL
166 JVM_IsSupportedJNIVersion(jint version);
167
168 JNIEXPORT jobjectArray JNICALL
169 JVM_GetVmArguments(JNIEnv *env);
170
171 JNIEXPORT jboolean JNICALL
172 JVM_IsPreviewEnabled(void);
173
174 JNIEXPORT jboolean JNICALL
175 JVM_IsContinuationsSupported(void);
176
177 JNIEXPORT jboolean JNICALL
178 JVM_IsForeignLinkerSupported(void);
179
180 JNIEXPORT void JNICALL
181 JVM_InitializeFromArchive(JNIEnv* env, jclass cls);
182
183 JNIEXPORT void JNICALL
184 JVM_RegisterLambdaProxyClassForArchiving(JNIEnv* env, jclass caller,
185 jstring interfaceMethodName,
186 jobject factoryType,
187 jobject interfaceMethodType,
188 jobject implementationMember,
189 jobject dynamicMethodType,
190 jclass lambdaProxyClass);
191
192 JNIEXPORT jclass JNICALL
193 JVM_LookupLambdaProxyClassFromArchive(JNIEnv* env, jclass caller,
405 * JVM_GetCallerClass. The Method.invoke and other frames due to
406 * reflection machinery are skipped.
407 *
408 * The caller is expected to be marked with
409 * jdk.internal.reflect.CallerSensitive. The JVM will throw an
410 * error if it is not marked properly.
411 */
412 JNIEXPORT jclass JNICALL
413 JVM_GetCallerClass(JNIEnv *env);
414
415
416 /*
417 * Find primitive classes
418 * utf: class name
419 */
420 JNIEXPORT jclass JNICALL
421 JVM_FindPrimitiveClass(JNIEnv *env, const char *utf);
422
423
424 /*
425 * Find a class from a boot class loader. Returns NULL if class not found.
426 */
427 JNIEXPORT jclass JNICALL
428 JVM_FindClassFromBootLoader(JNIEnv *env, const char *name);
429
430 /*
431 * Find a class from a given class loader. Throws ClassNotFoundException.
432 * name: name of class
433 * init: whether initialization is done
434 * loader: class loader to look up the class. This may not be the same as the caller's
435 * class loader.
436 * caller: initiating class. The initiating class may be null when a security
437 * manager is not installed.
438 */
439 JNIEXPORT jclass JNICALL
440 JVM_FindClassFromCaller(JNIEnv *env, const char *name, jboolean init,
441 jobject loader, jclass caller);
442
443 /*
444 * Find a class from a given class.
445 */
556 JVM_IsInterface(JNIEnv *env, jclass cls);
557
558 JNIEXPORT jobjectArray JNICALL
559 JVM_GetClassSigners(JNIEnv *env, jclass cls);
560
561 JNIEXPORT void JNICALL
562 JVM_SetClassSigners(JNIEnv *env, jclass cls, jobjectArray signers);
563
564 JNIEXPORT jobject JNICALL
565 JVM_GetProtectionDomain(JNIEnv *env, jclass cls);
566
567 JNIEXPORT jboolean JNICALL
568 JVM_IsArrayClass(JNIEnv *env, jclass cls);
569
570 JNIEXPORT jboolean JNICALL
571 JVM_IsPrimitiveClass(JNIEnv *env, jclass cls);
572
573 JNIEXPORT jboolean JNICALL
574 JVM_IsHiddenClass(JNIEnv *env, jclass cls);
575
576 JNIEXPORT jint JNICALL
577 JVM_GetClassModifiers(JNIEnv *env, jclass cls);
578
579 JNIEXPORT jobjectArray JNICALL
580 JVM_GetDeclaredClasses(JNIEnv *env, jclass ofClass);
581
582 JNIEXPORT jclass JNICALL
583 JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass);
584
585 JNIEXPORT jstring JNICALL
586 JVM_GetSimpleBinaryName(JNIEnv *env, jclass ofClass);
587
588 /* Generics support (JDK 1.5) */
589 JNIEXPORT jstring JNICALL
590 JVM_GetClassSignature(JNIEnv *env, jclass cls);
591
592 /* Annotations support (JDK 1.5) */
593 JNIEXPORT jbyteArray JNICALL
594 JVM_GetClassAnnotations(JNIEnv *env, jclass cls);
595
1111 JNIEXPORT void JNICALL
1112 JVM_RawMonitorExit(void *mon);
1113
1114 /*
1115 * java.lang.management support
1116 */
1117 JNIEXPORT void* JNICALL
1118 JVM_GetManagement(jint version);
1119
1120 /*
1121 * com.sun.tools.attach.VirtualMachine support
1122 *
1123 * Initialize the agent properties with the properties maintained in the VM.
1124 */
1125 JNIEXPORT jobject JNICALL
1126 JVM_InitAgentProperties(JNIEnv *env, jobject agent_props);
1127
1128 JNIEXPORT jstring JNICALL
1129 JVM_GetTemporaryDirectory(JNIEnv *env);
1130
1131 /* Generics reflection support.
1132 *
1133 * Returns information about the given class's EnclosingMethod
1134 * attribute, if present, or null if the class had no enclosing
1135 * method.
1136 *
1137 * If non-null, the returned array contains three elements. Element 0
1138 * is the java.lang.Class of which the enclosing method is a member,
1139 * and elements 1 and 2 are the java.lang.Strings for the enclosing
1140 * method's name and descriptor, respectively.
1141 */
1142 JNIEXPORT jobjectArray JNICALL
1143 JVM_GetEnclosingMethodInfo(JNIEnv* env, jclass ofClass);
1144
1145 /*
1146 * Virtual thread support.
1147 */
1148 JNIEXPORT void JNICALL
1149 JVM_VirtualThreadStart(JNIEnv* env, jobject vthread);
1150
154 JVM_LoadZipLibrary();
155
156 JNIEXPORT void * JNICALL
157 JVM_LoadLibrary(const char *name, jboolean throwException);
158
159 JNIEXPORT void JNICALL
160 JVM_UnloadLibrary(void * handle);
161
162 JNIEXPORT void * JNICALL
163 JVM_FindLibraryEntry(void *handle, const char *name);
164
165 JNIEXPORT jboolean JNICALL
166 JVM_IsSupportedJNIVersion(jint version);
167
168 JNIEXPORT jobjectArray JNICALL
169 JVM_GetVmArguments(JNIEnv *env);
170
171 JNIEXPORT jboolean JNICALL
172 JVM_IsPreviewEnabled(void);
173
174 JNIEXPORT jboolean JNICALL
175 JVM_IsValhallaEnabled(void);
176
177 JNIEXPORT jboolean JNICALL
178 JVM_IsContinuationsSupported(void);
179
180 JNIEXPORT jboolean JNICALL
181 JVM_IsForeignLinkerSupported(void);
182
183 JNIEXPORT void JNICALL
184 JVM_InitializeFromArchive(JNIEnv* env, jclass cls);
185
186 JNIEXPORT void JNICALL
187 JVM_RegisterLambdaProxyClassForArchiving(JNIEnv* env, jclass caller,
188 jstring interfaceMethodName,
189 jobject factoryType,
190 jobject interfaceMethodType,
191 jobject implementationMember,
192 jobject dynamicMethodType,
193 jclass lambdaProxyClass);
194
195 JNIEXPORT jclass JNICALL
196 JVM_LookupLambdaProxyClassFromArchive(JNIEnv* env, jclass caller,
408 * JVM_GetCallerClass. The Method.invoke and other frames due to
409 * reflection machinery are skipped.
410 *
411 * The caller is expected to be marked with
412 * jdk.internal.reflect.CallerSensitive. The JVM will throw an
413 * error if it is not marked properly.
414 */
415 JNIEXPORT jclass JNICALL
416 JVM_GetCallerClass(JNIEnv *env);
417
418
419 /*
420 * Find primitive classes
421 * utf: class name
422 */
423 JNIEXPORT jclass JNICALL
424 JVM_FindPrimitiveClass(JNIEnv *env, const char *utf);
425
426
427 /*
428 * Find a class from a boot class loader. Returns nullptr if class not found.
429 */
430 JNIEXPORT jclass JNICALL
431 JVM_FindClassFromBootLoader(JNIEnv *env, const char *name);
432
433 /*
434 * Find a class from a given class loader. Throws ClassNotFoundException.
435 * name: name of class
436 * init: whether initialization is done
437 * loader: class loader to look up the class. This may not be the same as the caller's
438 * class loader.
439 * caller: initiating class. The initiating class may be null when a security
440 * manager is not installed.
441 */
442 JNIEXPORT jclass JNICALL
443 JVM_FindClassFromCaller(JNIEnv *env, const char *name, jboolean init,
444 jobject loader, jclass caller);
445
446 /*
447 * Find a class from a given class.
448 */
559 JVM_IsInterface(JNIEnv *env, jclass cls);
560
561 JNIEXPORT jobjectArray JNICALL
562 JVM_GetClassSigners(JNIEnv *env, jclass cls);
563
564 JNIEXPORT void JNICALL
565 JVM_SetClassSigners(JNIEnv *env, jclass cls, jobjectArray signers);
566
567 JNIEXPORT jobject JNICALL
568 JVM_GetProtectionDomain(JNIEnv *env, jclass cls);
569
570 JNIEXPORT jboolean JNICALL
571 JVM_IsArrayClass(JNIEnv *env, jclass cls);
572
573 JNIEXPORT jboolean JNICALL
574 JVM_IsPrimitiveClass(JNIEnv *env, jclass cls);
575
576 JNIEXPORT jboolean JNICALL
577 JVM_IsHiddenClass(JNIEnv *env, jclass cls);
578
579 JNIEXPORT jboolean JNICALL
580 JVM_IsIdentityClass(JNIEnv *env, jclass cls);
581
582 JNIEXPORT jboolean JNICALL
583 JVM_IsImplicitlyConstructibleClass(JNIEnv *env, jclass cls);
584
585 JNIEXPORT jint JNICALL
586 JVM_GetClassModifiers(JNIEnv *env, jclass cls);
587
588 JNIEXPORT jobjectArray JNICALL
589 JVM_GetDeclaredClasses(JNIEnv *env, jclass ofClass);
590
591 JNIEXPORT jclass JNICALL
592 JVM_GetDeclaringClass(JNIEnv *env, jclass ofClass);
593
594 JNIEXPORT jstring JNICALL
595 JVM_GetSimpleBinaryName(JNIEnv *env, jclass ofClass);
596
597 /* Generics support (JDK 1.5) */
598 JNIEXPORT jstring JNICALL
599 JVM_GetClassSignature(JNIEnv *env, jclass cls);
600
601 /* Annotations support (JDK 1.5) */
602 JNIEXPORT jbyteArray JNICALL
603 JVM_GetClassAnnotations(JNIEnv *env, jclass cls);
604
1120 JNIEXPORT void JNICALL
1121 JVM_RawMonitorExit(void *mon);
1122
1123 /*
1124 * java.lang.management support
1125 */
1126 JNIEXPORT void* JNICALL
1127 JVM_GetManagement(jint version);
1128
1129 /*
1130 * com.sun.tools.attach.VirtualMachine support
1131 *
1132 * Initialize the agent properties with the properties maintained in the VM.
1133 */
1134 JNIEXPORT jobject JNICALL
1135 JVM_InitAgentProperties(JNIEnv *env, jobject agent_props);
1136
1137 JNIEXPORT jstring JNICALL
1138 JVM_GetTemporaryDirectory(JNIEnv *env);
1139
1140 JNIEXPORT jarray JNICALL
1141 JVM_NewNullRestrictedArray(JNIEnv *env, jclass elmClass, jint len);
1142
1143 JNIEXPORT jboolean JNICALL
1144 JVM_IsNullRestrictedArray(JNIEnv *env, jobject obj);
1145
1146 /* Generics reflection support.
1147 *
1148 * Returns information about the given class's EnclosingMethod
1149 * attribute, if present, or null if the class had no enclosing
1150 * method.
1151 *
1152 * If non-null, the returned array contains three elements. Element 0
1153 * is the java.lang.Class of which the enclosing method is a member,
1154 * and elements 1 and 2 are the java.lang.Strings for the enclosing
1155 * method's name and descriptor, respectively.
1156 */
1157 JNIEXPORT jobjectArray JNICALL
1158 JVM_GetEnclosingMethodInfo(JNIEnv* env, jclass ofClass);
1159
1160 /*
1161 * Virtual thread support.
1162 */
1163 JNIEXPORT void JNICALL
1164 JVM_VirtualThreadStart(JNIEnv* env, jobject vthread);
1165
< prev index next >
|
__label__pos
| 0.781954 |
Terrain Transparency - Too many text interpolators
I’ve been following the steps in this wiki to create a section of transparent terrain. When I paste the code into a new Standard Surface Shader, I received this error:
Shader error in ‘Nature/Terrain/Diffuse’: Too many texture interpolators would be used for ForwardBase pass (11 out of max 10) at line 24 (on )
I’ve looked at other questions here, but none of them have a solution to this compiling error. Here is the code from the wiki:
Shader "Nature/Terrain/Diffuse"
{
Properties
{
[HideInInspector] _Control ("Control (RGBA)", 2D) = "red" {}
[HideInInspector] _Splat3 ("Layer 3 (A)", 2D) = "white" {}
[HideInInspector] _Splat2 ("Layer 2 (B)", 2D) = "white" {}
[HideInInspector] _Splat1 ("Layer 1 (G)", 2D) = "white" {}
[HideInInspector] _Splat0 ("Layer 0 (R)", 2D) = "white" {}
//Used in fallback on old cards & base map
[HideInInspector] _MainTex ("BaseMap (RGB)", 2D) = "white" {}
[HideInInspector] _Color ("Main Color", Color) = (1,1,1,1)
}
SubShader
{
Tags
{
"SplatCount" = "4"
"Queue" = "Geometry-100"
"RenderType" = "Opaque"
}
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma surface surf Lambert
struct Input
{
float2 uv_Control : TEXCOORD0;
float2 uv_Splat0 : TEXCOORD1;
float2 uv_Splat1 : TEXCOORD2;
float2 uv_Splat2 : TEXCOORD3;
float2 uv_Splat3 : TEXCOORD4;
};
sampler2D _Control;
sampler2D _Splat0,_Splat1,_Splat2,_Splat3;
void surf (Input IN, inout SurfaceOutput o)
{
fixed4 splat_control = tex2D (_Control, IN.uv_Control);
fixed4 firstSplat = tex2D (_Splat0, IN.uv_Splat0);
fixed3 col;
col = splat_control.r * tex2D (_Splat0, IN.uv_Splat0).rgb;
col += splat_control.g * tex2D (_Splat1, IN.uv_Splat1).rgb;
col += splat_control.b * tex2D (_Splat2, IN.uv_Splat2).rgb;
col += splat_control.a * tex2D (_Splat3, IN.uv_Splat3).rgb;
o.Albedo = col;
o.Alpha = 1;
if(tex2D(_Splat0, IN.uv_Splat0).a == 0)
o.Alpha = 1 - splat_control.r;
else if(tex2D(_Splat1, IN.uv_Splat1).a == 0)
o.Alpha = 1 - splat_control.g;
else if(tex2D(_Splat2, IN.uv_Splat2).a == 0)
o.Alpha = 1 - splat_control.b;
else if(tex2D(_Splat3, IN.uv_Splat3).a == 0)
o.Alpha = 1 - splat_control.a;
}
ENDCG
}
Dependency "AddPassShader" = "Hidden/TerrainEngine/Splatmap/Lightmap-AddPass"
Dependency "BaseMapShader" = "Diffuse"
//Fallback to Diffuse
Fallback "Diffuse"
}
I’m using Unity 5.2.1f1 Personal. How can I fix this error? I’m new to coding shaders.
Your shaders model target does not support that many texture interpolators. You can specify a higher shader model target using #pragma target <shader model>, for example #pragma target 4.0, or you could try to simplify your shader so it fits in target 2.0 or 3.0.
By default, Unity compiles shaders into roughly shader model 2.0 equivalent.
#pragma target 4.0 - compile to DX10 shader model 4.0.
This target is currently only supported by DirectX 11 and XboxOne/PS4 platforms.
Note that all OpenGL-like platforms (including mobile) are treated as “capable of shader model 3.0”. WP8/WinRT platforms (DX11 feature level 9.x) are treated as only capable of shader model 2.0.
Shader "Nature/Terrain/Diffuse"
{
Properties
{
[HideInInspector] _Control("Control (RGBA)", 2D) = "red" {}
[HideInInspector] _Splat3("Layer 3 (A)", 2D) = "white" {}
[HideInInspector] _Splat2("Layer 2 (B)", 2D) = "white" {}
[HideInInspector] _Splat1("Layer 1 (G)", 2D) = "white" {}
[HideInInspector] _Splat0("Layer 0 (R)", 2D) = "white" {}
//Used in fallback on old cards & base map
[HideInInspector] _MainTex("BaseMap (RGB)", 2D) = "white" {}
[HideInInspector] _Color("Main Color", Color) = (1,1,1,1)
}
SubShader
{
Tags
{
"SplatCount" = "4"
"Queue" = "Geometry-100"
"RenderType" = "Opaque"
}
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma surface surf Lambert
#pragma target 4.0
struct Input
{
float2 uv_Control : TEXCOORD0;
float2 uv_Splat0 : TEXCOORD1;
float2 uv_Splat1 : TEXCOORD2;
float2 uv_Splat2 : TEXCOORD3;
float2 uv_Splat3 : TEXCOORD4;
};
sampler2D _Control;
sampler2D _Splat0,_Splat1,_Splat2,_Splat3;
void surf(Input IN, inout SurfaceOutput o)
{
fixed4 splat_control = tex2D(_Control, IN.uv_Control);
fixed4 firstSplat = tex2D(_Splat0, IN.uv_Splat0);
fixed3 col;
col = splat_control.r * tex2D(_Splat0, IN.uv_Splat0).rgb;
col += splat_control.g * tex2D(_Splat1, IN.uv_Splat1).rgb;
col += splat_control.b * tex2D(_Splat2, IN.uv_Splat2).rgb;
col += splat_control.a * tex2D(_Splat3, IN.uv_Splat3).rgb;
o.Albedo = col;
o.Alpha = 1;
if (tex2D(_Splat0, IN.uv_Splat0).a == 0)
o.Alpha = 1 - splat_control.r;
else if (tex2D(_Splat1, IN.uv_Splat1).a == 0)
o.Alpha = 1 - splat_control.g;
else if (tex2D(_Splat2, IN.uv_Splat2).a == 0)
o.Alpha = 1 - splat_control.b;
else if (tex2D(_Splat3, IN.uv_Splat3).a == 0)
o.Alpha = 1 - splat_control.a;
}
ENDCG
}
Dependency "AddPassShader" = "Hidden/TerrainEngine/Splatmap/Lightmap-AddPass"
Dependency "BaseMapShader" = "Diffuse"
//Fallback to Diffuse
Fallback "Diffuse"
}
|
__label__pos
| 0.977703 |
How to implement inheritance in python?
Description
To implement inheritance in python3.
Inheritance:
Like other object oriented language python also does inheritance.
To create new class from base class stats and behaviour.
Base class act as like parent class.
Inherited class act like child class.
It gives the the oops concept of re usability.
Syntax(simple inheritance):
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
#Parent class
class car:
#parent class method
def models(self):
print(‘Four wheel’)
#child class
class bike(car):
#child class method
def model(self):
print(‘Two wheeler’)
#object creation for child class
a=bike()
#call parent class method using child class object
a.models()
a.model()
|
__label__pos
| 0.999754 |
PageRenderTime 188ms CodeModel.GetById 101ms app.highlight 55ms RepoModel.GetById 25ms app.codeStats 0ms
/src/mpv5/ui/frames/MPBabelFish.java
http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 552 lines | 438 code | 73 blank | 41 comment | 17 complexity | 055e4b02f79731caaa723148af2a19a4 MD5 | raw file
1/*
2 * This file is part of YaBS.
3 *
4 * YaBS is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * YaBS is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with YaBS. If not, see <http://www.gnu.org/licenses/>.
16 */
17/*
18 * MPBabelFish.java
19 *
20 * Created on 01.02.2009, 17:33:56
21 */
22package mpv5.ui.frames;
23
24import javax.swing.DefaultComboBoxModel;
25import mpv5.db.common.NodataFoundException;
26import mpv5.globals.Headers;
27import mpv5.globals.Messages;
28import mpv5.i18n.LanguageManager;
29import mpv5.ui.dialogs.DialogForFile;
30
31import java.awt.Cursor;
32import java.io.File;
33import javax.swing.JTextField;
34import javax.swing.SwingWorker;
35import javax.swing.table.DefaultTableModel;
36import mpv5.db.common.Context;
37import mpv5.db.common.QueryHandler;
38import mpv5.db.objects.User;
39import mpv5.globals.Constants;
40import mpv5.globals.GlobalSettings;
41import mpv5.logging.Log;
42import mpv5.ui.dialogs.Popup;
43import mpv5.ui.dialogs.PropertyDialog;
44import mpv5.ui.misc.Position;
45import mpv5.usermanagement.MPSecurityManager;
46
47import mpv5.utils.models.MPComboBoxModelItem;
48import mpv5.utils.models.MPTableModel;
49import mpv5.utils.arrays.ArrayUtilities;
50import mpv5.utils.files.FileReaderWriter;
51import mpv5.utils.tables.ExcelAdapter;
52import mpv5.utils.text.RandomText;
53import mpv5.utils.ui.TextFieldUtils;
54
55/**
56 *
57 *
58 */
59public class MPBabelFish extends javax.swing.JFrame {
60
61 private String url;
62
63 /** Creates new form MPBabelFish */
64 public MPBabelFish() {
65 initComponents();
66 new ExcelAdapter(data);
67 setToolBar();
68 new Position(this);
69 setAlwaysOnTop(false);
70 setVisible(rootPaneCheckingEnabled);
71 setLanguageSelection();
72
73// Translate.setHttpReferrer(Constants.VERSION);
74
75 }
76
77 private void setLanguage() {
78
79 setCursor(new Cursor(Cursor.WAIT_CURSOR));
80 data.setModel(new MPTableModel(
81 new Class[]{String.class, String.class, String.class},
82 new boolean[]{false, true, true},
83 LanguageManager.getEditorModel(((MPComboBoxModelItem) languages.getSelectedItem()).getId()),
84 Headers.BABELFISH.getValue()));
85 setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
86 }
87
88 private void setLanguageSelection() {
89 languages.setModel(LanguageManager.getLanguagesAsComboBoxModel());
90 languages.setSelectedIndex(MPComboBoxModelItem.getItemID(mpv5.db.objects.User.getCurrentUser().__getLanguage(),
91 languages.getModel()));
92
93 setLanguage();
94 }
95
96 /** This method is called from within the constructor to
97 * initialize the form.
98 * WARNING: Do NOT modify this code. The content of this method is
99 * always regenerated by the Form Editor.
100 */
101 @SuppressWarnings("unchecked")
102 // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
103 private void initComponents() {
104
105 jPanel1 = new javax.swing.JPanel();
106 jLabel1 = new javax.swing.JLabel();
107 jScrollPane1 = new javax.swing.JScrollPane();
108 data = new javax.swing.JTable();
109 jLabel2 = new javax.swing.JLabel();
110 languages = new javax.swing.JComboBox();
111 langName = new mpv5.ui.beans.LabeledTextField();
112 jLabel7 = new javax.swing.JLabel();
113 GooogleTranslator = new javax.swing.JToolBar();
114 jLabel5 = new javax.swing.JLabel();
115 webserviceurl = new javax.swing.JTextField();
116 jLabel3 = new javax.swing.JLabel();
117 from = new javax.swing.JComboBox();
118 jLabel4 = new javax.swing.JLabel();
119 to = new javax.swing.JComboBox();
120 translate = new javax.swing.JButton();
121 progress = new javax.swing.JProgressBar();
122 jMenuBar1 = new javax.swing.JMenuBar();
123 jMenu1 = new javax.swing.JMenu();
124 jMenuItem4 = new javax.swing.JMenuItem();
125 jMenuItem2 = new javax.swing.JMenuItem();
126 jMenuItem1 = new javax.swing.JMenuItem();
127 jMenuItem3 = new javax.swing.JMenuItem();
128
129 setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
130 java.util.ResourceBundle bundle = mpv5.i18n.LanguageManager.getBundle(); // NOI18N
131 setTitle(bundle.getString("MPBabelFish.title_1")); // NOI18N
132 setAlwaysOnTop(true);
133 setName("Form"); // NOI18N
134
135 jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(bundle.getString("MPBabelFish.jPanel1.border.title_1"))); // NOI18N
136 jPanel1.setName("jPanel1"); // NOI18N
137
138 jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/mpv5/resources/images/32/babelfish.png"))); // NOI18N
139 jLabel1.setName("jLabel1"); // NOI18N
140
141 jScrollPane1.setName("jScrollPane1"); // NOI18N
142
143 data.setModel(new javax.swing.table.DefaultTableModel(
144 new Object [][] {
145 {},
146 {},
147 {},
148 {}
149 },
150 new String [] {
151
152 }
153 ));
154 data.setAutoCreateRowSorter(true);
155 data.setColumnSelectionAllowed(true);
156 data.setDoubleBuffered(true);
157 data.setDragEnabled(true);
158 data.setName("data"); // NOI18N
159 data.setSurrendersFocusOnKeystroke(true);
160 jScrollPane1.setViewportView(data);
161 data.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
162
163 jLabel2.setText(bundle.getString("MPBabelFish.jLabel2.text_1")); // NOI18N
164 jLabel2.setName("jLabel2"); // NOI18N
165
166 languages.setName("languages"); // NOI18N
167 languages.addMouseListener(new java.awt.event.MouseAdapter() {
168 public void mouseClicked(java.awt.event.MouseEvent evt) {
169 languagesMouseClicked(evt);
170 }
171 public void mouseExited(java.awt.event.MouseEvent evt) {
172 languagesMouseExited(evt);
173 }
174 });
175 languages.addActionListener(new java.awt.event.ActionListener() {
176 public void actionPerformed(java.awt.event.ActionEvent evt) {
177 languagesActionPerformed(evt);
178 }
179 });
180
181 langName.set_Label(bundle.getString("MPBabelFish.langName._Label")); // NOI18N
182 langName.setName("langName"); // NOI18N
183
184 jLabel7.setText(bundle.getString("MPBabelFish.jLabel7.text")); // NOI18N
185 jLabel7.setName("jLabel7"); // NOI18N
186
187 GooogleTranslator.setRollover(true);
188 GooogleTranslator.setName("GooogleTranslator"); // NOI18N
189
190 jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
191 jLabel5.setText(bundle.getString("MPBabelFish.jLabel5.text")); // NOI18N
192 jLabel5.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 0, 1, 5));
193 jLabel5.setEnabled(false);
194 jLabel5.setName("jLabel5"); // NOI18N
195 GooogleTranslator.add(jLabel5);
196
197 webserviceurl.setText(bundle.getString("MPBabelFish.webserviceurl.text")); // NOI18N
198 webserviceurl.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 5, 1, 5));
199 webserviceurl.setEnabled(false);
200 webserviceurl.setName("webserviceurl"); // NOI18N
201 GooogleTranslator.add(webserviceurl);
202
203 jLabel3.setText(bundle.getString("MPBabelFish.jLabel3.text")); // NOI18N
204 jLabel3.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 5, 1, 5));
205 jLabel3.setEnabled(false);
206 jLabel3.setName("jLabel3"); // NOI18N
207 GooogleTranslator.add(jLabel3);
208
209 from.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 5, 1, 5));
210 from.setEnabled(false);
211 from.setName("from"); // NOI18N
212 GooogleTranslator.add(from);
213
214 jLabel4.setText(bundle.getString("MPBabelFish.jLabel4.text")); // NOI18N
215 jLabel4.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 5, 1, 5));
216 jLabel4.setEnabled(false);
217 jLabel4.setName("jLabel4"); // NOI18N
218 GooogleTranslator.add(jLabel4);
219
220 to.setAutoscrolls(true);
221 to.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 5, 1, 5));
222 to.setEnabled(false);
223 to.setName("to"); // NOI18N
224 GooogleTranslator.add(to);
225
226 translate.setText(bundle.getString("MPBabelFish.translate.text")); // NOI18N
227 translate.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 5, 1, 5));
228 translate.setEnabled(false);
229 translate.setFocusable(false);
230 translate.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
231 translate.setName("translate"); // NOI18N
232 translate.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
233 translate.addActionListener(new java.awt.event.ActionListener() {
234 public void actionPerformed(java.awt.event.ActionEvent evt) {
235 translateActionPerformed(evt);
236 }
237 });
238 GooogleTranslator.add(translate);
239
240 progress.setName("progress"); // NOI18N
241
242 javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
243 jPanel1.setLayout(jPanel1Layout);
244 jPanel1Layout.setHorizontalGroup(
245 jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
246 .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
247 .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
248 .addComponent(jLabel2)
249 .addComponent(languages, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE))
250 .addGap(36, 36, 36)
251 .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
252 .addGroup(jPanel1Layout.createSequentialGroup()
253 .addComponent(langName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
254 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
255 .addComponent(progress, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE))
256 .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, 446, Short.MAX_VALUE))
257 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
258 .addComponent(jLabel1)
259 .addContainerGap())
260 .addComponent(GooogleTranslator, javax.swing.GroupLayout.DEFAULT_SIZE, 725, Short.MAX_VALUE)
261 .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 725, Short.MAX_VALUE)
262 );
263 jPanel1Layout.setVerticalGroup(
264 jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
265 .addGroup(jPanel1Layout.createSequentialGroup()
266 .addContainerGap()
267 .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
268 .addComponent(jLabel2)
269 .addComponent(jLabel7))
270 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
271 .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER, false)
272 .addComponent(languages, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
273 .addComponent(langName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
274 .addComponent(progress, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
275 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
276 .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 244, Short.MAX_VALUE)
277 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
278 .addComponent(GooogleTranslator, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
279 .addGroup(jPanel1Layout.createSequentialGroup()
280 .addComponent(jLabel1)
281 .addContainerGap(307, Short.MAX_VALUE))
282 );
283
284 jMenuBar1.setName("jMenuBar1"); // NOI18N
285
286 jMenu1.setText(bundle.getString("MPBabelFish.jMenu1.text_1")); // NOI18N
287 jMenu1.setName("jMenu1"); // NOI18N
288
289 jMenuItem4.setText(bundle.getString("MPBabelFish.jMenuItem4.text")); // NOI18N
290 jMenuItem4.setName("jMenuItem4"); // NOI18N
291 jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
292 public void actionPerformed(java.awt.event.ActionEvent evt) {
293 jMenuItem4ActionPerformed(evt);
294 }
295 });
296 jMenu1.add(jMenuItem4);
297
298 jMenuItem2.setText(bundle.getString("MPBabelFish.jMenuItem2.text_1")); // NOI18N
299 jMenuItem2.setName("jMenuItem2"); // NOI18N
300 jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
301 public void actionPerformed(java.awt.event.ActionEvent evt) {
302 jMenuItem2ActionPerformed(evt);
303 }
304 });
305 jMenu1.add(jMenuItem2);
306
307 jMenuItem1.setText(bundle.getString("MPBabelFish.jMenuItem1.text_1")); // NOI18N
308 jMenuItem1.setName("jMenuItem1"); // NOI18N
309 jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
310 public void actionPerformed(java.awt.event.ActionEvent evt) {
311 jMenuItem1ActionPerformed(evt);
312 }
313 });
314 jMenu1.add(jMenuItem1);
315
316 jMenuItem3.setText(bundle.getString("MPBabelFish.jMenuItem3.text_1")); // NOI18N
317 jMenuItem3.setName("jMenuItem3"); // NOI18N
318 jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
319 public void actionPerformed(java.awt.event.ActionEvent evt) {
320 jMenuItem3ActionPerformed(evt);
321 }
322 });
323 jMenu1.add(jMenuItem3);
324
325 jMenuBar1.add(jMenu1);
326
327 setJMenuBar(jMenuBar1);
328
329 javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
330 getContentPane().setLayout(layout);
331 layout.setHorizontalGroup(
332 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
333 .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
334 );
335 layout.setVerticalGroup(
336 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
337 .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
338 );
339
340 pack();
341 }// </editor-fold>//GEN-END:initComponents
342
343 private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
344
345 if (MPSecurityManager.checkAdminAccess()
346 && QueryHandler.instanceOf().clone(Context.getLanguage()).checkUniqueness("longname", new JTextField[]{langName.getTextField()})) {
347 if (langName.hasText()) {
348 Runnable runnable = new Runnable() {
349
350 public void run() {
351 try {
352 setCursor(new Cursor(Cursor.WAIT_CURSOR));
353 LanguageManager.importLanguage(langName.get_Text(), ArrayUtilities.tableModelToFile(data, new int[]{0, 2}, "=", RandomText.getText() + "language", "yabs"));
354 setLanguageSelection();
355 } catch (Exception e) {
356 Log.Debug(e);
357 } finally {
358 setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
359 }
360 }
361 };
362 new Thread(runnable).start();
363 } else {
364 TextFieldUtils.blinkerRed(langName.getTextField());
365 }
366 }
367 }//GEN-LAST:event_jMenuItem2ActionPerformed
368
369 private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
370
371 DialogForFile dialog = new DialogForFile(DialogForFile.FILES_ONLY);
372// MPTableModel mpdel = DataModelUtils.getModelCopy(data);
373 dialog.saveFile(ArrayUtilities.tableModelToFile(data, new int[]{0, 1}, "=", String.valueOf(languages.getSelectedItem()), "yabs"));
374// data.setModel(mpdel);
375// setLanguageSelection();
376 }//GEN-LAST:event_jMenuItem1ActionPerformed
377
378 private void translateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_translateActionPerformed
379 new Job(this).execute();
380 }//GEN-LAST:event_translateActionPerformed
381
382 private void languagesMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_languagesMouseExited
383 }//GEN-LAST:event_languagesMouseExited
384
385 private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
386 if (MPSecurityManager.checkAdminAccess()) {
387 if (Popup.Y_N_dialog(Messages.REALLY_WIPE + ": " + ((MPComboBoxModelItem) languages.getSelectedItem()).getValue())) {
388 try {
389 LanguageManager.removeLanguage(((MPComboBoxModelItem) languages.getSelectedItem()).getId());
390 } catch (NodataFoundException ex) {
391 Log.Debug(this, ex);
392 }
393 }
394 }
395
396 setLanguageSelection();
397 }//GEN-LAST:event_jMenuItem3ActionPerformed
398
399 private void languagesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_languagesMouseClicked
400 }//GEN-LAST:event_languagesMouseClicked
401
402 private void languagesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_languagesActionPerformed
403 setLanguage();
404 }//GEN-LAST:event_languagesActionPerformed
405
406 private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
407
408 DialogForFile d = new DialogForFile(DialogForFile.FILES_ONLY);
409 if (d.chooseFile()) {
410 new Job3(this, d.getFile()).execute();
411 }
412 }//GEN-LAST:event_jMenuItem4ActionPerformed
413
414 // Variables declaration - do not modify//GEN-BEGIN:variables
415 private javax.swing.JToolBar GooogleTranslator;
416 private javax.swing.JTable data;
417 private javax.swing.JComboBox from;
418 private javax.swing.JLabel jLabel1;
419 private javax.swing.JLabel jLabel2;
420 private javax.swing.JLabel jLabel3;
421 private javax.swing.JLabel jLabel4;
422 private javax.swing.JLabel jLabel5;
423 private javax.swing.JLabel jLabel7;
424 private javax.swing.JMenu jMenu1;
425 private javax.swing.JMenuBar jMenuBar1;
426 private javax.swing.JMenuItem jMenuItem1;
427 private javax.swing.JMenuItem jMenuItem2;
428 private javax.swing.JMenuItem jMenuItem3;
429 private javax.swing.JMenuItem jMenuItem4;
430 private javax.swing.JPanel jPanel1;
431 private javax.swing.JScrollPane jScrollPane1;
432 private mpv5.ui.beans.LabeledTextField langName;
433 private javax.swing.JComboBox languages;
434 private javax.swing.JProgressBar progress;
435 private javax.swing.JComboBox to;
436 private javax.swing.JButton translate;
437 private javax.swing.JTextField webserviceurl;
438 // End of variables declaration//GEN-END:variables
439
440 private void setToolBar() {
441// from.setModel(new DefaultComboBoxModel(Language.values()));
442// to.setModel(new DefaultComboBoxModel(Language.values()));
443 }
444
445 class Job extends SwingWorker<Object, Object> {
446
447 private MPBabelFish parent;
448
449 private Job(MPBabelFish aThis) {
450 this.parent = aThis;
451 }
452
453 @Override
454 public Object doInBackground() {
455 parent.setCursor(new Cursor(Cursor.WAIT_CURSOR));
456 String[] dat = ArrayUtilities.SmallObjectToStringArray(ArrayUtilities.getColumnAsArray(data, 1));
457 String[] translated = new String[dat.length];
458 mpv5.YabsViewProxy.instance().setProgressMaximumValue(dat.length);
459 progress.setStringPainted(true);
460 progress.setMaximum(dat.length);
461 for (int i = 0; i < dat.length; i++) {
462
463 String string = dat[i];
464 try {
465 if (string != null && string.length() > 0) {
466 Log.Debug(this, "Translating: " + string);
467// translated[i] = Translate.execute(string, (Language) from.getSelectedItem(), (Language) to.getSelectedItem());
468 mpv5.YabsViewProxy.instance().setProgressValue(i + 1);
469 progress.setValue(i + 1);
470 } else {
471 translated[i] = "";
472 mpv5.YabsViewProxy.instance().setProgressValue(i + 1);
473 progress.setValue(i + 1);
474 }
475 } catch (Exception ex) {
476 Log.Debug(this, ex.getMessage());
477 }
478 }
479 ArrayUtilities.replaceColumn(data, 2, translated);
480 return null;
481 }
482
483 @Override
484 public void done() {
485 parent.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
486 mpv5.YabsViewProxy.instance().setProgressReset();
487 progress.setValue(0);
488 Popup.notice(Messages.DONE);
489 }
490 }
491
492 class Job3 extends SwingWorker<Object, Object> {
493
494 private MPBabelFish parent;
495 private File f;
496
497 private Job3(MPBabelFish aThis, File f) {
498 this.parent = aThis;
499 this.f = f;
500 }
501
502 @Override
503 public Object doInBackground() {
504 parent.setCursor(new Cursor(Cursor.WAIT_CURSOR));
505
506 String[] originallanguage = ArrayUtilities.SmallObjectToStringArray(ArrayUtilities.getColumnAsArray(data, 1));
507 String[] components = ArrayUtilities.SmallObjectToStringArray(ArrayUtilities.getColumnAsArray(data, 0));
508
509 FileReaderWriter fr = new FileReaderWriter(f, "UTF8");
510 String[] imported = fr.readLinesWCharset();
511
512 mpv5.YabsViewProxy.instance().setProgressMaximumValue(imported.length);
513 progress.setStringPainted(true);
514 progress.setMaximum(imported.length);
515 for (int i = 0; i < originallanguage.length; i++) {
516 String component = components[i];
517 try {
518 for (int j = 0; j < imported.length; j++) {
519 String string = imported[j];
520 if (string.split("=").length == 2) {
521 if (string.split("=")[0].equals(component)) {
522 originallanguage[i] = string.split("=")[1];
523 mpv5.YabsViewProxy.instance().setProgressValue(i + 1);
524 progress.setValue(i + 1);
525 }
526 }
527 }
528 } catch (Exception ex) {
529 Log.Debug(this,
530 "\n'I refuse to prove that I exist', says God, \n"
531 + "'for proof denies faith, and without faith I am nothing'. \n"
532 + "'But,' says man, 'The Babel fish is a dead giveaway, isn't it? \n"
533 + "It could not have evolved by chance. \n"
534 + "It proves you exist, and so therefore, by your own arguments, you don't.\n"
535 + "The Hitchhiker's Guide to the Galaxy: Babelfish\n");
536 Log.Debug(this, ex);
537 }
538 }
539 ArrayUtilities.replaceColumn(data, 2, originallanguage);
540 return null;
541 }
542
543 @Override
544 public void done() {
545 ((MPTableModel)data.getModel()).setCanEdits(false, true, true);
546 parent.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
547 mpv5.YabsViewProxy.instance().setProgressReset();
548 progress.setValue(0);
549 Popup.notice(Messages.DONE);
550 }
551 }
552}
|
__label__pos
| 0.952586 |
Definition of:playlist (1) See video playlist.
(2) A file that contains an index to a selected group of music files on the computer. Using media player software such as iTunes and Winamp, playlists are created by the user by dragging and dropping titles from a master index. The software may be able to create a playlist automatically. For example, iTunes has a Smart Playlist feature that will automatically create a playlist with a selected maximum number of titles based on any number of criteria such as genre, artist and year.
Formats
There are several file formats used for playlists. For example, iTunes defines playlists in its XML-based library file, which also holds song information. Some formats are simple text files with a song on each line; for example, M3U files (MP3 playlists) contain a list of URLs or local file names, while RAM files contain a list of URLs to RealAudio files. The PLS playlist defines its song titles as key-value pairs in the Windows INI format (see INI file). Windows Media provides several playlist formats (see Windows Media formats). See media player and MPV.
|
__label__pos
| 0.801394 |
4
$\begingroup$
This is probably a well-known problem. Given a set or multiset of natural numbers let us construct its "Euclides" closure: on each step we take all possible products $P_i$ of the elements in the set, and add to the set those of $P_i+1$ who are primes. The question is whether this closure is finite or not.
For example, if we take $\{1\}$ as the initial set, then we add $2=1+1$, then we add $3=2+1$, then we add $7=2\cdot 3+1$, then we add $2\cdot 3\cdot 7+1=43$ and that is all. All other products of the elements of $\{1,2,3,7,43\}$, increased by 1 are composite numbers.
But if we start with the multiset $\{2,2\}$ then computations are much harder. We add $3=2+1,5=2\cdot2+1, 7=2\cdot3+1,11=2\cdot5+1,13=2\cdot2\cdot3+1,23=2\cdot 11+1$ and many many others.
Is "Euclides'"closure of $\{2,2\}$ finite?
Equivalent question: does there exist a positive integer $n$ such that whenever $p-1$ divides $4n$ for a prime number $p$, $p$ itself divides $2 n$.
$\endgroup$
• 2
$\begingroup$ Starting from the multiset $\{2,2\}$, do you add $3$ to the multiset twice or just once? $\endgroup$ – Greg Martin Apr 13 '18 at 19:24
• 1
$\begingroup$ I'm not convinced that the "equivalent question" is actually equivalent. Some data though: starting with $\{2,3,5\}$ (which is a subset of the $\{2,2,3,5\}$ that is one step after $\{2,2\}$), after only three iterations one has a set with over 10,000 elements, the largest of which has 34 digits. $\endgroup$ – Greg Martin Apr 13 '18 at 19:31
• $\begingroup$ @GregMartin, we add each element only once. Thank you for the data! I did not compute so many numbers, but still, it seems that the set is infinite... Concerning the equivalent question: If such a set is finite, take n= the product of all odd primes in it. $\endgroup$ – Nikita Kalinin Apr 13 '18 at 21:13
• $\begingroup$ Greg, each prime other than 2 is added only once. $\endgroup$ – Fedor Petrov Apr 14 '18 at 10:25
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Browse other questions tagged or ask your own question.
|
__label__pos
| 0.932567 |
problem z importowaniem dll'a
0
Witam
Mam problem przy importowaniu dll'a
Robie tak:
[DllImport("vhrgrablinkcontrol.dll",SetLastError=true,CharSet= CharSet.Unicode,ExactSpelling=true,CallingConvention= CallingConvention.StdCall)]
public static extern int PSL_VHR_Init(string path);
I mam tak:
Exception System.TypeLoadException was thrown in debuggee:
Could not load type 'camera.MainClass' from assembly 'camera, Version=1.0.2645.18697, Culture=neutral, PublicKeyToken=null' because the method 'PSL_VHR_SetTriggerMode' has no implementation (no RVA).
[???] POMOCY !!!
0
sam pisałeś tą bibliotekę?
0
nie bibioteka jest dostarczana przez producenta sprzetu ktory ma obslugiwac program
0
a nie musisz przypadkiem podać jeszcze EntryPoint :>, np
[DllImport("vhrgrablinkcontrol.dll", EntryPoint = "PSL_VHR_Init", SetLastError=true, CharSet= CharSet.Unicode, ExactSpelling=true, CallingConvention= CallingConvention.StdCall)]
public static extern int PSL_VHR_Init(string path);
0
dodanie EntryPoint nie pomaga :(
0
to niestety nie mam innych pomysłów poza tym, że biblioteka jest źle napisana
1 użytkowników online, w tym zalogowanych: 0, gości: 1, botów: 0
|
__label__pos
| 0.830411 |
Caplin Trader 5.1.0
Interface: module:ct-control/factory/ControlFramework
module:ct-control/factory/ControlFramework
The ControlFramework interface specifies those lifecycle functions that are necessary for a control implementation to be managed by the Control Framework.
Methods
attachControlEventListener(eventName, renderer)
Attaches an event listener to the control. When the event occurs on the control then the onRendererEvent callback will be invoked on the supplied renderer.
Parameters:
Name Type Description
eventName String
The event name such as 'click', 'change', 'mouseover' etc.
renderer module:ct-element/Renderer
The renderer
bind(controlElement, isDummyopt)
Binds the DOM control.
Parameters:
Name Type Attributes Description
controlElement HtmlElement
The DOM element which represents the control.
isDummy boolean <optional>
true if the supplied control is a dummy.
createHtml(value) → {HTMLElement|DocumentFragment}
Creates an HTML fragment using the supplied control value.
Parameters:
Name Type Description
value Variant
The field vale to display.
Returns:
The HTML element or document fragment
Type
HTMLElement | DocumentFragment
detachControlEventListener(eventName)
Detaches event listeners from the control.
Parameters:
Name Type Description
eventName String
The event name such as 'click', 'change', 'mouseover' etc.
finalize()
Releases any resources and unbinds the control from the DOM.
getInitialClassName() → {String}
Gets the initial class name.
Returns:
The initial class name.
Type
String
initialize()
Initializes the control, clearing any cached value and cached CSS styling information.
setInitialClassName(initialClassName)
Sets the initial class name.
Parameters:
Name Type Description
initialClassName String
The HTML class attribute (a space separated list).
unbind()
Unbinds the DOM control.
|
__label__pos
| 0.627405 |
Using Other Lanugages in Ruby
Notes from my presentation at the June 2015 University Ruby meetup at Cloudspace.
The following is a written / more accessible version of my presentation. It should include most of what I say aloud, as well as all of the code presented. For more, you can watch the Youtube video of the entire meetup.
The purpose of this guide is to demonstrate various ways of running code that is written in other languages from within a Ruby program. Sometimes we need to run some fast code, or use features of another language. Ugh! Don't worry, though; it doesn't have to be painful.
We'll begin with everyone's favorite…
C
When it comes to speed, it is hard to beat C. Sometimes you may find that an operation in Ruby just takes too long, or that you have to interface with someone's legacy code. Either way, you have some options when it comes to running that code from Ruby.
Throughout this guide, we'll use the example of the naïve (recursive, non-memoized) Fibonacci number generator. That is, the following C function:
int fib (int n) {
if (n < 2)
return n;
return fib(n-1) + fib(n-2);
}
This is a somewhat common test for language performance, as the number of function calls made grows exponentially with n.
So, let's look at a few ways you could run this code using Ruby.
Straight C
You can, of course, run this code by having Ruby make a system call to a compiled C executable. We'll use this as a benchmark for the other methods. Here's what that might look like in code:
fib.c:
#include <stdio.h>
#include <stdlib.h>
int fib (int n) {
if (n < 2)
return n;
return fib(n - 1) + fib(n - 2);
}
int main (int argc, char **argv) {
if (argc != 2) {
printf("Usage: ./fib <n>\n");
exit(1);
}
int result = fib(atoi(argv[1]));
printf("%d\n", result);
return 0;
}
In Ruby:
puts `/path/to/fib 42`
The backticks (``) are just one way of making system calls in Ruby. This method assumes that you've already compiled the C code on your system, and you have a path to the executable handy.
While this may be elementary, don't discount the fact that it works… and you can get it running without too much effort.
FFI
FFI stands for Foreign Function Interface, which is exactly the kind of thing we need. I recommend that you use FFI when you have a larger set of code that you wish to use. You can install FFI in the form of a gem using gem install ffi.
Using FFI is a bit more involved. Here's what it looks like:
fib.c is the same as above, except that it has been compiled into a shared object file using:
gcc -c -fPIC -o fib fib.c
gcc -shared -o fib.so fib
ffi.rb
#!/usr/bin/env ruby
require 'ffi'
module FibTest
extend FFI::Library
ffi_lib 'c'
ffi_lib './fib.so'
attach_function :fib, [ :int ], :int
end
result = FibTest.fib(ARGV[0].to_i)
puts "Result: " + result.to_s
As you can see, the fib() function is attached to and callable from the Ruby object. It doesn't much matter what the fib() function does beyond that.
You can expose as many functions as you wish in this way, and FFI will handle the language translation. When in doubt, try this method!
RubyInline
An alternative to FFI is RubyInline, which - as you'll see in a moment - is a very apt name. I recommend that you use RubyInline when you have very short snippets of code you'd like to run. Like FFI, you can install RubyInline in the form of a gem, via gem install RubyInline.
This is going to look a bit messy, but let's see how it works:
inline.rb
#!/usr/bin/env ruby
require 'inline'
class FibTest
inline do |builder|
builder.prefix "
int fib_inner (int n) {
if (n < 2)
return n;
return fib_inner(n - 1) + fib_inner(n - 2);
}"
builder.c "
int fib (int n) {
return fib_inner(n);
}"
end
end
inline = FibTest.new
result = inline.fib(ARGV[0].to_i)
puts "Result: " + result.to_s
You'll notice we've adapted the code slightly. RubyInline does a lot of translation when it comes to the types of parameters expected by the C functions. Thus, when you want to run a recursive function like fib(), it is best to introduce a wrapper function. Here we've moved fib() to fib_inner() and instead exposed a fib() wrapper function to the Ruby world.
The fib_inner() function is defined using the prefix method, which means that it won't be translated by RubyInline. This is important because it calls itself, and that won't work if RubyInline changes the way it accepts parameters.
Comparison
Great, so we have a few methods by which to call C code from Ruby. How do they compare, performance-wise? Here's the raw data:
Method Avg. Runtime (s)
Straight C 3.3777779
Ruby + FFI 3.4948946
RubyInline 2.9529457
Straight Ruby 64.398319
Interestingly, RubyInline performs faster than using a compiled C executable. Why is this? When we run the C executable, the OS has to create a new process, allocate some memory for the stack and heap of the program, and then supply it with its arguments. RubyInline avoids a lot of that mess by piggy-backing off of the resources already allocated to the Ruby process. This may not appear to be much of an improvement, but it can be significant with repeated calls over time.
Python
For working with Python in Ruby, you can use the rubypython gem. Much like FFI (in fact, it uses FFI libraries), rubypython allows you to expose and interact with Python. Because Python uses an object model, rubypython completes the added task of exposing Python modules and objects to Ruby. You can install rubypython using gem install rubypython.
Here's just a quick example of how it works:
py.rb
> require 'rubypython'
=> true
> RubyPython.start
=> true
> numpy = RubyPython.import("numpy")
=> <module 'numpy' from '/(...)/numpy/__init__.pyc'>
> arr = numpy.array([1,2,3])
=> array([1, 2, 3])
> RubyPython.stop
=> true
You are, of course, limited by the syntax of both languages. For example, you cannot use the succinct array splicing syntax available in numpy ([::2]). This may be annoying to die-hard python developers. However, the entirety of the Python object/module and its methods are available, inheritable, etc.
R
As a final note, let's take a brief look at using the R language within Ruby. You can do this using the rinruby gem, installed via gem install rinruby. Given that you have the R language installed locally, here's how it looks:
> require "rinruby"
=> true
> sample_size = 10
=> 10
> R.eval "x <- rnorm(#{sample_size})"
# (outputs code being run by R)
> R.eval "summary(x)"
.RINRUBY.PARSE.STRING <- rinruby_get_value()
rinruby_parseable(.RINRUBY.PARSE.STRING)
rm(.RINRUBY.PARSE.STRING)
summary(x)
Min. 1st Qu. Median Mean 3rd Qu. Max.
-0.77660 -0.35550 -0.01425 0.14630 0.67590 1.58500
print('RINRUBY.EVAL.FLAG')
=> true
This is just a quick summary, as found in the rinruby documentation.
Wrapping Up
We like to write Ruby code, so we should do so whenever possible. If the need to use code written in another language arises, there's no need to adopt that lanugage completely. With a few tools, you can use Ruby as a glue for your libraries and legacy codebases.
Have a comment or correction? Send me a tweet!
Thanks to the following articles for helping me get started:
1. Calling C/C++ from Ruby
2. Rubypython
3. R in Ruby Quick Start
|
__label__pos
| 0.648154 |
loopback-mixin-mongo-seq
loopback mixin to add support for sequential property
Usage no npm install needed!
<script type="module">
import loopbackMixinMongoSeq from 'https://cdn.skypack.dev/loopback-mixin-mongo-seq';
</script>
README
MONGO-SEQ Build Status
loopback v3 mixin to add support for sequential property.
usage
• install via npm.
npm install loopback-mixin-mongo-seq
• update server.js to load mixin.
const loopbackMixinMongoSeq = require('loopback-mixin-mongo-seq');
loopbackMixinMongoSeq(app, {
dataSource: 'MongoDS', modelName: 'Counter'
});
• add mixins property to the required model.
"mixins": {
"Seq" : {
"propertyName": "ID",
"step": 1,
"initialVal": 1,
"readOnly": true,
"definition": {
"index": { "unique": true }
}
}
}
options
propertyName: property name, defaults to ID.
step: defaults to 1.
initialVal: value to start counter from if the sequence doesn't exist, defaults to the highest record in the target model if not found then 1.
readOnly: if the value should be protested against changes, defaults to true.
definition: property definition ( can be used to add index to property), defaults to {}.
DEBUG MODE
DEBUG='loopback:mixin:mongo-seq'
|
__label__pos
| 0.876429 |
0
$\begingroup$
How can I prove this? Should I take $x$ and $x+2$ or not ? I am confused.
$\endgroup$
• 6
$\begingroup$ Try adding $2n+1$ and $2m+1$ $\endgroup$ – Henry Sep 29 '15 at 14:07
• 3
$\begingroup$ Further hint: $$(2n+1)+(2m+1)=2\cdot(\text{_____})$$ $\endgroup$ – Did Sep 29 '15 at 14:09
• $\begingroup$ how can i do it ? I don't understand it :/ $\endgroup$ – Anna Sep 29 '15 at 14:12
• $\begingroup$ Do you know what makes a number odd? $\endgroup$ – kingW3 Sep 29 '15 at 14:14
• $\begingroup$ All numbers that ends with 1, 3, 5, 7, or 9 are odd numbers. $\endgroup$ – Anna Sep 29 '15 at 14:20
3
$\begingroup$
Any even number has the form $2n$. (Why? No matter what you make $n$ to be, $2n$ will, be divisible by $2$.).
Any odd number has the form $2n+1$. (Why? Play with this by plugging numbers into $n$.).
So, add two odd numbers:
$$(2n+1)+(2n+1)=4n+2=2(2n+1)$$
Is your result always divisible by $2$? Why or why not?
Would you be able to reproduce the above with understanding?
| cite | improve this answer | |
$\endgroup$
• 1
$\begingroup$ Should be 2(2n+1) $\endgroup$ – JonH Feb 13 '17 at 0:28
• $\begingroup$ Fixed it. Thanks. $\endgroup$ – Adam Hrankowski Feb 14 '17 at 0:51
1
$\begingroup$
Other option: modular arithmetic,
even number $\pmod 2 \equiv 0$ and
odd number $\pmod 2 \equiv 1$, then
(odd+odd) $\pmod 2 \equiv \ ?$
Basically you can continue from there:
((odd $\pmod 2$) + (odd $\pmod 2$)) $\pmod 2$ $\equiv \ ?$
| cite | improve this answer | |
$\endgroup$
• 3
$\begingroup$ I don't think the OP will understand you answer. $\endgroup$ – gamma Sep 29 '15 at 14:54
• 2
$\begingroup$ @anubhav it is just other approach, if not initially for the OP, it will be useful for other people reading the question, or even for the OP later. $\endgroup$ – iadvd Sep 29 '15 at 15:08
1
$\begingroup$
Suppose there is greatest even integer N Then For every even integer n, N ≥ n. Now suppose M = N + 2. Then, M is an even integer. [Because it is a sum of even integers.] Also, M > N [since M = N + 2]. Therefore, M is an integer that is greater than the greatest integer. This contradicts the supposition that N ≥ n for every even integer n. [Hence, the supposition is false and the statement is true.]
| cite | improve this answer | |
$\endgroup$
0
$\begingroup$
Hint : With your definition of odd numbers : "All numbers that ends with 1, 3, 5, 7, or 9 are odd numbers." (consequently, even numbers are the numbers that end with 0,2,4,6 or 8). Take two odd numbers, what are the possible ends for this sum?
| cite | improve this answer | |
$\endgroup$
0
$\begingroup$
Using your approach, let $x$ be odd, and consider the other odd number as $x+2k$. Then the sum is $x+(x+2k)=2x+2k=2(x+k)$, which is even.
| cite | improve this answer | |
$\endgroup$
0
$\begingroup$
Let m and n be odd integers. Then, m and n can be expressed as 2r + 1 and 2s + 1 respectively, where r and s are integers. This only means that any odd number can be written as the sum of some even integer and one.
when substituting lets have m + n = (2r + 1) + 2s + 1 = 2r + 2s + 2.
| cite | improve this answer | |
$\endgroup$
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.991078 |
Opening instead of closing???
Hi,
I have a ListBox which contains a contextual menu. When I use the code below - all works perfectly. It closes certain windows if they are open, and opens the window selected by the user.
[code] Select Case hititem.text
case “Add a New Choice”
frm_Search.Close
win_Add.ShowModal
case “Edit or Delete the Selected Choice”
frm_Search.Close
win_Edit.ShowModal
case “Search Choices”
win_Add.Close
frm_Search.ShowModal
case “View All Choices”
frm_Search.Close
win_Add.Close
win_Main.Open
End select
Return True[/code]
HOWEVER - the impossible seems to happen when I add the code below to the 1st, 3rd and 4th Cases.
It causes ALL of the cases to OPEN the “win_Edit” window - instead of closing it, and opening the appropriate window ???
win_Edit.Close
It seems impossible and I am totally perplexed.
Can anyone shed any light or ideas?
Thank you all in advance.
Sounds like a side-effect of Implicit window instantiation which allows you to refer to your windows directly by their name. Although convenient, it can lead to this confusing behavior as projects get more complex.
You’ll instead want to create your own instances of your windows (like you would for any other object) and deal with the windows that way.
So something more like this:
Dim editWindow As win_Edit editWindow.Show
Then to close the window you can call:
editWindow.Show
Bit confused as I am only a part time user :frowning:
So I need to de-select the Implicit instance in the inspector.
Then add the first section of code you provided.
Also, should the last piece of code you kindly provided be editWindow.Close ?
Thank you for your patience. :slight_smile:
|
__label__pos
| 0.827206 |
Difference between providers
Hi everyone,
I saw there was a topic that touched on this, but didn’t completely explain, and I’ve tried to find a decent answer across the internet but I’m really struggling with this one;
Why is there such a vast difference in price for AWS & GCE vs the others provided by Cloudways?
My experience with any of them is extremely limited, and Cloudways seems to offer a great way to get a decent managed cloud server with a provider of your choosing but as far as I can see these are just compute instances/VPS which should have roughly a similar performance, right?
I can totally understand picking a provider with a DC closest to visitors, but beyond this I just don’t get it (even this is irrelevant if using a decent CDN). Speed benchmarks I’ve seen also seem to sometimes even put some like DigitalOcean ahead of AWS on like-for-like specs. 8gb 4core AWS is over 3 times the price of a DO machine - is it going to be 3 times better in some aspect?
I know I must be missing something so I’d really appreciate it if somebody could explain this to me, or point me to resources which would enlighten me and help me make an informed decision on which provider/server I should pick.
I performed some tests and already know that a fairly low spec DO machine is already consistently 20% faster than my current setup, so I’m happy with this but I’d rather know I’m picking a provider which may work out better for me.
Thank you
Hi there,
Just posting this here for reference.
Don’t forget that some providers like AWS you’re also paying for the branding, they all might have their own sauce to the recipe, yet yes they are all VPS; from a commercial view, if one chooses to take a machine or AWS or DO, it doesn’t really make a difference for Cloudways. In fact within Cloudways you are free to move provider any time you want without the hassles of creating more accounts, thus everything still remains under one hood.
Moving your server closer to your traffic source does still help in my opinion. Yes static stuff which can be cached will fly over the CDN irrespective of where your server is, yet what dynamic content which your server will need to serve? Your full page load time will still be effected by that. AWS in this terms, has the most extensive list of data centres available, thus you’re more flexible on how to position yourself.
In terms of picking the “best” one for your use, I would say pick the one which does make financial sense for you while giving you the best performance. Milage will vary from project to project, thus people might always have different views.
1 Like
Thank you - exactly what I was after.
Really appreciated.
You’re welcome - feel free to call back here or get back to Cloudways support if you require more information.
|
__label__pos
| 0.75904 |
Implement TextVertexInputFormat for text-format graph data
----------------------------------------------------------
Key: GIRAPH-29
URL: https://issues.apache.org/jira/browse/GIRAPH-29
Project: Giraph
Issue Type: New Feature
Components: bsp
Reporter: Hyunsik Choi
Assignee: Hyunsik Choi
Priority: Minor
Fix For: 0.70.0
Supporting text-format graph data would be nice. It is helpful for developing
graph algorithms and debugging because text-format graph data are
human-readable and enable users to easily write sample data sets. Furthermore,
text-format data are exchangeable regardless of operating systems or
programming languages.
So, we need a basic InputFormat to help users develop user-defined InputFormat
classes to deal text-represented graph data sets.
--
This message is automatically generated by JIRA.
For more information on JIRA, see: http://www.atlassian.com/software/jira
Reply via email to
|
__label__pos
| 0.665605 |
Wondershare Recoverit
File Recovery
• Recovers deleted or lost files effectively, safely and completely.
• Supports data recovery from 500+ data loss scenarios, including computer crash, partition loss, accidental human error, etc.
• Supports 1000+ file formats recovery with a high success rate and without any quality loss.
Free Download Free Download Free Download Learn More >
file recovery
6 Simple Methods to Increase Hard Drive Speed
Wondershare Recoverit Authors
Aug 04, 2023 • Filed to: Answer Hard Drive Problems • Proven solutions
The hard drive is of vital importance for a computer system. It offers large storage space. Nowadays, every modern computer system has a fast and large hard drive that helps in the quick retrieval of files and programs. However, even the fastest and biggest hard drives can become slow if you accumulate too much clutter. There is no need to worry, though, as you can easily increase the hard drive speed through proper maintenance and avoid issues that slow down your hard drive speed.
recoverit hard drive data recovery software
Part 1. What Cause Hard Drive Speed Slow Down?
Several reasons can hold down the speed of your hard drive. The following are some of the issues that can slow down the speed of your hard drive.
Video Tutorial on How to Perform Hard Disk Speed Test
Recent Videos from Recoverit
View More >
Read More: How to Test Hard Drive Speed?
Part 2. How to Increase Hard Drive Speed?
1 Delete Temporary Files
The internet browsers used for accessing the internet have a habit of storing a lot of temporary internet files on your hard drive. These files take up a lot of space and can slow down your hard drive's speed. By deleting these temporary files, you can instantly boost up the speed of your hard drive. The following simple steps can help you in cleaning up your hard drive.
1. Enter the Computer folder after clicking the Windows button.
2. Please search for your hard drive icon and then right-click on it after selecting it.
3. In the menu that appears, select the Properties option.
4. Press the Disk Cleanup button in the Properties dialog box of your chosen hard drive.
5. Select the option of Files from all users on this computer.
6. Check the boxes of the files to be deleted and then click the OK button.
Bonus: What if you delete the important files mistakenly?
Here you can use Wondershare Recoverit data recovery software to retrieve deleted files from your low-speed hard drive. Download the application through the below button. You can recover your data in three simple steps, get data out of crashed computer, and repair corrupted videos.
computer data recovery
2 Scan Hard Drive
Scanning your hard drive for possible bad sectors is another great way of increasing your hard drive speed. You can use the Check Disk tool for this purpose and find out if your hard disk has bad sectors or not. These simple steps need to be performed for scanning your hard drive.
1. Enter the Computer folder after clicking the Windows button.
2. Please search for your hard drive icon and then right-click on it after selecting it.
3. In the menu that appears, select the Properties option.
4. Enter the Tools tab in the Properties dialog box of your chosen hard drive.
5. Press the button labeled, Check Now.
6. Check the boxes of options 'Automatically fix file system errors' and 'Scan for and attempt recovery of bad sectors' and then click the Start button.
3 Defrag Your Hard Drive
Since fragmented hard disks can slow down the performance of a hard disk, it is best to defrag the hard drive to boost its speed and performance. Defragmentation is the process through which the scattered bits of a file are pieced together in a single block to be accessed more quickly by the hard drive. Following these simple steps will help you defrag your hard drive.
1. Enter the Computer folder after clicking the Windows button.
2. Please search for your hard drive icon and then right-click on it after selecting it.
3. In the menu that appears, select the Properties option.
4. Enter the Tools tab in the Properties dialog box of your chosen hard drive.
5. Press the button labeled, Defragment Now.
6. Click the Defragment button in the menu that appears to start the defragmentation process.
4 Enable Write Caching
Write caching is a feature included in the Vista and Windows 7 versions, enabling you to write information in a cache before it can be written on the hard drive. This helps increase the hard drive's performance as the cache is faster, and the information can be written on it much more quickly than on the hard drive itself. There is a drawback to this measure, though. You can lose the data in this temporary cache if the computer shuts down suddenly. These steps can help you enabling write caching.
1. Click the Start button.
2. In the Windows Search bar, type Device Manager.
3. Select your hard drive from the Disk Drives option in the Device Manager.
4. Right-click on the hard drive and then click the Properties button.
5. In the Properties menu, click on the Policies tab.
6. Check the box of enabling write caching on the device and click OK.
5 Partition Your Hard Drive
Distributing your hard drive into multiple partitions can also go a long way in increasing your hard drive speed. The more partitions you have on your hard disk, the more organized your hard disk becomes, and ultimately, its speed gets boosted too since the short stroking technology reduces the delays caused by head repositioning. Following these simple steps can help you in partitioning your hard drive.
1. Click the Start button.
2. In the Windows Search bar, type Computer Management.
3. Choose the Disk Management option.
4. Right-click on one of the existing partitions and click the Shrink Volume option.
5. Enter the size by which the partition is to be shrunk and then click the Shrink button.
6. Right-click on the unpartitioned disk space and choose the New Simple Volume option.
7. Please enter the amount of memory to be assigned to the new partition and select a drive letter for it.
8. Choose the file system for the new partition and then format it.
9. Click the Finish button to finish creating the new partition.
6 Upgrade
If the above-mentioned tips fail to bring about a significant change in your hard drive's speed, then it is highly likely that a hardware issue is causing the hard disk to slow down. In such cases, it is best to replace the aging hard disk with an upgraded version, which will enhance your computer speed.
Hard disk speed is crucial for the performance of a computer system. If the hard drive speed is low, accessing programs and files will take a great deal of time and slow down your PC's speed. There are several reasons why your hard drive might be slowing down. You can use various methods to increase your hard disk speed. The following tips can help in boosting the speed of your hard drive.
Other popular Articles From Wondershare
Recoverit author
Theo Lucia
chief Editor
Home > Resources > Answer Hard Drive Problems > 6 Simple Methods to Increase Hard Drive Speed
|
__label__pos
| 0.973041 |
sdfps/core.c
71 lines
1.3 KiB
C
Raw Permalink Normal View History
2022-03-21 17:58:17 +00:00
// core.c
#include <stdio.h>
#include <stdlib.h>
#define SDL_MAIN_HANDLED
#include <SDL2/SDL.h>
#define PROJECT_NAME "sdfps"
#ifdef __WIN32__
# define SHARED_OBJECT PROJECT_NAME ".dll"
# define SHARED_OBJECT_ACTIVE SHARED_OBJECT "-active.dll"
#else
# define SHARED_OBJECT "./" PROJECT_NAME ".so"
# define SHARED_OBJECT_ACTIVE SHARED_OBJECT
#endif
#define SHARED_MAIN PROJECT_NAME "_main"
#ifdef __WIN32__
/*
* windows doesn't let us overwite a dll that's currently in use, but it
* seems that macos/linux does
*/
int copy_shared_object() {
if (system("copy " SHARED_OBJECT " " SHARED_OBJECT_ACTIVE " /Y")) {
puts("failed copying to " SHARED_OBJECT_ACTIVE);
// puts(SDL_GetError());
return 1;
}
return 0;
}
#else
int copy_shared_object() {
return 0;
}
#endif
int main(int argc, char **argv) {
void *u_data = NULL;
puts("start.");
SDL_Init(SDL_INIT_EVERYTHING);
while (1) {
if (copy_shared_object())
break;
void *so = SDL_LoadObject(SHARED_OBJECT_ACTIVE);
if (so == 0) {
puts("failed load " SHARED_OBJECT_ACTIVE);
puts(SDL_GetError());
break;
}
int(*shared_main)(int, char **, void **) = SDL_LoadFunction(so, SHARED_MAIN);
if(shared_main(argc, argv, &u_data) != 0)
break;
SDL_UnloadObject(so);
}
quit:
SDL_Quit();
puts("done.");
return 0;
}
|
__label__pos
| 0.999959 |
Unleashing the Power of CMS Software: Streamlining Content Management for Businesses
CMS Software: Simplifying Content Management for Businesses
In today’s digital age, businesses are constantly striving to create and manage engaging online content. Whether it’s a website, blog, or e-commerce platform, the ability to efficiently manage and update content is crucial. This is where Content Management System (CMS) software comes into play.
A CMS software is a powerful tool that simplifies the process of creating, organizing, and publishing digital content. It provides businesses with a user-friendly interface that allows even non-technical users to manage their website or online platform effectively. With a CMS software in place, businesses can take control of their content without relying on external developers or IT specialists.
One of the key benefits of using CMS software is its ease of use. The intuitive interface enables users to create and update content effortlessly. Whether it’s adding new pages, uploading images, or editing existing text, the process is streamlined and requires no coding knowledge. This empowers businesses to make real-time changes to their websites, ensuring that information is always up-to-date and relevant.
Furthermore, CMS software offers flexibility in terms of design and customization. It provides businesses with a range of templates and themes that can be easily customized to match their brand identity. This allows for consistent branding across all web pages and enhances the overall user experience. Additionally, CMS software often supports plugins and extensions that provide additional functionality such as e-commerce capabilities or social media integration.
Another significant advantage of using CMS software is its collaborative nature. Multiple users can access the system simultaneously, allowing for efficient teamwork among content creators, editors, and administrators. This promotes collaboration within the organization and ensures that everyone involved can contribute to the content creation process seamlessly.
Moreover, CMS software enhances search engine optimization (SEO) efforts. It enables businesses to optimize their website for search engines by providing features like meta tags, keyword optimization tools, and clean URL structures. These SEO-friendly features help improve search engine rankings, making it easier for potential customers to find the business online.
Security is also a top priority when it comes to CMS software. Reputable CMS platforms regularly release updates and security patches to protect against vulnerabilities and cyber threats. This ensures that businesses can maintain a secure online presence and safeguard their valuable data.
In conclusion, CMS software has revolutionized the way businesses manage their digital content. Its user-friendly interface, customization options, collaboration capabilities, SEO features, and security measures make it an indispensable tool for businesses of all sizes. By utilizing CMS software, businesses can streamline their content management processes, save time and resources, and ultimately enhance their online presence.
5 Frequently Asked Questions About CMS Software Answered
1. What is the best CMS software?
2. How much does CMS software cost?
3. What features should I look for in a CMS software?
4. How can I make my website more user-friendly with a CMS software?
5. How easy is it to learn how to use a CMS software?
What is the best CMS software?
Choosing the best CMS software depends on various factors, including your specific needs, budget, technical expertise, and scalability requirements. However, several CMS platforms have gained popularity and are widely regarded as top choices in the industry. Here are some of the leading CMS software options:
1. WordPress: WordPress is one of the most popular and widely used CMS platforms worldwide. It offers a user-friendly interface, a vast selection of themes and plugins for customization, and a large community for support. It is highly flexible and suitable for various types of websites, from blogs to e-commerce sites.
2. Drupal: Drupal is known for its robustness and scalability. It is a powerful CMS platform that can handle complex websites with high traffic volumes. Drupal offers extensive customization options, advanced security features, and strong multilingual capabilities.
3. Joomla: Joomla is another popular choice that strikes a balance between ease of use and flexibility. It offers a wide range of features to create different types of websites, including e-commerce stores and social networks. Joomla has an active community and provides good support for users.
4. Magento: If you’re specifically looking for an e-commerce-focused CMS platform, Magento is a top contender. It offers comprehensive e-commerce functionality with advanced inventory management, marketing tools, and scalability options.
5. Shopify: Shopify is a cloud-based CMS platform designed specifically for creating online stores. It provides an all-in-one solution with easy setup, secure hosting, mobile responsiveness, and various built-in features to manage products, payments, shipping, and more.
6. Wix: Wix is a user-friendly website builder that also functions as a CMS platform. It offers drag-and-drop functionality with pre-designed templates suitable for different industries. Wix provides hosting services along with integrated features like SEO optimization tools.
It’s important to note that each CMS software has its own strengths and weaknesses depending on your specific requirements. It’s recommended to evaluate your needs, research the features and capabilities of each CMS platform, and consider seeking expert advice or consulting with professionals to determine the best fit for your business.
How much does CMS software cost?
The cost of CMS software can vary significantly depending on several factors such as the specific features and functionalities required, the size and complexity of the business, and the chosen CMS platform.
There are generally two types of CMS software: open-source and proprietary.
Open-source CMS software is free to use and can be downloaded and installed without any licensing fees. Examples of popular open-source CMS platforms include WordPress, Joomla, and Drupal. While the core software is free, there may still be costs associated with additional themes, plugins, or professional services for customization or support.
On the other hand, proprietary CMS software is developed by specific companies or vendors who charge a licensing fee for its use. The cost can vary greatly depending on the vendor and the level of customization or support required. Proprietary CMS platforms often offer additional features and dedicated customer support but come at a higher price point compared to open-source options.
It’s important to note that in addition to the initial software costs, businesses should also consider ongoing expenses such as hosting fees, maintenance costs, updates, security measures, and any additional integrations or customizations that may be required.
Ultimately, the cost of CMS software will depend on your specific business needs and budget. It’s recommended to evaluate different options based on their features, scalability, support services, user reviews, and overall value for money before making a decision.
What features should I look for in a CMS software?
When selecting a CMS software, it’s important to consider the specific needs and requirements of your business. Here are some key features to look for:
1. User-Friendly Interface: Choose a CMS software with an intuitive and user-friendly interface that allows non-technical users to easily create, edit, and manage content without requiring extensive coding knowledge.
2. Customization Options: Look for a CMS software that offers a range of templates, themes, and design options that can be customized to match your brand identity. This flexibility allows you to create a unique and visually appealing website.
3. Content Creation and Editing Tools: Ensure that the CMS software provides robust content creation and editing tools. These tools should include features such as WYSIWYG (What You See Is What You Get) editors, image uploading capabilities, multimedia support, and formatting options.
4. Scalability: Consider the scalability of the CMS software. It should be able to handle your current content management needs while also being capable of accommodating future growth as your business expands.
5. Multi-User Collaboration: Look for CMS software that supports multiple user accounts with different access levels and permissions. This feature enables efficient collaboration among content creators, editors, and administrators within your organization.
6. SEO-Friendly Features: Choose a CMS software that offers built-in SEO features or integrates well with popular SEO plugins. These features should include options for optimizing meta tags, URLs, headers, and other elements essential for improving search engine rankings.
7. Mobile Responsiveness: In today’s mobile-centric world, it is crucial for your website to be responsive on various devices such as smartphones and tablets. Ensure that the CMS software you choose supports mobile responsiveness or provides responsive design templates.
8. E-commerce Capabilities: If you plan to sell products or services online, consider a CMS software with built-in e-commerce capabilities or seamless integration with popular e-commerce platforms. This will enable you to set up and manage an online store efficiently.
9. Security Features: Prioritize the security of your website and data. Look for CMS software that offers regular updates, security patches, and robust user authentication mechanisms to protect against cyber threats.
10. Support and Community: Consider the availability of support resources such as documentation, tutorials, forums, and customer support channels offered by the CMS software provider. A strong community of users can also provide valuable insights and assistance when needed.
Remember to thoroughly evaluate your options, read reviews, and consider your specific business needs before making a decision.
How can I make my website more user-friendly with a CMS software?
Making your website more user-friendly with a CMS software involves implementing several key strategies. Here are some tips to enhance the user experience:
1. Responsive Design: Ensure that your website is mobile-friendly and responsive across different devices and screen sizes. A CMS software typically offers responsive templates or themes that automatically adjust the layout for optimal viewing on smartphones, tablets, and desktops.
2. Clear Navigation: Simplify your website’s navigation by organizing content into logical categories and using descriptive labels for menu items. Users should be able to easily find what they’re looking for without confusion or frustration.
3. Intuitive Interface: Customize the CMS software’s interface to match your brand’s visual identity while keeping it clean and uncluttered. Use consistent design elements, such as font styles, colors, and buttons, throughout your website to provide a cohesive experience.
4. Streamlined Content Creation: Take advantage of the CMS software’s content creation features to make it easier for users to add and update content on your website. Provide clear instructions or tutorials for non-technical users to navigate the CMS interface effectively.
5. Optimized Page Load Speed: Optimize your website’s performance by compressing images, minifying CSS and JavaScript files, and leveraging caching mechanisms provided by the CMS software. Faster page load times improve user satisfaction and decrease bounce rates.
6. Readable Typography: Choose legible fonts with appropriate sizes and line spacing to ensure easy reading across different devices. Avoid using excessive decorative fonts that may hinder readability.
7. Multimedia Integration: Utilize the multimedia capabilities of the CMS software to enhance engagement on your website. Incorporate images, videos, infographics, or audio elements strategically within your content to make it more visually appealing and informative.
8. Consistent Branding: Maintain consistent branding elements throughout your website using customizable templates offered by the CMS software. This includes incorporating your logo, color scheme, typography, and tone of voice in all aspects of your website.
9. Accessibility Features: Implement accessibility features such as alt text for images, proper heading structure, and keyboard navigation options. This ensures that your website is inclusive and can be easily accessed by users with disabilities.
10. User Feedback and Testing: Regularly gather user feedback through surveys, feedback forms, or usability testing to identify areas for improvement. Use this feedback to make iterative changes to your website’s design and functionality using the CMS software.
By implementing these user-friendly strategies with the help of a CMS software, you can create a positive user experience that encourages visitors to engage with your content, stay longer on your website, and ultimately achieve your business goals.
How easy is it to learn how to use a CMS software?
Learning how to use a CMS software can vary depending on the specific platform and the user’s familiarity with technology. However, in general, CMS software is designed to be user-friendly and accessible to individuals with little to no technical background. Here are some factors that contribute to the ease of learning:
1. Intuitive Interface: CMS software typically offers a user-friendly interface that simplifies content management tasks. The interface is designed with clear navigation menus, drag-and-drop functionality, and WYSIWYG (What You See Is What You Get) editors, allowing users to easily create and edit content without any coding knowledge.
2. Documentation and Tutorials: Most CMS platforms provide comprehensive documentation, tutorials, and video guides that walk users through the various features and functionalities of the software. These resources help users understand how to perform specific tasks step-by-step, making it easier for them to learn at their own pace.
3. Community Support: Many popular CMS platforms have active online communities where users can seek help from fellow users or experts. Forums, discussion boards, and social media groups dedicated to the CMS software can provide valuable insights, tips, and troubleshooting assistance.
4. Training Resources: In addition to documentation and community support, some CMS software providers offer training resources such as webinars or online courses. These resources can provide more structured learning experiences for users who prefer guided instruction.
5. Familiarity with Similar Tools: If a user has prior experience with other content management systems or website builders, they may find it easier to adapt to a new CMS software since many platforms share similar concepts and functionalities.
It’s important to note that while learning the basics of using a CMS software can be relatively straightforward, mastering advanced features or customizations may require more time and practice. Additionally, each CMS platform has its own unique interface and features, so there may be a learning curve when switching between different systems.
Overall, with the user-friendly nature of CMS software, the availability of resources, and a willingness to explore and experiment, individuals can quickly become proficient in using a CMS software to manage their digital content effectively.
Leave a comment
Your email address will not be published. Required fields are marked *
Time limit exceeded. Please complete the captcha once again.
|
__label__pos
| 0.948005 |
answersLogoWhite
0
Best Answer
Ummm, would you believe 1200 square feet?
User Avatar
Wiki User
12y ago
This answer is:
User Avatar
Add your answer:
Earn +20 pts
Q: How many square feet is at 1200 square foot house?
Write your answer...
Submit
Still have questions?
magnify glass
imp
Related questions
How many square foot is in 1200 square meter?
1200 square meters is 12,916.69 square feet.
How many square feet in a 1200 square foot home?
1,200
How do you calculate 1200 square feet at 7.25 per square foot?
A 1,200 square feet parcel at $7.25 per square foot is worth: 1200 sq.ft. X $7.25/sq.ft. = $8,700
What size attic fan is needed for a home measuring 1200 square feet?
My home needs ventilation. What size attic fan would I need for a 1200 square foot house?
What is the square feet in a house 30 feet by 40 feet?
The area of 30 feet times 40 feet are 1200 square feet. But, when a house is advertised as containing 'xx square feet of living area', that can include second and third floors or a finished basement or attic, so a 30 X 40 house could be a 6000 square foot home.
What is a 1200 square foot building?
a building with a total floorspace of 1,200 square feet. For instance, a building that is 40 feet wide and 30 feet long would have 1200 square feet of floor space.
1200 square foot house how many btu needed?
82285btu.
What is the square foot of a house 30x40 feet?
1,200 square feet.
What is 1200 cm square in feet?
1 200 square centimeter = 1.291 669 25 square foot
How many yards of sand do you need to cover 1200 sq ft?
depends on the depth that you need to cover the 1200 square feet (area) to. there are 3 foot to 1 yard (1 foot=3 yards). so 1 square foot = 9 square yards (3x3). 1200 square feet = 1200 x9 = 10,800 square yards. you then multiply the 10,800 by the amount of yards (depth) that you want to cover the area to.
How much water in an area of 1200 square feet at a depth of 1 foot?
1200 sf x 1 ft = 1200 cubic feet x 7.48 gallons/cf = 8976 gallons.
1200 square meters equals how many foot squared?
1 sq metre = 10.7639 sq feet so 1200 sq metres = 12916.6925 sq feet
|
__label__pos
| 1 |
Scroll To Top
Reader Level:
Article
PHP
Use Stored Procedure in PHP
By Sharad Gupta on Dec 17, 2012
In this article I am going to explain how to create a Stored Procedure in PHP and how to call it.
Introduction
• A Stored Procedures is a precompiled SQL statement stored in the database for later use. Within a Stored Procedure you can write procedural code that controls the flow of execution. That includes if or else constructs, and error-handling code.
• A Stored Procedure helps improve performance when performing repetitive tasks because they are compiled the first time they are executed.
• A Stored Procedure can be used to share application logic to other front-end applications, thus making it easier to change business rules or policies.
Simple syntax of a Stored Procedure
CREATE/ ALTER PROCEDURE procedure_name (parameters...)
BEGIN
DECLARE variable_name datatype;
.......
.......// Sql statements
.......
END
The CREATE PROCEDURE statement creates the procedure. The code with in the CREATE PROCEDURE statement is defined by a block of code that begins with the BEGIN keyword and ends with the END keyword. The DECLARE statement is used to define a variable name.
Parameter in Stored Procedure
A Stored Procedure can have IN, INOUT and OUT parameters, depending on the MySQL version.
1. IN
Passes a value into a procedure.
2. OUT
Passes a value from a procedure back to the caller.
3. INOUT
The caller initializes an INOUT parameter, but the procedure can modify the value, and the final value is visible to the caller when the procedure returns.
You can create a Stored Procedures (sp) using a PHP application and you can also use it in a PHP application. Here I am describing step-by-step how to create a sp in PHP and how to use it in a PHP application.
Step 1
For creating a Stored Procedure you must use a CREATE PROCEDURE statement.
CREATE PROCEDURE test()
BEGIN
SELECT * FROM EMP
END
If you want to make any changes to a previously created Stored Procedure, you can use the "ALTER statement" instead of the CREATE statement.
ALTER PROCEDURE test()
SELECT name FROM EMP WHERE id=102
If you want to drop any procedure permanently from a database. use "DROP statement" before the procedure statement.
DROP PROCEDURE IF EXISTS TEST;
Step 2
The "CALL SQL statement" is used to execute a Stored Procedure.
CALL procedure_name
CALL test()
Example of Stored Procedure in PHP
<?php
$con=mysql_connect("localhost","sharad","gupta");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Employees", $con);
print "<h2>MySQL: Simple Select statement</h2>";
$result = mysql_query("select * fromemp");
while($row = mysql_fetch_array($result))
{
echo $row['id'] ."". $row['FirstName'] . "" . $row['LastName'];
echo "<br/>";
}
print "<h2>MySQL: Creating Stored Procedure</h2>";
$qry = mysql_query("create procedure user() select * from emp");
echo "Stored Procedure created.";
mysql_query($qry,$con);
print "<h2>MySQL: Calling Stored procedure</h2>";
$res = mysql_query("call user()");
while($row=mysql_fetch_array($res))
{
echo $row['id'] ." ". $row['FirstName'] . " " . $row['LastName'];
echo "<br/>";
}
mysql_close($con);
?>
NOTE: In the example given above I have covered three (3) important statements. First I created a simple SQL statement, second created a Stored Procedure and third I called the Stored Procedure in the front end using PHP code.
Output
stored-procedure-in-php.jpg
|
__label__pos
| 0.775726 |
segmentation fault while building dominator tree in clang
Hello,
This is my first post in this list. I am building an analysis tool in ClangTool.I am getting segmentation fault while building a dominator tree in clang. The sample code that I am using to build the dominator tree is the following:
const Decl* D=static_cast<Decl *>(f); // FunctionDecl f
AnalysisDeclContextManager *analDeclCtxMgr=new AnalysisDeclContextManager(context);
if(AnalysisDeclContext *analDeclCtx=analDeclCtxMgr->getContext(D)){
DominatorTree domTree;
domTree.buildDominatorTree(*analDeclCtx);
}
The input function for my tool is the following code from perlbench(CPU 2017)
static bool
S_adjust_index(pTHX_ AV *av, const MAGIC *mg, SSize_t *keyp)
{
bool adjust_index = 1;
if (mg) {
/* Handle negative array indices 20020222 MJD */
SV * const ref = SvTIED_obj(MUTABLE_SV(av), mg);
SvGETMAGIC(ref);
if (SvROK(ref) && SvOBJECT(SvRV(ref))) {
SV * const * const negative_indices_glob =
hv_fetchs(SvSTASH(SvRV(ref)), NEGATIVE_INDICES_VAR, 0);
if (negative_indices_glob && isGV(*negative_indices_glob)
&& SvTRUE(GvSV(*negative_indices_glob)))
adjust_index = 0;
}
}
if (adjust_index) {
*keyp += AvFILL(av) + 1;
if (*keyp < 0)
return FALSE;
}
return TRUE;
}
Would you please let me know where the problem is?
Thanks,
Masud
Hi!
I recently fiddled around this part of the code as well when trying to implement an improvement for my checker in the StaticAnalyzer. For the following invocation:
clang -cc1 -analyze -analyzer-checker=debug.DumpDominators (clang repository)test/Analysis/cxx-uninitialized-object-unguarded-access.cpp
I received a segfault. I eventually figured that Clang’s CFG contains nullpointers, and the following patch on LLVM fixed the issue:
diff --git a/include/llvm/Support/GenericDomTreeConstruction.h b/include/llvm/Support/GenericDomTreeConstruction.h
index ccceba88171…a4a238c310b 100644
— a/include/llvm/Support/GenericDomTreeConstruction.h
+++ b/include/llvm/Support/GenericDomTreeConstruction.h
@@ -235,6 +235,9 @@ struct SemiNCAInfo {
constexpr bool Direction = IsReverse != IsPostDom; // XOR.
for (const NodePtr Succ :
ChildrenGetter::Get(BB, BatchUpdates)) {
• if (!Succ)
• continue;
const auto SIT = NodeToInfo.find(Succ);
// Don’t visit nodes more than once but remember to collect
// ReverseChildren.
However, I’m not sure whether the CFG is supposed to have nullpointers – logically, maybe this isn’t where we should fix this issue. An assert wouldn’t hurt though.
Good luck!
Kristóf
However, I’m not sure whether the CFG is supposed to have nullpointers – logically, maybe this isn’t where we should fix this issue
DomTree requires llvm::children and llvm::inverse_children to return valid node pointers.
A proper fix would be not to return nulls from llvm::children. I’m not familiar with the Clang CFG – why do nullptr appear there in the first place?
Best,
Kuba
However, I’m not sure whether the CFG is supposed to have nullpointers – logically, maybe this isn’t where we should fix this issue
DomTree requires llvm::children and llvm::inverse_children to return valid node pointers.
A proper fix would be not to return nulls from llvm::children. I’m not familiar with the Clang CFG – why do nullptr appear there in the first place?
Maybe I’m just wrong, I didn’t investigate that much :slight_smile:
|
__label__pos
| 0.956393 |
Answers
Solutions by everydaycalculation.com
Answers.everydaycalculation.com » A% of what number is B
1 percent of what number is 2100?
2100 is 1% of 210000
Steps to solve "2100 is 1 percent of what number?"
1. We have, 1% × x = 2100
2. or, 1/100 × x = 2100
3. Multiplying both sides by 100 and dividing both sides by 1,
we have x = 2100 × 100/1
4. x = 210000
If you are using a calculator, simply enter 2100×100÷1, which will give you the answer.
MathStep (Works offline)
Download our mobile app and learn how to work with percentages in your own time:
Android and iPhone/ iPad
More percentage problems:
Find another
is % of
© everydaycalculation.com
|
__label__pos
| 0.998415 |
How To Check If Multiple Variables Are Equal In Python
Check if multiple variables are equal in Python
If you are looking for an instruction to check if multiple variables are equal in Python, keep reading our article. Today, we will provide a few methods to show you how to implement code.
Check if multiple variables are equal in Python
Compare discrete variables by the operator “==”
Like other programming languages, you can use the operator “==” to compare two variables. Moreover, you can still use it to compare multiple variables. The variables can be an integer, a string, a list, a dictionary, etc. The result is a boolean value. True if all the variables are equal to each other. Otherwise, the result is false.
Syntax:
var1 == var2 == var3 == … == varN
Detailed implementation in the following code:
Code:
myTuple = (1, 2, 3, 4, 5)
myList = [1, 2, 3, 4, 5]
myInt = 2
# Compare the second element of the tuple, the list, and the number
print(myTuple[1] == myList[1] == myInt )
Result:
True
Compare elements of an iterable by the function all()
In this part, we will introduce you to compare many elements in an iterable with the function all(). The function returns true if all the elements or conditions are true, otherwise returns false.
In the example below, we use the function to compare all the elements with the first element. If they are equal to the first element, they are all the same. So, the result of the function will be true. We also use list comprehension techniques to traverse the list.
Code:
myList = [3, 3, 3, 3, 3, 3]
# Compare all elements of the list with the first element
print (all(element == myList[0] for element in myList))
Result:
True
Compare elements of an iterable by the operator “==”
We all know how to use the operator “==” to compare multiple variables in the first part. Now we will use the operator to compare an iterable’s elements.
Code:
myList = [3, 3, 3, 3, 3, 3]
# Function to check if all elements are equal
def check_equal(aList):
# Loop the list
for i in aList:
# Compare each element with the first element return false if there is a different value
if i != aList[0]:
return False
return True
print(check_equal(myList))
Result:
True
Summary
Our tutorial provides detailed examples to check if multiple variables are equal in Python. If you want to compare discrete variables, use the operator “==”, and if you compare multiple elements of an iterable such as a list, use the function all().
Maybe you are interested:
Leave a Reply
Your email address will not be published. Required fields are marked *
|
__label__pos
| 0.974459 |
3.7 Granting Access to EM Express for Nonadministrative Users
As a database administrator, you can log in to Oracle Enterprise Manager Database Express (EM Express) with the SYS or SYSTEM user account to perform administrative and other tasks. Nonadministrative users may also want to log in to EM Express. For example, application developers may want to take advantage of the EM Express interface to create or modify tables, indexes, views, and so on. You must grant access to EM Express to these users before they can log in.
For nonadministrative users to have access to EM Express, they must be granted the EM_EXPRESS_BASIC or the EM_EXPRESS_ALL role.
The EM_EXPRESS_BASIC role enables users to connect to EM Express and to view the pages in read-only mode. The EM_EXPRESS_BASIC role includes the SELECT_CATALOG_ROLE role.
The EM_EXPRESS_ALL role enables users to connect to EM Express and use all the functionality provided by EM Express (read/write access to all EM Express features). The EM_EXPRESS_ALL role includes the EM_EXPRESS_BASIC role.
For an example of granting privileges and roles to a user account, see "Example: Granting Privileges and Roles to a User Account".
See Also:
|
__label__pos
| 0.675183 |
Skip to main content
Integrate a payment form with your website
Zuora
Integrate a payment form with your website
The Payment Form Implementation Guide provides detailed instructions on integrating a payment form. Follow these steps for a smooth learning path:
1. Download the sample code from the implementation guide and complete the Quick Start tasks to quickly get a payment form up and running in a few minutes.
2. Complete the Customize tasks to personalize the checkout and return page.
3. Follow the additional steps in the Integrate section to integrate the payment form with your own website.
The following diagram shows how the hosted payment form works.
1. When your customers are ready to pay, your checkout page creates a payment session.
2. You mount the payment form component on your website to show the form.
3. Your customers enter payment details and complete the transaction.
paymentFormWorkflow.png
|
__label__pos
| 0.728707 |
package Cwd; =head1 NAME Cwd - get pathname of current working directory =head1 SYNOPSIS use Cwd; my $dir = getcwd; use Cwd 'abs_path'; my $abs_path = abs_path($file); =head1 DESCRIPTION This module provides functions for determining the pathname of the current working directory. It is recommended that getcwd (or another *cwd() function) be used in I code to ensure portability. By default, it exports the functions cwd(), getcwd(), fastcwd(), and fastgetcwd() (and, on Win32, getdcwd()) into the caller's namespace. =head2 getcwd and friends Each of these functions are called without arguments and return the absolute path of the current working directory. =over 4 =item getcwd my $cwd = getcwd(); Returns the current working directory. Exposes the POSIX function getcwd(3) or re-implements it if it's not available. =item cwd my $cwd = cwd(); The cwd() is the most natural form for the current architecture. For most systems it is identical to `pwd` (but without the trailing line terminator). =item fastcwd my $cwd = fastcwd(); A more dangerous version of getcwd(), but potentially faster. It might conceivably chdir() you out of a directory that it can't chdir() you back into. If fastcwd encounters a problem it will return undef but will probably leave you in a different directory. For a measure of extra security, if everything appears to have worked, the fastcwd() function will check that it leaves you in the same directory that it started in. If it has changed it will C with the message "Unstable directory path, current directory changed unexpectedly". That should never happen. =item fastgetcwd my $cwd = fastgetcwd(); The fastgetcwd() function is provided as a synonym for cwd(). =item getdcwd my $cwd = getdcwd(); my $cwd = getdcwd('C:'); The getdcwd() function is also provided on Win32 to get the current working directory on the specified drive, since Windows maintains a separate current working directory for each drive. If no drive is specified then the current drive is assumed. This function simply calls the Microsoft C library _getdcwd() function. =back =head2 abs_path and friends These functions are exported only on request. They each take a single argument and return the absolute pathname for it. If no argument is given they'll use the current working directory. =over 4 =item abs_path my $abs_path = abs_path($file); Uses the same algorithm as getcwd(). Symbolic links and relative-path components ("." and "..") are resolved to return the canonical pathname, just like realpath(3). =item realpath my $abs_path = realpath($file); A synonym for abs_path(). =item fast_abs_path my $abs_path = fast_abs_path($file); A more dangerous, but potentially faster version of abs_path. =back =head2 $ENV{PWD} If you ask to override your chdir() built-in function, use Cwd qw(chdir); then your PWD environment variable will be kept up to date. Note that it will only be kept up to date if all packages which use chdir import it from Cwd. =head1 NOTES =over 4 =item * Since the path seperators are different on some operating systems ('/' on Unix, ':' on MacPerl, etc...) we recommend you use the File::Spec modules wherever portability is a concern. =item * Actually, on Mac OS, the C, C and C functions are all aliases for the C function, which, on Mac OS, calls `pwd`. Likewise, the C function is an alias for C. =back =head1 AUTHOR Originally by the perl5-porters. Maintained by Ken Williams =head1 COPYRIGHT Copyright (c) 2004 by the Perl 5 Porters. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Portions of the C code in this library are copyright (c) 1994 by the Regents of the University of California. All rights reserved. The license on this code is compatible with the licensing of the rest of the distribution - please see the source code in F for the details. =head1 SEE ALSO L =cut use strict; use Exporter; use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION); $VERSION = '3.30'; my $xs_version = $VERSION; $VERSION = eval $VERSION; @ISA = qw/ Exporter /; @EXPORT = qw(cwd getcwd fastcwd fastgetcwd); push @EXPORT, qw(getdcwd) if $^O eq 'MSWin32'; @EXPORT_OK = qw(chdir abs_path fast_abs_path realpath fast_realpath); # sys_cwd may keep the builtin command # All the functionality of this module may provided by builtins, # there is no sense to process the rest of the file. # The best choice may be to have this in BEGIN, but how to return from BEGIN? if ($^O eq 'os2') { local $^W = 0; *cwd = defined &sys_cwd ? \&sys_cwd : \&_os2_cwd; *getcwd = \&cwd; *fastgetcwd = \&cwd; *fastcwd = \&cwd; *fast_abs_path = \&sys_abspath if defined &sys_abspath; *abs_path = \&fast_abs_path; *realpath = \&fast_abs_path; *fast_realpath = \&fast_abs_path; return 1; } # Need to look up the feature settings on VMS. The preferred way is to use the # VMS::Feature module, but that may not be available to dual life modules. my $use_vms_feature; BEGIN { if ($^O eq 'VMS') { if (eval { local $SIG{__DIE__}; require VMS::Feature; }) { $use_vms_feature = 1; } } } # Need to look up the UNIX report mode. This may become a dynamic mode # in the future. sub _vms_unix_rpt { my $unix_rpt; if ($use_vms_feature) { $unix_rpt = VMS::Feature::current("filename_unix_report"); } else { my $env_unix_rpt = $ENV{'DECC$FILENAME_UNIX_REPORT'} || ''; $unix_rpt = $env_unix_rpt =~ /^[ET1]/i; } return $unix_rpt; } # Need to look up the EFS character set mode. This may become a dynamic # mode in the future. sub _vms_efs { my $efs; if ($use_vms_feature) { $efs = VMS::Feature::current("efs_charset"); } else { my $env_efs = $ENV{'DECC$EFS_CHARSET'} || ''; $efs = $env_efs =~ /^[ET1]/i; } return $efs; } # If loading the XS stuff doesn't work, we can fall back to pure perl eval { if ( $] >= 5.006 ) { require XSLoader; XSLoader::load( __PACKAGE__, $xs_version); } else { require DynaLoader; push @ISA, 'DynaLoader'; __PACKAGE__->bootstrap( $xs_version ); } }; # Must be after the DynaLoader stuff: $VERSION = eval $VERSION; # Big nasty table of function aliases my %METHOD_MAP = ( VMS => { cwd => '_vms_cwd', getcwd => '_vms_cwd', fastcwd => '_vms_cwd', fastgetcwd => '_vms_cwd', abs_path => '_vms_abs_path', fast_abs_path => '_vms_abs_path', }, MSWin32 => { # We assume that &_NT_cwd is defined as an XSUB or in the core. cwd => '_NT_cwd', getcwd => '_NT_cwd', fastcwd => '_NT_cwd', fastgetcwd => '_NT_cwd', abs_path => 'fast_abs_path', realpath => 'fast_abs_path', }, dos => { cwd => '_dos_cwd', getcwd => '_dos_cwd', fastgetcwd => '_dos_cwd', fastcwd => '_dos_cwd', abs_path => 'fast_abs_path', }, # QNX4. QNX6 has a $os of 'nto'. qnx => { cwd => '_qnx_cwd', getcwd => '_qnx_cwd', fastgetcwd => '_qnx_cwd', fastcwd => '_qnx_cwd', abs_path => '_qnx_abs_path', fast_abs_path => '_qnx_abs_path', }, cygwin => { getcwd => 'cwd', fastgetcwd => 'cwd', fastcwd => 'cwd', abs_path => 'fast_abs_path', realpath => 'fast_abs_path', }, epoc => { cwd => '_epoc_cwd', getcwd => '_epoc_cwd', fastgetcwd => '_epoc_cwd', fastcwd => '_epoc_cwd', abs_path => 'fast_abs_path', }, MacOS => { getcwd => 'cwd', fastgetcwd => 'cwd', fastcwd => 'cwd', abs_path => 'fast_abs_path', }, ); $METHOD_MAP{NT} = $METHOD_MAP{MSWin32}; # Find the pwd command in the expected locations. We assume these # are safe. This prevents _backtick_pwd() consulting $ENV{PATH} # so everything works under taint mode. my $pwd_cmd; foreach my $try ('/bin/pwd', '/usr/bin/pwd', '/QOpenSys/bin/pwd', # OS/400 PASE. ) { if( -x $try ) { $pwd_cmd = $try; last; } } my $found_pwd_cmd = defined($pwd_cmd); unless ($pwd_cmd) { # Isn't this wrong? _backtick_pwd() will fail if somenone has # pwd in their path but it is not /bin/pwd or /usr/bin/pwd? # See [perl #16774]. --jhi $pwd_cmd = 'pwd'; } # Lazy-load Carp sub _carp { require Carp; Carp::carp(@_) } sub _croak { require Carp; Carp::croak(@_) } # The 'natural and safe form' for UNIX (pwd may be setuid root) sub _backtick_pwd { # Localize %ENV entries in a way that won't create new hash keys my @localize = grep exists $ENV{$_}, qw(PATH IFS CDPATH ENV BASH_ENV); local @ENV{@localize}; my $cwd = `$pwd_cmd`; # Belt-and-suspenders in case someone said "undef $/". local $/ = "\n"; # `pwd` may fail e.g. if the disk is full chomp($cwd) if defined $cwd; $cwd; } # Since some ports may predefine cwd internally (e.g., NT) # we take care not to override an existing definition for cwd(). unless ($METHOD_MAP{$^O}{cwd} or defined &cwd) { # The pwd command is not available in some chroot(2)'ed environments my $sep = $Config::Config{path_sep} || ':'; my $os = $^O; # Protect $^O from tainting # Try again to find a pwd, this time searching the whole PATH. if (defined $ENV{PATH} and $os ne 'MSWin32') { # no pwd on Windows my @candidates = split($sep, $ENV{PATH}); while (!$found_pwd_cmd and @candidates) { my $candidate = shift @candidates; $found_pwd_cmd = 1 if -x "$candidate/pwd"; } } # MacOS has some special magic to make `pwd` work. if( $os eq 'MacOS' || $found_pwd_cmd ) { *cwd = \&_backtick_pwd; } else { *cwd = \&getcwd; } } if ($^O eq 'cygwin') { # We need to make sure cwd() is called with no args, because it's # got an arg-less prototype and will die if args are present. local $^W = 0; my $orig_cwd = \&cwd; *cwd = sub { &$orig_cwd() } } # set a reasonable (and very safe) default for fastgetcwd, in case it # isn't redefined later (20001212 rspier) *fastgetcwd = \&cwd; # A non-XS version of getcwd() - also used to bootstrap the perl build # process, when miniperl is running and no XS loading happens. sub _perl_getcwd { abs_path('.'); } # By John Bazik # # Usage: $cwd = &fastcwd; # # This is a faster version of getcwd. It's also more dangerous because # you might chdir out of a directory that you can't chdir back into. sub fastcwd_ { my($odev, $oino, $cdev, $cino, $tdev, $tino); my(@path, $path); local(*DIR); my($orig_cdev, $orig_cino) = stat('.'); ($cdev, $cino) = ($orig_cdev, $orig_cino); for (;;) { my $direntry; ($odev, $oino) = ($cdev, $cino); CORE::chdir('..') || return undef; ($cdev, $cino) = stat('.'); last if $odev == $cdev && $oino == $cino; opendir(DIR, '.') || return undef; for (;;) { $direntry = readdir(DIR); last unless defined $direntry; next if $direntry eq '.'; next if $direntry eq '..'; ($tdev, $tino) = lstat($direntry); last unless $tdev != $odev || $tino != $oino; } closedir(DIR); return undef unless defined $direntry; # should never happen unshift(@path, $direntry); } $path = '/' . join('/', @path); if ($^O eq 'apollo') { $path = "/".$path; } # At this point $path may be tainted (if tainting) and chdir would fail. # Untaint it then check that we landed where we started. $path =~ /^(.*)\z/s # untaint && CORE::chdir($1) or return undef; ($cdev, $cino) = stat('.'); die "Unstable directory path, current directory changed unexpectedly" if $cdev != $orig_cdev || $cino != $orig_cino; $path; } if (not defined &fastcwd) { *fastcwd = \&fastcwd_ } # Keeps track of current working directory in PWD environment var # Usage: # use Cwd 'chdir'; # chdir $newdir; my $chdir_init = 0; sub chdir_init { if ($ENV{'PWD'} and $^O ne 'os2' and $^O ne 'dos' and $^O ne 'MSWin32') { my($dd,$di) = stat('.'); my($pd,$pi) = stat($ENV{'PWD'}); if (!defined $dd or !defined $pd or $di != $pi or $dd != $pd) { $ENV{'PWD'} = cwd(); } } else { my $wd = cwd(); $wd = Win32::GetFullPathName($wd) if $^O eq 'MSWin32'; $ENV{'PWD'} = $wd; } # Strip an automounter prefix (where /tmp_mnt/foo/bar == /foo/bar) if ($^O ne 'MSWin32' and $ENV{'PWD'} =~ m|(/[^/]+(/[^/]+/[^/]+))(.*)|s) { my($pd,$pi) = stat($2); my($dd,$di) = stat($1); if (defined $pd and defined $dd and $di == $pi and $dd == $pd) { $ENV{'PWD'}="$2$3"; } } $chdir_init = 1; } sub chdir { my $newdir = @_ ? shift : ''; # allow for no arg (chdir to HOME dir) $newdir =~ s|///*|/|g unless $^O eq 'MSWin32'; chdir_init() unless $chdir_init; my $newpwd; if ($^O eq 'MSWin32') { # get the full path name *before* the chdir() $newpwd = Win32::GetFullPathName($newdir); } return 0 unless CORE::chdir $newdir; if ($^O eq 'VMS') { return $ENV{'PWD'} = $ENV{'DEFAULT'} } elsif ($^O eq 'MacOS') { return $ENV{'PWD'} = cwd(); } elsif ($^O eq 'MSWin32') { $ENV{'PWD'} = $newpwd; return 1; } if (ref $newdir eq 'GLOB') { # in case a file/dir handle is passed in $ENV{'PWD'} = cwd(); } elsif ($newdir =~ m#^/#s) { $ENV{'PWD'} = $newdir; } else { my @curdir = split(m#/#,$ENV{'PWD'}); @curdir = ('') unless @curdir; my $component; foreach $component (split(m#/#, $newdir)) { next if $component eq '.'; pop(@curdir),next if $component eq '..'; push(@curdir,$component); } $ENV{'PWD'} = join('/',@curdir) || '/'; } 1; } sub _perl_abs_path { my $start = @_ ? shift : '.'; my($dotdots, $cwd, @pst, @cst, $dir, @tst); unless (@cst = stat( $start )) { _carp("stat($start): $!"); return ''; } unless (-d _) { # Make sure we can be invoked on plain files, not just directories. # NOTE that this routine assumes that '/' is the only directory separator. my ($dir, $file) = $start =~ m{^(.*)/(.+)$} or return cwd() . '/' . $start; # Can't use "-l _" here, because the previous stat was a stat(), not an lstat(). if (-l $start) { my $link_target = readlink($start); die "Can't resolve link $start: $!" unless defined $link_target; require File::Spec; $link_target = $dir . '/' . $link_target unless File::Spec->file_name_is_absolute($link_target); return abs_path($link_target); } return $dir ? abs_path($dir) . "/$file" : "/$file"; } $cwd = ''; $dotdots = $start; do { $dotdots .= '/..'; @pst = @cst; local *PARENT; unless (opendir(PARENT, $dotdots)) { # probably a permissions issue. Try the native command. return File::Spec->rel2abs( $start, _backtick_pwd() ); } unless (@cst = stat($dotdots)) { _carp("stat($dotdots): $!"); closedir(PARENT); return ''; } if ($pst[0] == $cst[0] && $pst[1] == $cst[1]) { $dir = undef; } else { do { unless (defined ($dir = readdir(PARENT))) { _carp("readdir($dotdots): $!"); closedir(PARENT); return ''; } $tst[0] = $pst[0]+1 unless (@tst = lstat("$dotdots/$dir")) } while ($dir eq '.' || $dir eq '..' || $tst[0] != $pst[0] || $tst[1] != $pst[1]); } $cwd = (defined $dir ? "$dir" : "" ) . "/$cwd" ; closedir(PARENT); } while (defined $dir); chop($cwd) unless $cwd eq '/'; # drop the trailing / $cwd; } my $Curdir; sub fast_abs_path { local $ENV{PWD} = $ENV{PWD} || ''; # Guard against clobberage my $cwd = getcwd(); require File::Spec; my $path = @_ ? shift : ($Curdir ||= File::Spec->curdir); # Detaint else we'll explode in taint mode. This is safe because # we're not doing anything dangerous with it. ($path) = $path =~ /(.*)/; ($cwd) = $cwd =~ /(.*)/; unless (-e $path) { _croak("$path: No such file or directory"); } unless (-d _) { # Make sure we can be invoked on plain files, not just directories. my ($vol, $dir, $file) = File::Spec->splitpath($path); return File::Spec->catfile($cwd, $path) unless length $dir; if (-l $path) { my $link_target = readlink($path); die "Can't resolve link $path: $!" unless defined $link_target; $link_target = File::Spec->catpath($vol, $dir, $link_target) unless File::Spec->file_name_is_absolute($link_target); return fast_abs_path($link_target); } return $dir eq File::Spec->rootdir ? File::Spec->catpath($vol, $dir, $file) : fast_abs_path(File::Spec->catpath($vol, $dir, '')) . '/' . $file; } if (!CORE::chdir($path)) { _croak("Cannot chdir to $path: $!"); } my $realpath = getcwd(); if (! ((-d $cwd) && (CORE::chdir($cwd)))) { _croak("Cannot chdir back to $cwd: $!"); } $realpath; } # added function alias to follow principle of least surprise # based on previous aliasing. --tchrist 27-Jan-00 *fast_realpath = \&fast_abs_path; # --- PORTING SECTION --- # VMS: $ENV{'DEFAULT'} points to default directory at all times # 06-Mar-1996 Charles Bailey [email protected] # Note: Use of Cwd::chdir() causes the logical name PWD to be defined # in the process logical name table as the default device and directory # seen by Perl. This may not be the same as the default device # and directory seen by DCL after Perl exits, since the effects # the CRTL chdir() function persist only until Perl exits. sub _vms_cwd { return $ENV{'DEFAULT'}; } sub _vms_abs_path { return $ENV{'DEFAULT'} unless @_; my $path = shift; my $efs = _vms_efs; my $unix_rpt = _vms_unix_rpt; if (defined &VMS::Filespec::vmsrealpath) { my $path_unix = 0; my $path_vms = 0; $path_unix = 1 if ($path =~ m#(?<=\^)/#); $path_unix = 1 if ($path =~ /^\.\.?$/); $path_vms = 1 if ($path =~ m#[\[<\]]#); $path_vms = 1 if ($path =~ /^--?$/); my $unix_mode = $path_unix; if ($efs) { # In case of a tie, the Unix report mode decides. if ($path_vms == $path_unix) { $unix_mode = $unix_rpt; } else { $unix_mode = 0 if $path_vms; } } if ($unix_mode) { # Unix format return VMS::Filespec::unixrealpath($path); } # VMS format my $new_path = VMS::Filespec::vmsrealpath($path); # Perl expects directories to be in directory format $new_path = VMS::Filespec::pathify($new_path) if -d $path; return $new_path; } # Fallback to older algorithm if correct ones are not # available. if (-l $path) { my $link_target = readlink($path); die "Can't resolve link $path: $!" unless defined $link_target; return _vms_abs_path($link_target); } # may need to turn foo.dir into [.foo] my $pathified = VMS::Filespec::pathify($path); $path = $pathified if defined $pathified; return VMS::Filespec::rmsexpand($path); } sub _os2_cwd { $ENV{'PWD'} = `cmd /c cd`; chomp $ENV{'PWD'}; $ENV{'PWD'} =~ s:\\:/:g ; return $ENV{'PWD'}; } sub _win32_cwd { if (defined &DynaLoader::boot_DynaLoader) { $ENV{'PWD'} = Win32::GetCwd(); } else { # miniperl chomp($ENV{'PWD'} = `cd`); } $ENV{'PWD'} =~ s:\\:/:g ; return $ENV{'PWD'}; } *_NT_cwd = defined &Win32::GetCwd ? \&_win32_cwd : \&_os2_cwd; sub _dos_cwd { if (!defined &Dos::GetCwd) { $ENV{'PWD'} = `command /c cd`; chomp $ENV{'PWD'}; $ENV{'PWD'} =~ s:\\:/:g ; } else { $ENV{'PWD'} = Dos::GetCwd(); } return $ENV{'PWD'}; } sub _qnx_cwd { local $ENV{PATH} = ''; local $ENV{CDPATH} = ''; local $ENV{ENV} = ''; $ENV{'PWD'} = `/usr/bin/fullpath -t`; chomp $ENV{'PWD'}; return $ENV{'PWD'}; } sub _qnx_abs_path { local $ENV{PATH} = ''; local $ENV{CDPATH} = ''; local $ENV{ENV} = ''; my $path = @_ ? shift : '.'; local *REALPATH; defined( open(REALPATH, '-|') || exec '/usr/bin/fullpath', '-t', $path ) or die "Can't open /usr/bin/fullpath: $!"; my $realpath = ; close REALPATH; chomp $realpath; return $realpath; } sub _epoc_cwd { $ENV{'PWD'} = EPOC::getcwd(); return $ENV{'PWD'}; } # Now that all the base-level functions are set up, alias the # user-level functions to the right places if (exists $METHOD_MAP{$^O}) { my $map = $METHOD_MAP{$^O}; foreach my $name (keys %$map) { local $^W = 0; # assignments trigger 'subroutine redefined' warning no strict 'refs'; *{$name} = \&{$map->{$name}}; } } # In case the XS version doesn't load. *abs_path = \&_perl_abs_path unless defined &abs_path; *getcwd = \&_perl_getcwd unless defined &getcwd; # added function alias for those of us more # used to the libc function. --tchrist 27-Jan-00 *realpath = \&abs_path; 1;
|
__label__pos
| 0.995133 |
Implementation
Background
To monitor the network status in real-time and to obtain detailed network topology and changes in the topology, network administrators usually deploy the Link Layer Discovery Protocol (LLDP) on live networks. LLDP, however, has limited applications due to the following characteristics:
• LLDP uniquely identifies a device by its IP address. IP addresses are expressed in dotted decimal notation and therefore are not easy to maintain or manage, when compared with NE IDs that are expressed in decimal integers.
• LLDP is not supported on Ethernet sub-interfaces, Eth-Trunk interfaces, or low-speed interfaces, and therefore cannot discover neighbors for these types of interfaces.
• LLDP-enabled devices periodically broadcast LLDP packets, consuming many system resources and even affecting the transmission of user services.
Link Automatic Discovery (LAD) addresses the preceding problems and is more flexible:
• LAD uniquely identifies a device by an NE ID in decimal integers, which are easier to maintain and manage.
• LAD can discover neighbors for various types of interfaces and therefore are more widely used than LLDP.
• LAD is triggered by an NMS or command lines and therefore can be implemented as you need.
Implementation
The following example uses the networking in Figure 1 to illustrate how LAD is implemented.
Figure 1 LAD networking
The LAD implementation is as follows:
1. DeviceA determines the interface type, encapsulates local information into a Link Detect packet, and sends the packet to DeviceB.
2. After DeviceB receives the link Detect packet, DeviceB parses the packet and encapsulates local information and DeviceA's information carried in the packet into a Link Reply packet, and sends the Link Reply packet to DeviceA.
3. After DeviceA receives the Link Reply packet, DeviceA parses the packet and saves local information and DeviceB's information carried in the packet to the local MIB. The local and neighbor information is recorded as one entry.
Local and remote devices exchange LAD packets to learn each other's NE ID, slot ID, subcard ID, interface number, and even each other's VLAN ID if sub-interfaces are used.
4. The NMS exchanges NETCONF packets with DeviceA to obtain DeviceA's local and neighbor information and then generates the topology of the entire network.
Benefits
After network administrators deploy LAD on devices, they can obtain information about all links connected to the devices. LAD helps extend the network management scale. Network administrators can obtain detailed network topology information and topology changes.
Copyright © Huawei Technologies Co., Ltd.
Copyright © Huawei Technologies Co., Ltd.
< Previous topic
|
__label__pos
| 0.971567 |
Export (0) Print
Expand All
1 out of 3 rated this helpful - Rate this topic
Advanced Settings
Applies To: Windows SBS 2008
Windows SBS 2008 automatically configures Remote Web Workplace settings. If you are an advanced user, you can manually change some settings in the registry if necessary.
CautionCaution
Incorrectly editing the registry may severely damage your system. Before making changes to the registry, you should back up any valued data on the computer.
To change the server time-out setting for Remote Web Workplace
1. On the Windows SBS 2008 server, click Start, click Administrative Tools, and then click Internet Information Services (IIS) Manager.
2. At the User Account Control prompt, click Continue.
3. In the left pane, double-click the name of the server to expand the tree.
4. Double-click Sites to expand it, and then double-click SBS Web Applications to expand it.
5. In SBS Web Applications Home, double-click Session State.
6. In Cookie Settings, change the Time-out (in minutes) to the desired amount of time.
7. Click Apply to save the changes.
To change the client time-out setting for Remote Web Workplace
1. Open Registry Editor.
2. Open the following registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SmallBusinessServer\RemoteUserPortal\PublicTimeOut
3. In the Value data box, type the number of minutes that you want to elapse before the Remote Web Workplace session times out.
ImportantImportant
The value you enter should not be larger than 1440. Otherwise, Connect to a computer and Connect to a server will not function properly.
4. Click OK.
To add a Terminal Services server in Application mode to the Select Computer drop-down list in Remote Web Workplace
1. Open Registry Editor.
2. Open the following registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SmallBusinessServer\RemoteUserPortal
noteNote
If the RemoteUserPortal key does not exist, create it.
3. Create the following multi-string (REG_MULTI_SZ) key:
TsServerNames
4. Type the name of your terminal services server. Type one name per line.
Verify that the name is exactly the same as the server. If a server key already exists, modify its value. If the type isn’t correct, remove it first, and then recreate it.
5. Click OK.
To create a new registry key that shows all computers
1. Open Registry Editor. To do this, click Start, in the search field type regedit, and then press ENTER.
2. In the User Account Control window, click Continue.
3. Browse to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\SmallBusinessServer.
4. Right-click SmallBusinessServer, click New, and then click Key.
5. Name the key BusinessProductivity.
6. Right-click BusinessProductivity, click New, and then click DWORD (32-bit) Value.
7. Name the new value ShowAllComputers.
8. Double-click ShowAllComputers, and then, in the Value data text box, type 1.
9. Click OK, and then close Registry Editor.
Did you find this helpful?
(1500 characters remaining)
Community Additions
ADD
Show:
© 2013 Microsoft. All rights reserved.
|
__label__pos
| 0.950361 |
Verified Commit 0988a1f7 authored by Sébastien Villemot's avatar Sébastien Villemot
Browse files
Generated LaTeX files are now under <basename>/latex/
parent ac9d352a
Pipeline #1517 passed with stage
in 1 minute and 25 seconds
......@@ -6062,13 +6062,13 @@ DynamicModel::writeParamsDerivativesFile(const string &basename, bool julia) con
void
DynamicModel::writeLatexFile(const string &basename, const bool write_equation_tags) const
{
writeLatexModelFile(basename + "_dynamic", ExprNodeOutputType::latexDynamicModel, write_equation_tags);
writeLatexModelFile(basename, "dynamic", ExprNodeOutputType::latexDynamicModel, write_equation_tags);
}
void
DynamicModel::writeLatexOriginalFile(const string &basename, const bool write_equation_tags) const
{
writeLatexModelFile(basename + "_original", ExprNodeOutputType::latexDynamicModel, write_equation_tags);
writeLatexModelFile(basename, "original", ExprNodeOutputType::latexDynamicModel, write_equation_tags);
}
void
......
......@@ -132,10 +132,11 @@ SteadyStateModel::checkPass(ModFileStructure &mod_file_struct, WarningConsolidat
void
SteadyStateModel::writeLatexSteadyStateFile(const string &basename) const
{
boost::filesystem::create_directories(basename + "/latex");
ofstream output, content_output;
string filename = basename + "_steady_state.tex";
string content_basename = basename + "_steady_state_content";
string content_filename = content_basename + ".tex";
string filename = basename + "/latex/steady_state.tex";
string content_filename = basename + "/latex/steady_state_content.tex";
output.open(filename, ios::out | ios::binary);
if (!output.is_open())
......@@ -172,7 +173,7 @@ SteadyStateModel::writeLatexSteadyStateFile(const string &basename) const
static_model.writeLatexAuxVarRecursiveDefinitions(content_output);
output << "\\include{" << content_basename << "}" << endl
output << "\\include{steady_state_content.tex}" << endl
<< "\\end{document}" << endl;
output.close();
......
......@@ -1834,12 +1834,13 @@ ModelTree::Write_Inf_To_Bin_File(const string &filename,
}
void
ModelTree::writeLatexModelFile(const string &basename, ExprNodeOutputType output_type, const bool write_equation_tags) const
ModelTree::writeLatexModelFile(const string &mod_basename, const string &latex_basename, ExprNodeOutputType output_type, const bool write_equation_tags) const
{
boost::filesystem::create_directories(mod_basename + "/latex");
ofstream output, content_output;
string filename = basename + ".tex";
string content_basename = basename + "_content";
string content_filename = content_basename + ".tex";
string filename = mod_basename + "/latex/" + latex_basename + ".tex";
string content_filename = mod_basename + "/latex/" + latex_basename + "_content" + ".tex";
output.open(filename, ios::out | ios::binary);
if (!output.is_open())
{
......@@ -1906,7 +1907,7 @@ ModelTree::writeLatexModelFile(const string &basename, ExprNodeOutputType output
content_output << endl << R"(\end{dmath})" << endl;
}
output << R"(\include{)" << content_basename << "}" << endl
output << R"(\include{)" << latex_basename + "_content" << "}" << endl
<< R"(\end{document})" << endl;
output.close();
......
......@@ -191,7 +191,7 @@ protected:
void compileModelEquations(ostream &code_file, unsigned int &instruction_number, const temporary_terms_t &tt, const map_idx_t &map_idx, bool dynamic, bool steady_dynamic) const;
//! Writes LaTeX model file
void writeLatexModelFile(const string &basename, ExprNodeOutputType output_type, const bool write_equation_tags) const;
void writeLatexModelFile(const string &mod_basename, const string &latex_basename, ExprNodeOutputType output_type, const bool write_equation_tags) const;
//! Sparse matrix of double to store the values of the Jacobian
/*! First index is equation number, second index is endogenous type specific ID */
......
......@@ -2380,7 +2380,7 @@ StaticModel::collect_block_first_order_derivatives()
void
StaticModel::writeLatexFile(const string &basename, bool write_equation_tags) const
{
writeLatexModelFile(basename + "_static", ExprNodeOutputType::latexStaticModel, write_equation_tags);
writeLatexModelFile(basename, "static", ExprNodeOutputType::latexStaticModel, write_equation_tags);
}
void
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment
|
__label__pos
| 0.991286 |
Commit 77d7b1e9 authored by Frank Winklmeier's avatar Frank Winklmeier
Browse files
Merge branch 'MuonSegment_surface_holder_simplify' into 'master'
MuonSegment use ptr holder. Default a few operation avoid a dynamic cast. Tidy up code
See merge request !44515
parents b76640a0 b5f4640e
/* /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration Copyright (C) 2002-2021 CERN for the benefit of the ATLAS collaboration
*/ */
/////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////
...@@ -10,181 +10,210 @@ ...@@ -10,181 +10,210 @@
#define MUONSEGMENT_MUONSEGMENT_H #define MUONSEGMENT_MUONSEGMENT_H
// Trk // Trk
#include "TrkSegment/Segment.h"
#include "TrkEventPrimitives/LocalDirection.h" #include "TrkEventPrimitives/LocalDirection.h"
#include "TrkEventPrimitives/SurfaceHolderImpl.h"
#include "TrkRIO_OnTrack/RIO_OnTrack.h"
#include "TrkSegment/Segment.h"
#include "TrkSpaceTimePoint/SpaceTimePointBase.h" #include "TrkSpaceTimePoint/SpaceTimePointBase.h"
#include "TrkSurfaces/PlaneSurface.h" #include "TrkSurfaces/PlaneSurface.h"
#include "TrkRIO_OnTrack/RIO_OnTrack.h"
namespace Muon { namespace Muon {
/** @class MuonSegment /** @class MuonSegment
This is the common class for 3D segments used in the muon spectrometer.
The Surface type for MuonSegments is restricted to be a PlaneSurface.
The parameters of the MuonSegment are:
- the Trk::LocalPosition of the segment in the surface reference frame
- the Trk::LocalDirection of the segment which consistes of the angles
@f$ \theta_{xz} @f$ and @f$\theta_{yz}@f$.
The MuonSegment stores a list of Trk::MeasurementBase objects allowing it to
contain measurements from all detector types in the muon spectrometer.
@image html segment_example.gif
@image html MuonSegment.gif
@author [email protected], [email protected], [email protected]
*/
class MuonSegment : public Trk::Segment, public Trk::SpaceTimePointBase {
public:
/** define invalid value, used when the segment has no fitted t0 */
static const float kNoValue;
/** Default Constructor for POOL */
MuonSegment();
/** Copy Constructor */
MuonSegment(const MuonSegment& seg);
/** Assignment operator */
MuonSegment& operator=(const MuonSegment& seg);
/** Constructor within standard track parameters frame taking a vector of MeasurementBase.
@param locpars 4 dim or 5 dim standard track parameters representation
@param locerr 4 x 4 error or 5 x 5 error on standard track parameters repr.
@param psf plane surface
@param cmeas vector of contained measurements on track
@param fqual fit quality object
@param author enum to indicate author, see Segment.h for the possible authors
*/
MuonSegment( const Trk::LocalParameters& locpars,
const Amg::MatrixX& locerr,
Trk::PlaneSurface* psf,
DataVector<const Trk::MeasurementBase>* cmeas,
Trk::FitQuality* fqual,
Segment::Author author=AuthorUnknown
);
/** Constructor within local parameters of the Segment taking a vector of MeasurementBase
@param segLocPos 2 local position coordinates
@param segLocalErr 2 local direction coordinates
@param segLocalErr 4 x 4 full local error
@param psf plane surface
@param cmeas vector of contained measurements on track
@param fqual fit quality object
@param author enum to indicate author, see Segment.h for the possible authors
*/
MuonSegment( const Amg::Vector2D& segLocPos, // 2 local position coordinates
const Trk::LocalDirection& segLocDir, //
const Amg::MatrixX& segLocalErr, //
Trk::PlaneSurface* psf, // plane surface to define frame
DataVector<const Trk::MeasurementBase>* cmeas, // vector of contained measurements on track
Trk::FitQuality* fqual, // fit quality object
Segment::Author author=AuthorUnknown);
/** Destructor */
virtual ~MuonSegment();
/** needed to avoid excessive RTTI*/
virtual MuonSegment* clone() const;
/** global position */
const Amg::Vector3D& globalPosition() const;
/** global direction */
const Amg::Vector3D& globalDirection() const;
/** local direction */
const Trk::LocalDirection& localDirection() const;
/** returns the surface for the local to global transformation
- interface from MeasurementBase */
const Trk::PlaneSurface& associatedSurface() const;
/** number of RIO_OnTracks */
unsigned int numberOfContainedROTs() const;
/** returns the RIO_OnTrack (also known as ROT) objects depending on the integer*/
const Trk::RIO_OnTrack* rioOnTrack(unsigned int) const;
/** set the fitted time and error on the time */
void setT0Error(float t0, float t0Error);
/** returns whether the segment has a fitted t0 */
bool hasFittedT0() const;
/** recalculate the cache */
void recalculateCache();
private:
/** The global position the surface can be associated to. Cached (not persistified)*/
Amg::Vector3D m_globalPosition;
/** cache global direction, not persistified */
Amg::Vector3D m_globalDirection;
/** LocalDirection */
Trk::LocalDirection m_localDirection;
/** The plane surface to which the segment parameters are expressed to */
const Trk::PlaneSurface* m_associatedSurface;
/** private method to clear the Trk::MeasurementBase vector */
void clearMeasVector();
protected:
/**returns some information about this RIO_OnTrack/TrackSegment.
It should be overloaded by any child classes*/
MsgStream& dump( MsgStream& out ) const;
/**returns some information about this RIO_OnTrack/TrackSegment.
It should be overloaded by any child classes*/
std::ostream& dump( std::ostream& out ) const;
};
inline const Amg::Vector3D& MuonSegment::globalPosition() const
{
return m_globalPosition;
}
inline const Amg::Vector3D& MuonSegment::globalDirection() const This is the common class for 3D segments used in the muon spectrometer.
{
return m_globalDirection;
}
inline const Trk::LocalDirection& MuonSegment::localDirection() const The Surface type for MuonSegments is restricted to be a PlaneSurface.
{ The parameters of the MuonSegment are:
return m_localDirection; - the Trk::LocalPosition of the segment in the surface reference frame
} - the Trk::LocalDirection of the segment which consistes of the angles
@f$ \theta_{xz} @f$ and @f$\theta_{yz}@f$.
inline const Trk::PlaneSurface& MuonSegment::associatedSurface() const The MuonSegment stores a list of Trk::MeasurementBase objects allowing it to
{ return (*m_associatedSurface); } contain measurements from all detector types in the muon spectrometer.
inline MuonSegment* MuonSegment::clone() const @image html segment_example.gif
{ @image html MuonSegment.gif
return new MuonSegment(*this);
}
inline const Trk::RIO_OnTrack* MuonSegment::rioOnTrack(unsigned int indx) const
{
if (indx<containedMeasurements().size()){
const Trk::RIO_OnTrack* rot=dynamic_cast<const Trk::RIO_OnTrack*>(containedMeasurements()[indx]);
return rot;
}
else return 0;
}
inline unsigned int MuonSegment::numberOfContainedROTs() const {
return containedMeasurements().size();
}
inline void MuonSegment::setT0Error(float t0, float t0Error){ @author [email protected], [email protected],
m_time=t0; m_errorTime=t0Error; [email protected]
} */
class MuonSegment final
: public Trk::Segment
, public Trk::SpaceTimePointBase
, public Trk::SurfacePtrHolderImplDetEl<Trk::PlaneSurface>
{
public:
/** define invalid value, used when the segment has no fitted t0 */
static const float kNoValue;
/** Default Constructor for POOL */
MuonSegment();
/** Copy Constructor */
MuonSegment(const MuonSegment& seg);
/** Assignment operator */
MuonSegment& operator=(const MuonSegment& seg);
/** Move Constructor */
MuonSegment(MuonSegment&& seg) noexcept = default;
/** Move Assignment operator */
MuonSegment& operator=(MuonSegment&& seg) noexcept = default;
/** Constructor within standard track parameters frame taking a vector of
MeasurementBase.
@param locpars 4 dim or 5 dim standard track parameters representation
@param locerr 4 x 4 error or 5 x 5 error on standard track parameters
repr.
@param psf plane surface
@param cmeas vector of contained measurements on track
@param fqual fit quality object
@param author enum to indicate author, see Segment.h for the possible
authors
*/
MuonSegment(const Trk::LocalParameters& locpars,
const Amg::MatrixX& locerr,
Trk::PlaneSurface* psf,
DataVector<const Trk::MeasurementBase>* cmeas,
Trk::FitQuality* fqual,
Segment::Author author = AuthorUnknown);
/** Constructor within local parameters of the Segment taking a vector of
MeasurementBase
@param segLocPos 2 local position coordinates
@param segLocalErr 2 local direction coordinates
@param segLocalErr 4 x 4 full local error
@param psf plane surface
@param cmeas vector of contained measurements on track
@param fqual fit quality object
@param author enum to indicate author, see Segment.h for the possible
authors
*/
MuonSegment(const Amg::Vector2D& segLocPos, // 2 local position coordinates
const Trk::LocalDirection& segLocDir, //
const Amg::MatrixX& segLocalErr, //
Trk::PlaneSurface* psf, // plane surface to define frame
DataVector<const Trk::MeasurementBase>*
cmeas, // vector of contained measurements on track
Trk::FitQuality* fqual, // fit quality object
Segment::Author author = AuthorUnknown);
/** Destructor */
virtual ~MuonSegment();
/** needed to avoid excessive RTTI*/
virtual MuonSegment* clone() const override final;
/** global position */
virtual const Amg::Vector3D& globalPosition() const override final;
/** global direction */
const Amg::Vector3D& globalDirection() const;
/** local direction */
const Trk::LocalDirection& localDirection() const;
/** returns the surface for the local to global transformation
- interface from MeasurementBase */
virtual const Trk::PlaneSurface& associatedSurface() const override final;
/** number of RIO_OnTracks */
unsigned int numberOfContainedROTs() const;
/** returns the RIO_OnTrack (also known as ROT) objects depending on the
* integer*/
const Trk::RIO_OnTrack* rioOnTrack(unsigned int) const;
/** set the fitted time and error on the time */
void setT0Error(float t0, float t0Error);
/** returns whether the segment has a fitted t0 */
bool hasFittedT0() const;
/** recalculate the cache */
void recalculateCache();
private:
/** The global position the surface can be associated to. Cached (not
* persistified)*/
Amg::Vector3D m_globalPosition;
/** cache global direction, not persistified */
Amg::Vector3D m_globalDirection;
/** LocalDirection */
Trk::LocalDirection m_localDirection;
/** private method to clear the Trk::MeasurementBase vector */
void clearMeasVector();
protected:
/**returns some information about this RIO_OnTrack/TrackSegment.
It should be overloaded by any child classes*/
virtual MsgStream& dump(MsgStream& out) const override final;
/**returns some information about this RIO_OnTrack/TrackSegment.
It should be overloaded by any child classes*/
virtual std::ostream& dump(std::ostream& out) const override final;
};
inline const Amg::Vector3D&
MuonSegment::globalPosition() const
{
return m_globalPosition;
}
inline const Amg::Vector3D&
MuonSegment::globalDirection() const
{
return m_globalDirection;
}
inline bool MuonSegment::hasFittedT0() const { inline const Trk::LocalDirection&
return m_time != MuonSegment::kNoValue; MuonSegment::localDirection() const
{
return m_localDirection;
}
inline const Trk::PlaneSurface&
MuonSegment::associatedSurface() const
{
return (*m_associatedSurface);
}
inline MuonSegment*
MuonSegment::clone() const
{
return new MuonSegment(*this);
}
inline const Trk::RIO_OnTrack*
MuonSegment::rioOnTrack(unsigned int indx) const
{
if (indx < containedMeasurements().size()) {
const Trk::MeasurementBase* meas = containedMeasurements()[indx];
if (meas->type(Trk::MeasurementBaseType::RIO_OnTrack)) {
return static_cast<const Trk::RIO_OnTrack*>(meas);
}
} }
return nullptr;
}
inline unsigned int
MuonSegment::numberOfContainedROTs() const
{
return containedMeasurements().size();
}
inline void
MuonSegment::setT0Error(float t0, float t0Error)
{
m_time = t0;
m_errorTime = t0Error;
}
inline bool
MuonSegment::hasFittedT0() const
{
return m_time != MuonSegment::kNoValue;
}
} }
......
/* /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration Copyright (C) 2002-2021 CERN for the benefit of the ATLAS collaboration
*/ */
#include "MuonSegment/MuonSegment.h" #include "MuonSegment/MuonSegment.h"
// TrkEvent // TrkEvent
#include "CxxUtils/sincos.h"
#include "EventPrimitives/EventPrimitivesToStringConverter.h"
#include "GeoPrimitives/GeoPrimitivesToStringConverter.h"
#include "TrkEventPrimitives/DefinedParameter.h"
#include "TrkEventPrimitives/FitQuality.h" #include "TrkEventPrimitives/FitQuality.h"
#include "TrkEventPrimitives/LocalParameters.h" #include "TrkEventPrimitives/LocalParameters.h"
#include "TrkEventPrimitives/DefinedParameter.h"
#include "TrkEventPrimitives/ParamDefs.h" #include "TrkEventPrimitives/ParamDefs.h"
#include "TrkRIO_OnTrack/RIO_OnTrack.h" #include "TrkRIO_OnTrack/RIO_OnTrack.h"
#include "CxxUtils/sincos.h"
#include "EventPrimitives/EventPrimitivesToStringConverter.h"
#include "GeoPrimitives/GeoPrimitivesToStringConverter.h"
#include <float.h> #include <cfloat>
#include <iostream> #include <iostream>
namespace Muon { namespace Muon {
const float MuonSegment::kNoValue = FLT_MAX; const float MuonSegment::kNoValue = FLT_MAX;
MuonSegment::MuonSegment() MuonSegment::MuonSegment()
: : Segment()
Segment(), , SpaceTimePointBase(kNoValue, kNoValue, 1.)
SpaceTimePointBase(kNoValue,kNoValue,1.), , Trk::SurfacePtrHolderImplDetEl<Trk::PlaneSurface>(nullptr)
m_globalPosition( ), , m_globalPosition()
m_globalDirection( ), , m_globalDirection()
m_localDirection( ), , m_localDirection()
m_associatedSurface( 0 )
{} {}
MuonSegment::MuonSegment(const MuonSegment& seg) MuonSegment::MuonSegment(const MuonSegment& seg)
: : Segment(seg)
Segment(seg), , SpaceTimePointBase(seg)
SpaceTimePointBase(seg), , Trk::SurfacePtrHolderImplDetEl<Trk::PlaneSurface>(nullptr)
m_globalPosition( seg.m_globalPosition ), , m_globalPosition(seg.m_globalPosition)
m_globalDirection( seg.m_globalDirection ), , m_globalDirection(seg.m_globalDirection)
m_localDirection ( seg.m_localDirection ), , m_localDirection(seg.m_localDirection)
m_associatedSurface( 0 )
{ {
m_associatedSurface = (seg.m_associatedSurface->associatedDetectorElement()) ? m_associatedSurface = (seg.m_associatedSurface->associatedDetectorElement())
seg.m_associatedSurface : seg.m_associatedSurface->clone(); ? seg.m_associatedSurface
: seg.m_associatedSurface->clone();
} }
MuonSegment& MuonSegment::operator=(const MuonSegment& seg) MuonSegment&
MuonSegment::operator=(const MuonSegment& seg)
{ {
if (this!=&seg){ if (this != &seg) {
Trk::Segment::operator=(seg); Trk::Segment::operator=(seg);
Trk::SpaceTimePointBase::operator=(seg); Trk::SpaceTimePointBase::operator=(seg);
m_globalPosition = seg.m_globalPosition; Trk::SurfacePtrHolderImplDetEl<Trk::PlaneSurface>::operator=(seg);
m_globalDirection = seg.m_globalDirection; m_globalPosition = seg.m_globalPosition;
m_localDirection = seg.m_localDirection; m_globalDirection = seg.m_globalDirection;
m_localDirection = seg.m_localDirection;
// delete & clone the surface only if there's no associated DetectorElement }
if (0!=m_associatedSurface && 0==m_associatedSurface->associatedDetectorElement()) delete m_associatedSurface; return (*this);
m_associatedSurface = (seg.m_associatedSurface->associatedDetectorElement()) ?
seg.m_associatedSurface : seg.m_associatedSurface->clone();
}
return (*this);
} }
MuonSegment::MuonSegment( const Trk::LocalParameters& locpars, MuonSegment::MuonSegment(const Trk::LocalParameters& locpars,
const Amg::MatrixX& locerr, const Amg::MatrixX& locerr,
Trk::PlaneSurface* psf, Trk::PlaneSurface* psf,
DataVector<const Trk::MeasurementBase>* cmeas, DataVector<const Trk::MeasurementBase>* cmeas,
Trk::FitQuality* fqual, Trk::FitQuality* fqual,
Segment::Author author) Segment::Author author)
: : Segment(locpars, locerr, cmeas, fqual, author)
Segment( locpars, locerr, cmeas, fqual,author ), , SpaceTimePointBase(kNoValue, kNoValue, 1.)
SpaceTimePointBase(kNoValue,kNoValue,1.), , Trk::SurfacePtrHolderImplDetEl<Trk::PlaneSurface>(psf)
m_globalPosition(), , m_globalPosition()
m_globalDirection(), , m_globalDirection()
m_localDirection(), , m_localDirection()
m_associatedSurface( psf )
{ {
recalculateCache(); recalculateCache();
psf->globalToLocalDirection(m_globalDirection,m_localDirection); psf->globalToLocalDirection(m_globalDirection, m_localDirection);
} }
MuonSegment::MuonSegment(const Amg::Vector2D& locSegPos,
MuonSegment::MuonSegment( const Amg::Vector2D& locSegPos, const Trk::LocalDirection& locSegDir,
const Trk::LocalDirection& locSegDir, const Amg::MatrixX& locErr,
const Amg::MatrixX& locErr, Trk::PlaneSurface* psf,
Trk::PlaneSurface* psf, DataVector<const Trk::MeasurementBase>* cmeas,
DataVector<const Trk::MeasurementBase>* cmeas, Trk::FitQuality* fqual,
Trk::FitQuality* fqual, Segment::Author author)
Segment::Author author) : Segment(Trk::LocalParameters(), locErr, cmeas, fqual, author)
: , SpaceTimePointBase(kNoValue, kNoValue, 1.)
Segment( Trk::LocalParameters(), locErr, cmeas, fqual,author ), , Trk::SurfacePtrHolderImplDetEl<Trk::PlaneSurface>(psf)
SpaceTimePointBase(kNoValue,kNoValue,1.), , m_globalPosition()
m_globalPosition( ), , m_globalDirection()
m_globalDirection(), , m_localDirection(locSegDir)
m_localDirection(locSegDir),
m_associatedSurface( psf )
{ {
psf->localToGlobalDirection(locSegDir,m_globalDirection); psf->localToGlobalDirection(locSegDir, m_globalDirection);
Amg::Vector2D lpos(locSegPos[Trk::locX], locSegPos[Trk::locY]); Amg::Vector2D lpos(locSegPos[Trk::locX], locSegPos[Trk::locY]);
m_associatedSurface->localToGlobal(lpos, m_globalDirection, m_globalPosition); m_associatedSurface->localToGlobal(lpos, m_globalDirection, m_globalPosition);
double phi = m_globalDirection.phi(); double phi = m_globalDirection.phi();
double theta = m_globalDirection.theta(); double theta = m_globalDirection.theta();
std::vector<Trk::DefinedParameter > pars; std::vector<Trk::DefinedParameter> pars;
pars.push_back( Trk::DefinedParameter( locSegPos[Trk::locX], Trk::locX) ); pars.emplace_back(locSegPos[Trk::locX], Trk::locX);
pars.push_back( Trk::DefinedParameter( locSegPos[Trk::locY], Trk::locY) ); pars.emplace_back(locSegPos[Trk::locY], Trk::locY);
pars.push_back( Trk::DefinedParameter( phi, Trk::phi) ); pars.emplace_back(phi, Trk::phi);
|
__label__pos
| 0.584155 |
基于JAVA的文件分割和文件合并-大文件的读取
本次讲解的是基于JAVA的文件分割和文件合并。文件分割和文件合并可以应用于大文件的读取操作。
文件分割主要涉及的知识:文件输入输出流、随机文件的读写之类的。其它的就是循环,很简单的,有兴趣的就看看。
只有两个文件:Separator.java(文件分割)、Combination.java(文件合并)。
Separator.java(文件分割):
import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
/**
* 文件分隔器:给定文件的路径和每一块要拆分的大小,就可以按要求拆分文件
* 如果指定的块给原文件都还要大,为了不动原文件,就生成另一个文件,以.bak为后缀,这样可以保证原文件
* 如果是程序自动拆分为多个文件,那么后缀分别为”.part序号”,这样就可以方便文件的合并了
* 原理:很简单,就是利用是输入输出流,加上随机文件读取。
*/
public class Separator
{
String FileName=null;//原文件名
long FileSize=0;//原文件的大小
long BlockNum=0;//可分的块数
public Separator()
{
}
/**
*
* @param fileAndPath 原文件名及路径
*/
private void getFileAttribute(String fileAndPath)//取得原文件的属性
{
File file=new File(fileAndPath);
FileName=file.getName();
FileSize=file.length();
}
/**
*
* @param blockSize 每一块的大小
* @return 能够分得的块数
*/
private long getBlockNum(long blockSize)//取得分块数
{
long fileSize=FileSize;
if(fileSize<=blockSize)//如果分块的小小只够分一个块
return 1;
else
{
if(fileSize%blockSize>0)
{
return fileSize/blockSize+1;
}
else
return fileSize/blockSize;
}
}
/**
*
* @param fileAndPath 原文件及完整路径
* @param currentBlock 当前块的序号
* @return 现在拆分后块的文件名
*/
private String generateSeparatorFileName(String fileAndPath,int currentBlock)//生成折分后的文件名,以便于将来合将
{
return fileAndPath+”.part”+currentBlock;
}
/**
*
* @param fileAndPath 原文件及完整路径
* @param fileSeparateName 文件分隔后要生成的文件名,与原文件在同一个目录下
* @param blockSize 当前块要写的字节数
* @param beginPos 从原文件的什么地方开始读取
* @return true为写入成功,false为写入失败
*/
private boolean writeFile(String fileAndPath,String fileSeparateName,long blockSize,long beginPos)//往硬盘写文件
{
RandomAccessFile raf=null;
FileOutputStream fos=null;
byte[] bt=new byte[1024];
long writeByte=0;
int len=0;
try
{
raf = new RandomAccessFile(fileAndPath,”r”);
raf.seek(beginPos);
fos = new FileOutputStream(fileSeparateName);
while((len=raf.read(bt))>0)
{
if(writeByte<blockSize)//如果当前块还没有写满
{
writeByte=writeByte+len;
if(writeByte<=blockSize)
fos.write(bt,0,len);
else
{
len=len-(int)(writeByte-blockSize);
fos.write(bt,0,len);
}
}
}
fos.close();
raf.close();
}
catch (Exception e)
{
e.printStackTrace();
try
{
if(fos!=null)
fos.close();
if(raf!=null)
raf.close();
}
catch(Exception f)
{
f.printStackTrace();
}
return false;
}
return true;
}
/**
*
* @param fileAndPath 原文路径及文件名
* @param blockSize 要拆分的每一块的大小
* @return true为拆分成功,false为拆分失败
*/
private boolean separatorFile(String fileAndPath,long blockSize)//折分文件主函数
{
getFileAttribute(fileAndPath);//将文件的名及大小属性取出来
//System.out.println(“FileSize:”+FileSize);
//System.out.println(“blockSize:”+blockSize);
BlockNum=getBlockNum(blockSize);//取得分块总数
//System.out.println(“BlockNum:”+BlockNum);
//System.exit(0);
if(BlockNum==1)//如果只能够分一块,就一次性写入
blockSize=FileSize;
long writeSize=0;//每次写入的字节
long writeTotal=0;//已经写了的字节
String FileCurrentNameAndPath=null;
for(int i=1;i<=BlockNum;i++)
{
if(i<BlockNum)
writeSize=blockSize;//取得每一次要写入的文件大小
else
writeSize=FileSize-writeTotal;
if(BlockNum==1)
FileCurrentNameAndPath=fileAndPath+”.bak”;
else
FileCurrentNameAndPath=generateSeparatorFileName(fileAndPath,i);
//System.out.print(“本次写入:”+writeSize);
if(!writeFile(fileAndPath,FileCurrentNameAndPath,writeSize,writeTotal))//循环往硬盘写文件
return false;
writeTotal=writeTotal+writeSize;
//System.out.println(” 总共写入:”+writeTotal);
}
return true;
}
public static void main(String[] args)
{
Separator separator = new Separator();
String fileAndPath=”d:\\test.rar”;//文件名及路径
long blockSize=200*1024;//每一个文件块的大小,大小是按字节计算
if(separator.separatorFile(fileAndPath,blockSize))
{
System.out.println(“文件折分成功!”);
}
else
{
System.out.println(“文件折分失败!”);
}
}
}
Combination.java(文件合并):
/**
* 合并文件:合并由拆分文件拆分的文件
* 要求将拆分文件放到一个文件夹中
* 主要利用随机文件读取和文件输入输出流
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Combination
{
String srcDirectory=null;//拆分文件存放的目录
String[] separatedFiles;//存放所有拆分文件名
String[][] separatedFilesAndSize;//存放所有拆分文件名及分件大小
int FileNum=0;//确定文件个数
String fileRealName=””;//据拆分文件名确定现在原文件名
public Combination()
{
srcDirectory=”d:\\test\\”;
}
/**
*
* @param sFileName 任一一个拆分文件名
* @return 原文件名
*/
private String getRealName(String sFileName)
{
StringTokenizer st=new StringTokenizer(sFileName,”.”);
return st.nextToken()+”.”+st.nextToken();
}
/**
* 取得指定拆分文件模块的文件大小
* @param FileName 拆分的文件名
* @return
*/
private long getFileSize(String FileName)
{
FileName=srcDirectory+FileName;
return (new File(FileName).length());
}
/**
* 生成一些属性,做初使化
* @param drictory 拆分文件目录
*/
private void getFileAttribute(String drictory)
{
File file=new File(drictory);
separatedFiles=new String[file.list().length];//依文件数目动态生成一维数组,只有文件名
separatedFiles=file.list();
//依文件数目动态生成二维数组,包括文件名和文件大小
//第一维装文件名,第二维为该文件的字节大小
separatedFilesAndSize=new String[separatedFiles.length][2];
Arrays.sort(separatedFiles);//排序
FileNum=separatedFiles.length;//当前文件夹下面有多少个文件
for(int i=0;i<FileNum;i++)
{
separatedFilesAndSize[i][0]=separatedFiles[i];//文件名
separatedFilesAndSize[i][1]=String.valueOf(getFileSize(separatedFiles[i]));//文件大上
}
fileRealName=getRealName(separatedFiles[FileNum-1]);//取得文件分隔前的原文件名
}
/**
* 合并文件:利用随机文件读写
* @return true为成功合并文件
*/
private boolean CombFile()
{
RandomAccessFile raf=null;
long alreadyWrite=0;
FileInputStream fis=null;
int len=0;
byte[] bt=new byte[1024];
try
{
raf = new RandomAccessFile(srcDirectory+fileRealName,”rw”);
for(int i=0;i<FileNum;i++)
{
raf.seek(alreadyWrite);
fis=new FileInputStream(srcDirectory+separatedFilesAndSize[i][0]);
while((len=fis.read(bt))>0)
{
raf.write(bt,0,len);
}
fis.close();
alreadyWrite=alreadyWrite+Long.parseLong(separatedFilesAndSize[i][1]);
}
raf.close();
}
catch (Exception e)
{
e.printStackTrace();
try
{
if(raf!=null)
raf.close();
if(fis!=null)
fis.close();
}
catch (IOException f)
{
f.printStackTrace();
}
return false;
}
return true;
}
public static void main(String[] args)
{
Combination combination = new Combination();
combination.getFileAttribute(combination.srcDirectory);
combination.CombFile();
System.exit(0);
}
}
转自:http://hi.baidu.com/k_boy/item/d706f7094adcfc91a2df4389
此条目发表在JAVA SE分类目录,贴了, , , 标签。将固定链接加入收藏夹。
|
__label__pos
| 0.998379 |
This is machine translation
Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.
Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.
gradient
Numerical gradient
Syntax
FX = gradient(F)
[FX,FY] = gradient(F)
[FX,FY,FZ,...,FN] = gradient(F)
[___] = gradient(F,h)
[___] = gradient(F,hx,hy,...,hN)
Description
example
FX = gradient(F) returns the one-dimensional numerical gradient of vector F. The output FX corresponds to ∂F/∂x, which are the differences in the x (horizontal) direction. The spacing between points is assumed to be 1.
example
[FX,FY] = gradient(F) returns the x and y components of the two-dimensional numerical gradient of matrix F. The additional output FY corresponds to ∂F/∂y, which are the differences in the y (vertical) direction. The spacing between points in each direction is assumed to be 1.
[FX,FY,FZ,...,FN] = gradient(F) returns the N components of the numerical gradient of F, where F is an array with N dimensions.
example
[___] = gradient(F,h) uses h as a uniform spacing between points in each direction. You can specify any of the output arguments in previous syntaxes.
example
[___] = gradient(F,hx,hy,...,hN) specifies N spacing parameters for the spacing in each dimension of F.
Examples
collapse all
Calculate the gradient of a monotonically increasing vector.
x = 1:10
x = 1×10
1 2 3 4 5 6 7 8 9 10
fx = gradient(x)
fx = 1×10
1 1 1 1 1 1 1 1 1 1
Calculate the 2-D gradient of on a grid.
x = -2:0.2:2;
y = x';
z = x .* exp(-x.^2 - y.^2);
[px,py] = gradient(z);
Plot the contour lines and vectors in the same figure.
figure
contour(x,y,z)
hold on
quiver(x,y,px,py)
hold off
Use the gradient at a particular point to linearly approximate the function value at a nearby point and compare it to the actual value.
The equation for linear approximation of a function value is
That is, if you know the value of a function and the slope of the derivative at a particular point , then you can use this information to approximate the value of the function at a nearby point .
Calculate some values of the sine function between -1 and 0.5. Then calculate the gradient.
y = sin(-1:0.25:0.5);
yp = gradient(y,0.25);
Use the function value and derivative at x = 0.5 to predict the value of sin(0.5005).
y_guess = y(end) + yp(end)*(0.5005 - 0.5)
y_guess = 0.4799
Compute the actual value for comparison.
y_actual = sin(0.5005)
y_actual = 0.4799
Find the value of the gradient of a multivariate function at a specified point.
Consider the multivariate function .
x = -3:0.2:3;
y = x';
f = x.^2 .* y.^3;
surf(x,y,f)
xlabel('x')
ylabel('y')
zlabel('z')
Calculate the gradient on the grid.
[fx,fy] = gradient(f,0.2);
Extract the value of the gradient at the point (1,-2). To do this, first obtain the indices of the point you want to work with. Then, use the indices to extract the corresponding gradient values from fx and fy.
x0 = 1;
y0 = -2;
t = (x == x0) & (y == y0);
indt = find(t);
f_grad = [fx(indt) fy(indt)]
f_grad = 1×2
-16.0000 12.0400
The exact value of the gradient of at the point (1,-2) is
Input Arguments
collapse all
Input array, specified as a vector, matrix, or multidimensional array.
Data Types: single | double
Complex Number Support: Yes
Uniform spacing between points in all directions, specified as a scalar.
Example: [FX,FY] = gradient(F,2)
Data Types: single | double
Complex Number Support: Yes
Spacing between points in each direction, specified as separate inputs of scalars or vectors. The number of inputs must match the number of array dimensions of F. Each input can be a scalar or vector:
• A scalar specifies a constant spacing in that dimension.
• A vector specifies the coordinates of the values along the corresponding dimension of F. In this case, the length of the vector must match the size of the corresponding dimension.
Example: [FX,FY] = gradient(F,0.1,2)
Example: [FX,FY] = gradient(F,[0.1 0.3 0.5],2)
Example: [FX,FY] = gradient(F,[0.1 0.3 0.5],[2 3 5])
Data Types: single | double
Complex Number Support: Yes
Output Arguments
collapse all
Numerical gradients, returned as arrays of the same size as F. The first output FX is always the gradient along the 2nd dimension of F, going across columns. The second output FY is always the gradient along the 1st dimension of F, going across rows. For the third output FZ and the outputs that follow, the Nth output is the gradient along the Nth dimension of F.
More About
collapse all
Numerical Gradient
The numerical gradient of a function is a way to estimate the values of the partial derivatives in each dimension using the known values of the function at certain points.
For a function of two variables, F(x,y), the gradient is
F=Fxi^+Fyj^.
The gradient can be thought of as a collection of vectors pointing in the direction of increasing values of F. In MATLAB®, you can compute numerical gradients for functions with any number of variables. For a function of N variables, F(x,y,z, ...), the gradient is
F=Fxi^+Fyj^+Fzk^+...+FNn^.
Algorithms
gradient calculates the central difference for interior data points. For example, consider a matrix with unit-spaced data, A, that has horizontal gradient G = gradient(A). The interior gradient values, G(:,j), are
G(:,j) = 0.5*(A(:,j+1) - A(:,j-1));
The subscript j varies between 2 and N-1, with N = size(A,2).
gradient calculates values along the edges of the matrix with single-sided differences:
G(:,1) = A(:,2) - A(:,1);
G(:,N) = A(:,N) - A(:,N-1);
If you specify the point spacing, then gradient scales the differences appropriately. If you specify two or more outputs, then the function also calculates differences along other dimensions in a similar manner. Unlike the diff function, gradient returns an array with the same number of elements as the input.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Introduced before R2006a
|
__label__pos
| 0.956793 |
How to Block Internet Access to an App in Windows 10: A Step-by-Step Guide
How to Block Internet Access to an App in Windows 10
Blocking internet access to a specific app in Windows 10 can be handy if you want to control data usage or ensure security. This guide will show you how to use Windows Firewall to block an app’s internet access. Follow the steps below, and in just a few minutes, your chosen app will no longer be able to connect to the internet.
Step-by-Step Guide to Block Internet Access to an App in Windows 10
In this guide, we will walk you through the process of blocking an app’s access to the internet using Windows Firewall. This will ensure that the app cannot send or receive data online.
Step 1: Open Control Panel
First, open the Control Panel on your computer.
To do this, click on the Start menu and type "Control Panel." Select it from the search results.
Step 2: Go to Windows Defender Firewall
Next, navigate to Windows Defender Firewall.
In the Control Panel, find and click on "System and Security," then select "Windows Defender Firewall."
Step 3: Advanced Settings
Access the advanced settings of Windows Defender Firewall.
Locate and click on "Advanced settings" on the left-hand side. This will open the Windows Defender Firewall with Advanced Security window.
Step 4: Create a New Outbound Rule
Now, create a new rule to block the app’s internet access.
In the left pane, click on "Outbound Rules." Then, in the right pane, click on "New Rule."
Step 5: Select Program
Choose the type of rule you want to create.
Select "Program" and then click "Next" to specify which program you want to block.
Step 6: Locate the Program
Find and select the app you want to block.
Click on "This program path" and then "Browse" to locate the executable (.exe) file of the app. Once selected, click "Next."
Step 7: Block the Connection
Specify what action to take when the program tries to connect to the internet.
Select "Block the connection" and click "Next."
Step 8: Apply Rule to All Profiles
Decide where the rule will apply.
Make sure all three options (Domain, Private, Public) are checked, then click "Next."
Step 9: Name the Rule
Give your new rule a name.
Enter a name (like "Block Internet Access for [App Name]") and click "Finish."
After completing these steps, the app will no longer be able to access the internet.
Tips for Blocking Internet Access to an App in Windows 10
• Always double-check which app you’re blocking.
• You can always disable or delete the rule if needed.
• Use descriptive names for your rules to keep track.
• Apply rules to all profiles (Domain, Private, Public) for comprehensive blocking.
• Regularly review and update your firewall rules for optimal security.
Frequently Asked Questions
Can I unblock an app later?
Yes, you can easily unblock an app by deleting or disabling the rule in Windows Defender Firewall.
Does blocking an app affect its performance?
Blocking internet access won’t affect the app’s performance unless it requires internet access to function properly.
Can I block multiple apps at once?
You need to create separate rules for each app you want to block.
Is it safe to block internet access to system apps?
Be cautious when blocking system apps, as it may affect your computer’s functionality.
Will this method work on other versions of Windows?
This guide specifically applies to Windows 10, but similar steps can be followed in other versions of Windows.
Summary
1. Open Control Panel.
2. Go to Windows Defender Firewall.
3. Advanced Settings.
4. Create a New Outbound Rule.
5. Select Program.
6. Locate the Program.
7. Block the Connection.
8. Apply Rule to All Profiles.
9. Name the Rule.
Conclusion
Now that you know how to block internet access to an app in Windows 10, you can take control of your apps and their online activities. This can help you manage data usage, enhance security, and maintain privacy. If you ever need to reverse the process, simply disable or delete the rule you created.
Blocking apps from accessing the internet can be particularly useful for maintaining focus, protecting sensitive information, and ensuring that your bandwidth is used wisely. Make sure to double-check any changes you make and monitor your firewall rules regularly.
For further reading, consider looking into other features provided by Windows Defender Firewall. You might discover more ways to customize and secure your internet usage. Happy configuring!
Get Our Free Newsletter
How-to guides and tech deals
You may opt out at any time.
Read our Privacy Policy
|
__label__pos
| 0.911626 |
AudioListener
AudioListener 接口代表了人听音乐场景时声音的位置和方向, 和用于音频空间化。 所有PannerNode 相对于 AudioListener 的空间化储存在BaseAudioContext.listener 属性里.
特别需要注意的是一个环境中只能有一个收听者而且这不是AudioNode.
We see the position, up and front vectors of an AudioListener, with the up and front vectors at 90° from the other.
Properties
position,forward和up值是以不同的语法设置和检索的。检索是通过访问来实现的,比如说 AudioListener.positionX ,设置相同属性时可以通过使用 AudioListener.positionX.value 来完成。 这就是为什么他们不被标记为只读, 这在规范的接口定义中就是这么说的.
AudioListener.positionX
在笛卡尔右手坐标系中代表一个收听者的水平坐标。默认值是 0.
AudioListener.positionY
Represents the vertical position of the listener in a right-hand cartesian coordinate sytem. The default is 0.
AudioListener.positionZ
Represents the longitudinal (back and forth) position of the listener in a right-hand cartesian coordinate sytem. The default is 0.
AudioListener.forwardX
在相同的笛卡尔坐标系中代表了收听者的面向的方向的水平坐标,就像 (positionX, positionY, 和 positionZ) 值一样。前方和上方值互相线性无关。默认值是 0.
AudioListener.forwardY
Represents the vertical position of the listener's forward direction in the same cartesian coordinate sytem as the position (positionX, positionY, and positionZ) values. The forward and up values are linearly independent of each other. The default is 0.
AudioListener.forwardZ
Represents the longitudinal (back and forth) position of the listener's forward direction in the same cartesian coordinate sytem as the position (positionX, positionY, and positionZ) values. The forward and up values are linearly independent of each other. The default is -1.
AudioListener.upX
代表了收听者头顶在笛卡尔坐标系的水平位置,就像 (positionX, positionY, 和positionZ) 值一样。 前方和上方值线性无关。默认值是 0.
AudioListener.upY
Represents the vertical position of the top of the listener's head in the same cartesian coordinate sytem as the position (positionX, positionY, and positionZ) values. The forward and up values are linearly independent of each other. The default is 1.
AudioListener.upZ
Represents the longitudinal (back and forth) position of the top of the listener's head in the same cartesian coordinate sytem as the position (positionX, positionY, and positionZ) values. The forward and up values are linearly independent of each other. The default is 0.
Methods
AudioListener.setOrientation() This deprecated API should no longer be used, but will probably still work.
设置收听者的方向。
AudioListener.setPosition() This deprecated API should no longer be used, but will probably still work.
设置收听者的位置。
Note: Although these methods are deprecated they are currently the only way to set the orientation and position in Firefox, Internet Explorer and Safari.
Deprecated features
AudioListener.dopplerFactor This is an obsolete API and is no longer guaranteed to work.
一个Double值,表示在呈现 多普勒效应 时要使用的音高偏移量。
AudioListener.speedOfSound This is an obsolete API and is no longer guaranteed to work.
一个Double值代表了声音的速度,以米每秒的单位计算。
In a previous version of the specification, the dopplerFactor and speedOfSound properties and the setPosition() method could be used to control the doppler effect applied to AudioBufferSourceNodes connected downstream — these would be pitched up and down according to the relative speed of the PannerNode and the AudioListener. These features had a number of problems:
• Only AudioBufferSourceNodes were pitched up or down, not other source nodes.
• The behavior to adopt when an AudioBufferSourceNode was connected to multiple PannerNodes was unclear.
• Because the velocity of the panner and the listener were not AudioParams, the pitch modification could not be smoothly applied, resulting in audio glitches.
Because of these issues, these properties and methods have been removed.
The setOrientation() and setPosition() methods have been replaced by setting their property value equivilents. For example setPosition(x, y, z) can be achieved by setting positionX.value, positionY.value, and positionZ.value respectively.
Example
In the following example, you can see an example of how the createPanner() method, AudioListener and PannerNode would be used to control audio spatialisation. Generally you will define the position in 3D space that your audio listener and panner (source) occupy initially, and then update the position of one or both of these as the application is used. You might be moving a character around inside a game world for example, and wanting delivery of audio to change realistically as your character moves closer to or further away from a music player such as a stereo. In the example you can see this being controlled by the functions moveRight(), moveLeft(), etc., which set new values for the panner position via the PositionPanner() function.
To see a complete implementation, check out our panner-node example (view the source code) — this demo transports you to the 2.5D "Room of metal", where you can play a track on a boom box and then walk around the boom box to see how the sound changes!
Note how we have used some feature detection to either give the browser the newer property values (like AudioListener.forwardX) for setting position, etc. if it supports those, or older methods (like AudioListener.setOrientation()) if it still supports those but not the new properties.
// set up listener and panner position information
var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
var xPos = Math.floor(WIDTH/2);
var yPos = Math.floor(HEIGHT/2);
var zPos = 295;
// define other variables
var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioCtx = new AudioContext();
var panner = audioCtx.createPanner();
panner.panningModel = 'HRTF';
panner.distanceModel = 'inverse';
panner.refDistance = 1;
panner.maxDistance = 10000;
panner.rolloffFactor = 1;
panner.coneInnerAngle = 360;
panner.coneOuterAngle = 0;
panner.coneOuterGain = 0;
if(panner.orientationX) {
panner.orientationX.setValueAtTime(1, audioCtx.currentTime);
panner.orientationY.setValueAtTime(0, audioCtx.currentTime);
panner.orientationZ.setValueAtTime(0, audioCtx.currentTime);
} else {
panner.setOrientation(1,0,0);
}
var listener = audioCtx.listener;
if(listener.forwardX) {
listener.forwardX.setValueAtTime(0, audioCtx.currentTime);
listener.forwardY.setValueAtTime(0, audioCtx.currentTime);
listener.forwardZ.setValueAtTime(-1, audioCtx.currentTime);
listener.upX.setValueAtTime(0, audioCtx.currentTime);
listener.upY.setValueAtTime(1, audioCtx.currentTime);
listener.upZ.setValueAtTime(0, audioCtx.currentTime);
} else {
listener.setOrientation(0,0,-1,0,1,0);
}
var source;
var play = document.querySelector('.play');
var stop = document.querySelector('.stop');
var boomBox = document.querySelector('.boom-box');
var listenerData = document.querySelector('.listener-data');
var pannerData = document.querySelector('.panner-data');
leftBound = (-xPos) + 50;
rightBound = xPos - 50;
xIterator = WIDTH/150;
// listener will always be in the same place for this demo
if(listener.positionX) {
listener.positionX.setValueAtTime(xPos, audioCtx.currentTime);
listener.positionY.setValueAtTime(yPos, audioCtx.currentTime);
listener.positionZ.setValueAtTime(300, audioCtx.currentTime);
} else {
listener.setPosition(xPos,yPos,300);
}
listenerData.textContent = `Listener data: X ${xPos} Y ${yPos} Z 300`;
// panner will move as the boombox graphic moves around on the screen
function positionPanner() {
if(panner.positionX) {
panner.positionX.setValueAtTime(xPos, audioCtx.currentTime);
panner.positionY.setValueAtTime(yPos, audioCtx.currentTime);
panner.positionZ.setValueAtTime(zPos, audioCtx.currentTime);
} else {
panner.setPosition(xPos,yPos,zPos);
}
pannerData.textContent = `Panner data: X ${xPos} Y ${yPos} Z ${zPos}`;
}
Note: In terms of working out what position values to apply to the listener and panner, to make the sound appropriate to what the visuals are doing on screen, there is quite a bit of math involved, but you will soon get used to it with a bit of experimentation.
Specifications
Specification Status Comment
Web Audio API
AudioListener
Working Draft
Browser compatibility
BCD tables only load in the browser
See also
|
__label__pos
| 0.775176 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
//! Streaming iterators.
//!
//! The iterator APIs in the Rust standard library do not allow elements to be yielded which borrow
//! from the iterator itself. That means, for example, that the `std::io::Lines` iterator must
//! allocate a new `String` for each line rather than reusing an internal buffer. The
//!`StreamingIterator` trait instead provides access to elements being iterated over only by
//! reference rather than by value.
//!
//! `StreamingIterator`s cannot be used in Rust `for` loops, but `while let` loops offer a similar
//! level of ergonomics:
//!
//! ```ignore
//! while let Some(item) = iter.next() {
//! // work with item
//! }
//! ```
//!
//! While the standard `Iterator` trait's functionality is based off of the `next` method,
//! `StreamingIterator`'s functionality is based off of a pair of methods: `advance` and `get`. This
//! essentially splits the logic of `next` in half (in fact, `StreamingIterator`'s `next` method
//! does nothing but call `advance` followed by `get`).
//!
//! This is required because of Rust's lexical handling of borrows (more specifically a lack of
//! single entry, multiple exit borrows). If `StreamingIterator` was defined like `Iterator` with
//! just a required `next` method, operations like `filter` would be impossible to define.
#![doc(html_root_url="https://docs.rs/streaming_iterator/0.1.1")]
#![warn(missing_docs)]
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
extern crate core;
use core::cmp;
/// An interface for dealing with streaming iterators.
pub trait StreamingIterator {
/// The type of the elements being iterated over.
type Item: ?Sized;
/// Advances the iterator to the next element.
///
/// Iterators start just before the first element, so this should be called before `get`.
///
/// The behavior of calling this method after the end of the iterator has been reached is
/// unspecified.
fn advance(&mut self);
/// Returns a reference to the current element of the iterator.
///
/// The behavior of calling this method before `advance` has been called is unspecified.
fn get(&self) -> Option<&Self::Item>;
/// Advances the iterator and returns the next value.
///
/// The behavior of calling this method after the end of the iterator has been reached is
/// unspecified.
///
/// The default implementation simply calls `advance` followed by `get`.
#[inline]
fn next(&mut self) -> Option<&Self::Item> {
self.advance();
(*self).get()
}
/// Returns the bounds on the remaining length of the iterator.
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, None)
}
/// Determines if all elements of the iterator satisfy a predicate.
#[inline]
fn all<F>(&mut self, mut f: F) -> bool
where F: FnMut(&Self::Item) -> bool
{
while let Some(i) = self.next() {
if !f(i) {
return false;
}
}
true
}
/// Determines if any elements of the iterator satisfy a predicate.
#[inline]
fn any<F>(&mut self, mut f: F) -> bool
where F: FnMut(&Self::Item) -> bool
{
!self.all(|i| !f(i))
}
/// Borrows an iterator, rather than consuming it.
///
/// This is useful to allow the application of iterator adaptors while still retaining ownership
/// of the original adaptor.
#[inline]
fn by_ref(&mut self) -> &mut Self {
self
}
/// Produces a normal, non-streaming, iterator by cloning the elements of this iterator.
#[inline]
fn cloned(self) -> Cloned<Self>
where Self: Sized,
Self::Item: Clone
{
Cloned(self)
}
/// Consumes the iterator, counting the number of remaining elements and returning it.
#[inline]
fn count(mut self) -> usize
where Self: Sized
{
let mut count = 0;
while let Some(_) = self.next() {
count += 1;
}
count
}
/// Creates an iterator which uses a closure to determine if an element should be yielded.
#[inline]
fn filter<F>(self, f: F) -> Filter<Self, F>
where Self: Sized,
F: FnMut(&Self::Item) -> bool
{
Filter {
it: self,
f: f,
}
}
/// Creates an iterator which both filters and maps by applying a closure to elements.
#[inline]
fn filter_map<B, F>(self, f: F) -> FilterMap<Self, B, F>
where Self: Sized,
F: FnMut(&Self::Item) -> Option<B>
{
FilterMap {
it: self,
f: f,
item: None,
}
}
/// Returns the first element of the iterator that satisfies the predicate.
#[inline]
fn find<F>(&mut self, mut f: F) -> Option<&Self::Item>
where F: FnMut(&Self::Item) -> bool
{
loop {
self.advance();
match self.get() {
Some(i) => {
if f(i) {
break;
}
}
None => break,
}
}
(*self).get()
}
/// Creates an iterator which is "well behaved" at the beginning and end of iteration
///
/// The behavior of calling `get` before iteration has been started, and of continuing to call
/// `advance` after `get` has returned `None` is normally unspecified, but this guarantees that
/// `get` will return `None` in both cases.
#[inline]
fn fuse(self) -> Fuse<Self>
where Self: Sized
{
Fuse {
it: self,
state: FuseState::Start,
}
}
/// Creates an iterator which transforms elements of this iterator by passing them to a closure.
#[inline]
fn map<B, F>(self, f: F) -> Map<Self, B, F>
where Self: Sized,
F: FnMut(&Self::Item) -> B
{
Map {
it: self,
f: f,
item: None,
}
}
/// Creates an iterator which transforms elements of this iterator by passing them to a closure.
///
/// Unlike `map`, this method takes a closure that returns a reference into the original value.
#[inline]
fn map_ref<B: ?Sized, F>(self, f: F) -> MapRef<Self, F>
where Self: Sized,
F: Fn(&Self::Item) -> &B
{
MapRef {
it: self,
f: f,
}
}
/// Consumes the first `n` elements of the iterator, returning the next one.
#[inline]
fn nth(&mut self, n: usize) -> Option<&Self::Item> {
for _ in 0..n {
self.advance();
if self.get().is_none() {
return None;
}
}
self.next()
}
/// Creates a normal, non-streaming, iterator with elements produced by calling `to_owned` on
/// the elements of this iterator.
///
/// Requires the `std` feature.
#[cfg(feature = "std")]
#[inline]
fn owned(self) -> Owned<Self>
where Self: Sized,
Self::Item: ToOwned
{
Owned(self)
}
/// Returns the index of the first element of the iterator matching a predicate.
#[inline]
fn position<F>(&mut self, mut f: F) -> Option<usize>
where F: FnMut(&Self::Item) -> bool
{
let mut n = 0;
while let Some(i) = self.next() {
if f(i) {
return Some(n);
}
n += 1;
}
None
}
/// Creates an iterator which skips the first `n` elements.
#[inline]
fn skip(self, n: usize) -> Skip<Self>
where Self: Sized
{
Skip {
it: self,
n: n,
}
}
/// Creates an iterator that skips initial elements matching a predicate.
#[inline]
fn skip_while<F>(self, f: F) -> SkipWhile<Self, F>
where Self: Sized,
F: FnMut(&Self::Item) -> bool
{
SkipWhile {
it: self,
f: f,
done: false,
}
}
/// Creates an iterator which only returns the first `n` elements.
#[inline]
fn take(self, n: usize) -> Take<Self>
where Self: Sized
{
Take {
it: self,
n: n,
done: false,
}
}
/// Creates an iterator which only returns initial elements matching a predicate.
#[inline]
fn take_while<F>(self, f: F) -> TakeWhile<Self, F>
where Self: Sized,
F: FnMut(&Self::Item) -> bool
{
TakeWhile {
it: self,
f: f,
done: false,
}
}
}
impl<'a, I: ?Sized> StreamingIterator for &'a mut I
where I: StreamingIterator
{
type Item = I::Item;
#[inline]
fn advance(&mut self) {
(**self).advance()
}
#[inline]
fn get(&self) -> Option<&Self::Item> {
(**self).get()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(**self).size_hint()
}
#[inline]
fn next(&mut self) -> Option<&Self::Item> {
(**self).next()
}
}
/// Turns a normal, non-streaming iterator into a streaming iterator.
#[inline]
pub fn convert<I>(it: I) -> Convert<I>
where I: Iterator
{
Convert {
it: it,
item: None,
}
}
/// A normal, non-streaming, iterator which converts the elements of a streaming iterator into owned
/// values by cloning them.
#[derive(Clone)]
pub struct Cloned<I>(I);
impl<I> Iterator for Cloned<I>
where I: StreamingIterator,
I::Item: Clone
{
type Item = I::Item;
#[inline]
fn next(&mut self) -> Option<I::Item> {
self.0.next().map(Clone::clone)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// A streaming iterator which yields elements from a normal, non-streaming, iterator.
#[derive(Clone)]
pub struct Convert<I>
where I: Iterator
{
it: I,
item: Option<I::Item>,
}
impl<I> StreamingIterator for Convert<I>
where I: Iterator
{
type Item = I::Item;
#[inline]
fn advance(&mut self) {
self.item = self.it.next();
}
#[inline]
fn get(&self) -> Option<&I::Item> {
self.item.as_ref()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
#[inline]
fn count(self) -> usize {
self.it.count()
}
}
/// A streaming iterator which filters the elements of a streaming iterator with a predicate.
pub struct Filter<I, F> {
it: I,
f: F,
}
impl<I, F> StreamingIterator for Filter<I, F>
where I: StreamingIterator,
F: FnMut(&I::Item) -> bool
{
type Item = I::Item;
#[inline]
fn advance(&mut self) {
while let Some(i) = self.it.next() {
if (self.f)(i) {
break;
}
}
}
#[inline]
fn get(&self) -> Option<&I::Item> {
self.it.get()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, self.it.size_hint().1)
}
}
/// An iterator which both filters and maps elements of a streaming iterator with a closure.
pub struct FilterMap<I, B, F> {
it: I,
f: F,
item: Option<B>,
}
impl<I, B, F> StreamingIterator for FilterMap<I, B, F>
where I: StreamingIterator,
F: FnMut(&I::Item) -> Option<B>
{
type Item = B;
#[inline]
fn advance(&mut self) {
loop {
match self.it.next() {
Some(i) => {
if let Some(i) = (self.f)(i) {
self.item = Some(i);
break;
}
}
None => {
self.item = None;
break;
}
}
}
}
#[inline]
fn get(&self) -> Option<&B> {
self.item.as_ref()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
(0, self.it.size_hint().1)
}
}
#[derive(Copy, Clone)]
enum FuseState {
Start,
Middle,
End,
}
/// A streaming iterator which is well-defined before and after iteration.
#[derive(Clone)]
pub struct Fuse<I> {
it: I,
state: FuseState,
}
impl<I> StreamingIterator for Fuse<I>
where I: StreamingIterator
{
type Item = I::Item;
#[inline]
fn advance(&mut self) {
match self.state {
FuseState::Start => {
self.it.advance();
self.state = match self.it.get() {
Some(_) => FuseState::Middle,
None => FuseState::End,
};
}
FuseState::Middle => {
self.it.advance();
if let None = self.it.get() {
self.state = FuseState::End;
}
}
FuseState::End => {}
}
}
#[inline]
fn get(&self) -> Option<&I::Item> {
match self.state {
FuseState::Start | FuseState::End => None,
FuseState::Middle => self.it.get(),
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
#[inline]
fn next(&mut self) -> Option<&I::Item> {
match self.state {
FuseState::Start => {
match self.it.next() {
Some(i) => {
self.state = FuseState::Middle;
Some(i)
}
None => {
self.state = FuseState::End;
None
}
}
}
FuseState::Middle => {
match self.it.next() {
Some(i) => Some(i),
None => {
self.state = FuseState::End;
None
}
}
}
FuseState::End => None,
}
}
#[inline]
fn count(self) -> usize {
match self.state {
FuseState::Start | FuseState::Middle => self.it.count(),
FuseState::End => 0,
}
}
}
/// A streaming iterator which transforms the elements of a streaming iterator.
pub struct Map<I, B, F> {
it: I,
f: F,
item: Option<B>,
}
impl<I, B, F> StreamingIterator for Map<I, B, F>
where I: StreamingIterator,
F: FnMut(&I::Item) -> B
{
type Item = B;
#[inline]
fn advance(&mut self) {
self.item = self.it.next().map(&mut self.f);
}
#[inline]
fn get(&self) -> Option<&B> {
self.item.as_ref()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
}
/// A streaming iterator which transforms the elements of a streaming iterator.
pub struct MapRef<I, F> {
it: I,
f: F,
}
impl<I, B: ?Sized, F> StreamingIterator for MapRef<I, F>
where I: StreamingIterator,
F: Fn(&I::Item) -> &B
{
type Item = B;
#[inline]
fn advance(&mut self) {
self.it.advance();
}
#[inline]
fn get(&self) -> Option<&B> {
self.it.get().map(&self.f)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.it.size_hint()
}
#[inline]
fn next(&mut self) -> Option<&B> {
self.it.next().map(&self.f)
}
}
/// A normal, non-streaming, iterator which converts the elements of a streaming iterator into owned
/// versions.
///
/// Requires the `std` feature.
#[cfg(feature = "std")]
#[derive(Clone)]
pub struct Owned<I>(I);
#[cfg(feature = "std")]
impl<I> Iterator for Owned<I>
where I: StreamingIterator,
I::Item: Sized + ToOwned
{
type Item = <I::Item as ToOwned>::Owned;
#[inline]
fn next(&mut self) -> Option<<I::Item as ToOwned>::Owned> {
self.0.next().map(ToOwned::to_owned)
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
self.0.size_hint()
}
}
/// A streaming iterator which skips a number of elements in a streaming iterator.
#[derive(Clone)]
pub struct Skip<I> {
it: I,
n: usize,
}
impl<I> StreamingIterator for Skip<I>
where I: StreamingIterator
{
type Item = I::Item;
#[inline]
fn advance(&mut self) {
self.it.nth(self.n);
self.n = 0;
}
#[inline]
fn get(&self) -> Option<&I::Item> {
self.it.get()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let hint = self.it.size_hint();
(hint.0.saturating_sub(self.n), hint.1.map(|n| n.saturating_sub(self.n)))
}
}
/// A streaming iterator which skips initial elements that match a predicate
#[derive(Clone)]
pub struct SkipWhile<I, F> {
it: I,
f: F,
done: bool,
}
impl<I, F> StreamingIterator for SkipWhile<I, F>
where I: StreamingIterator,
F: FnMut(&I::Item) -> bool
{
type Item = I::Item;
#[inline]
fn advance(&mut self) {
if !self.done {
let f = &mut self.f;
self.it.find(|i| !f(i));
self.done = true;
} else {
self.it.advance();
}
}
#[inline]
fn get(&self) -> Option<&I::Item> {
self.it.get()
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let hint = self.it.size_hint();
(0, hint.1)
}
}
/// A streaming iterator which only yields a limited number of elements in a streaming iterator.
#[derive(Clone)]
pub struct Take<I> {
it: I,
n: usize,
done: bool,
}
impl<I> StreamingIterator for Take<I>
where I: StreamingIterator
{
type Item = I::Item;
#[inline]
fn advance(&mut self) {
if self.n != 0 {
self.it.advance();
self.n -= 1;
} else {
self.done = true;
}
}
#[inline]
fn get(&self) -> Option<&I::Item> {
if self.done {
None
} else {
self.it.get()
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let hint = self.it.size_hint();
(cmp::min(hint.0, self.n), Some(self.n))
}
}
/// A streaming iterator which only returns initial elements matching a predicate.
pub struct TakeWhile<I, F> {
it: I,
f: F,
done: bool,
}
impl<I, F> StreamingIterator for TakeWhile<I, F>
where I: StreamingIterator,
F: FnMut(&I::Item) -> bool
{
type Item = I::Item;
#[inline]
fn advance(&mut self) {
if !self.done {
self.it.advance();
if let Some(i) = self.it.get() {
if !(self.f)(i) {
self.done = true;
}
}
}
}
#[inline]
fn get(&self) -> Option<&I::Item> {
if self.done {
None
} else {
self.it.get()
}
}
#[inline]
fn next(&mut self) -> Option<&I::Item> {
if self.done {
None
} else {
match self.it.next() {
Some(i) => {
if (self.f)(i) {
Some(i)
} else {
self.done = true;
None
}
}
None => None
}
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let upper = if self.done {
Some(0)
} else {
self.it.size_hint().1
};
(0, upper)
}
}
#[cfg(test)]
mod test {
use core::fmt::Debug;
use super::*;
fn test<I>(mut it: I, expected: &[I::Item])
where I: StreamingIterator,
I::Item: Sized + PartialEq + Debug,
{
for item in expected {
it.advance();
assert_eq!(it.get(), Some(item));
assert_eq!(it.get(), Some(item));
}
it.advance();
assert_eq!(it.get(), None);
assert_eq!(it.get(), None);
}
#[test]
fn all() {
let items = [0, 1, 2];
let it = convert(items.iter().cloned());
assert!(it.clone().all(|&i| i < 3));
assert!(!it.clone().all(|&i| i % 2 == 0));
}
#[test]
fn any() {
let items = [0, 1, 2];
let it = convert(items.iter().cloned());
assert!(it.clone().any(|&i| i > 1));
assert!(!it.clone().any(|&i| i > 2));
}
#[test]
fn cloned() {
let items = [0, 1];
let mut it = convert(items.iter().cloned()).cloned();
assert_eq!(it.next(), Some(0));
assert_eq!(it.next(), Some(1));
assert_eq!(it.next(), None);
}
#[test]
fn test_convert() {
let items = [0, 1];
let it = convert(items.iter().cloned());
test(it, &items);
}
#[test]
fn count() {
let items = [0, 1, 2, 3];
let it = convert(items.iter());
assert_eq!(it.count(), 4);
}
#[test]
fn filter() {
let items = [0, 1, 2, 3];
let it = convert(items.iter().cloned()).filter(|x| x % 2 == 0);
test(it, &[0, 2]);
}
#[test]
fn fuse() {
struct Flicker(i32);
impl StreamingIterator for Flicker {
type Item = i32;
fn advance(&mut self) {
self.0 += 1;
}
fn get(&self) -> Option<&i32> {
if self.0 % 4 == 3 {
None
} else {
Some(&self.0)
}
}
}
let mut it = Flicker(0).fuse();
assert_eq!(it.get(), None);
it.advance();
assert_eq!(it.get(), Some(&1));
assert_eq!(it.get(), Some(&1));
it.advance();
assert_eq!(it.get(), Some(&2));
assert_eq!(it.get(), Some(&2));
it.advance();
assert_eq!(it.get(), None);
assert_eq!(it.get(), None);
it.advance();
assert_eq!(it.get(), None);
assert_eq!(it.get(), None);
}
#[test]
fn map() {
let items = [0, 1];
let it = convert(items.iter().map(|&i| i as usize)).map(|&i| i as i32);
test(it, &items);
}
#[test]
fn map_ref() {
#[derive(Clone)]
struct Foo(i32);
let items = [Foo(0), Foo(1)];
let it = convert(items.iter().cloned()).map_ref(|f| &f.0);
test(it, &[0, 1]);
}
#[test]
fn nth() {
let items = [0, 1];
let it = convert(items.iter().cloned());
assert_eq!(it.clone().nth(0), Some(&0));
assert_eq!(it.clone().nth(1), Some(&1));
assert_eq!(it.clone().nth(2), None);
}
#[test]
fn filter_map() {
let items = [0u8, 1, 1, 2, 4];
let it = convert(items.iter())
.filter_map(|&&i| {
if i % 2 == 0 {
Some(i)
} else {
None
}
});
test(it, &[0, 2, 4])
}
#[test]
fn find() {
let items = [0, 1];
let it = convert(items.iter().cloned());
assert_eq!(it.clone().find(|&x| x % 2 == 1), Some(&1));
assert_eq!(it.clone().find(|&x| x % 3 == 2), None);
}
#[test]
#[cfg(feature = "std")]
fn owned() {
let items = [0, 1];
let it = convert(items.iter().cloned()).owned();
assert_eq!(it.collect::<Vec<_>>(), items);
}
#[test]
fn position() {
let items = [0, 1];
let it = convert(items.iter().cloned());
assert_eq!(it.clone().position(|&x| x % 2 == 1), Some(1));
assert_eq!(it.clone().position(|&x| x % 3 == 2), None);
}
#[test]
fn skip() {
let items = [0, 1, 2, 3];
let it = convert(items.iter().cloned());
test(it.clone().skip(0), &[0, 1, 2, 3]);
test(it.clone().skip(2), &[2, 3]);
test(it.clone().skip(5), &[]);
}
#[test]
fn skip_while() {
let items = [0, 1, 2, 3];
let it = convert(items.iter().cloned());
test(it.clone().skip_while(|&i| i < 0), &[0, 1, 2, 3]);
test(it.clone().skip_while(|&i| i < 2), &[2, 3]);
test(it.clone().skip_while(|&i| i < 5), &[]);
}
#[test]
fn take() {
let items = [0, 1, 2, 3];
let it = convert(items.iter().cloned());
test(it.clone().take(0), &[]);
test(it.clone().take(2), &[0, 1]);
test(it.clone().take(5), &[0, 1, 2, 3]);
}
#[test]
fn take_while() {
let items = [0, 1, 2, 3];
let it = convert(items.iter().cloned());
test(it.clone().take_while(|&i| i < 0), &[]);
test(it.clone().take_while(|&i| i < 2), &[0, 1]);
test(it.clone().take_while(|&i| i < 5), &[0, 1, 2, 3]);
}
}
|
__label__pos
| 0.994051 |
JADE
From MediaWiki.org
Jump to navigation Jump to search
A mock of a Jade entity page is presented.
Jade ecosystem - Judgments will be created by users using varied workflows
Jade is an MediaWiki extension that is designed to allow editors to annotate articles, revisions, diffs, and other wiki things using structured data. Wikipedia editors make difficult judgment calls all of the time. For example, "Is this edit vandalism?", "What is the quality level of this article?", "What type of changes are happening in this edit?", and "Is this newcomer a vandal or a good-faith contributor in need of help? Jade is a system that is designed to capture those judgments in a central repository to support collaboration and re-use. As Wikipedia invests more heavily in algorithmic strategies (e.g., ORES), human judgment and consensus needs to remain the gold standard. Jade provides an effective means for correcting the mistakes of AIs and calling attention to problematic biases.
How does Jade work[edit]
See the glossary for an overview of terminology.
Jade is a a MediaWiki extension that adds a new namespace to the wiki called "Jade". Each Jade page represents a wiki entity and it contains labels/annotations that are relevant to that entity. For example, the page with the title "Jade:Diff/123456" represents the edit described at Special:Diff/123456 and it can contain labels describing whether the edit was "damaging" or whether it appears to be saved in "good-faith" or it is "vandalism". Similarly, "Jade:Revision/123456" represents the entire page as a rev_id 123456 and it can contain labels describing the quality level of the page from "Stub" to "Featured Article".
Jade pages work like regular pages, so they have a history and changes to them can be reverted. And Jade shows up in Special:RecentChanges so activity there can be monitored.
Jade has an en:application programming interface so that labels/annotations can be submitted directly from tools without needing to manually go to the target Jade page.
Core use-cases[edit]
Coordination between patrollers[edit]
When a patroller reviews an edit and decides that it is good, it's a waste of time to review that edit again. Currently the patrolled flag can help with coordination between patrollers, but it only records that something has been done -- not what judgment was made. Labels stored in Jade create a record of the judgments that people make about wiki entities. Jade provides a flexible strategy for managing backlogs of review work.
Training new AIs[edit]
Jade stores human judgment, so it provides valuable examples for training new AIs. Generally, when training AIs, gathering high quality labeled examples is the most difficult task. Systems like m:wiki labels allow editors to generate AI training data as a specific activity outside of their work. Jade allows editors to store their judgment while they are doing their regular wiki-work. This makes it possible to build large datasets of high quality training data without wasting the time of editors.
Auditing/Refuting of AI predictions[edit]
AI systems like ORES make predictions about the subtle qualities of edits, articles, and editors themselves. By their nature, many of these predictions are wrong. Jade provides a mechanism for recording specific instances where humans disagree with AIs. This provides a reliable strategy for humans to refute the algorithms and correct mistakes in the record. It also provides a mechanism for tracking trends in what AIs get right and wrong. This is essential for identifying and addressing en:algorithmic bias.
How to get involved[edit]
Background[edit]
See JADE/Background.
What are labels?[edit]
A label in Jade begin as individuals' subjective opinions about a wiki entity. For example, "Is this edit damaging?" or "Has this version of an article reached Featured Article status?" An editor can propose a label and mark that as consensus. Another editor can disagree, propose another label and mark that label as consensus. If there is disagreement, that can be managed via the talk page. In this way, Jade allows editors to manage the production and maintenance of "labels" as first order wiki entities.
A label consists of structured data along with a free-form note. Currently, Jade supports one type of label:
Edit quality
• damaging – does this edit cause damage to the article (i.e. it is vandalism or otherwise inappropriate). The values for this are true or false.
• goodfaith – an educated guess as to whether an edit was made in good faith (or with the intent of causing harm). This field is useful for clarifying whether a "damaging" edit was intended vandalism or accidental mistake (e.g. by a newcomer). The values for this are true or false.
Proposed labels[edit]
Article quality
the quality of a given wiki page (as of a given revision). The values for this can be configured per-wiki. For example, on English Wikipedia it would use the Wikipedia 1.0 Assessment Scale.
Subject matter needed
does this edit make a subtle change that a subject matter expert will need to review? This should be marked true for cases when a patroller will not be able to effectively review the edit without specific knowledge or research to verify its claim.
Citation needed
does this sentence need a citation?
Concept topic
what topic is this Wikidata item relevant to. E.g. d:Q7251 maps to en:Alan Turing which topics are relevant? "Military and Warfare", "Computer Science", "Mathematics", "Northern Europe", "Biography", etc.
Newcomer quality
Is this new editor already doing productive work? Are they are least trying? Or are they a vandal?
Edit type
What type of change is happening in this edit? A copyedit, refactoring, elaboration, etc?
Community governance of AI systems[edit]
Jade will serve several purposes, to give a rich structure to patrolling and assessment workflows, and to produce high-quality feedback for the ORES AIs. But most importantly, Jade provides a powerful tool for editors to monitor the behavior of AIs running in the Wikis.
Jade enables editors to directly critique specific predictions made by various AIs. E.g. if ORES "damaging" model thinks an edit is damaging, but a real human editor does not, Jade is the place that human can file their rebuttal. After collecting a large number of such confirmations and rejections of ORES "damaging" model, editors can use Jade's data to monitor trends in fitness and bias. Before Jade, this work was done ad-hoc on wiki pages. E.g. see it:Progetto:Patrolling/ORES. Jade represents basic infrastructure to better support these auditing and monitoring processes.
What does Jade support?[edit]
MediaWiki integration
• Allows editors to propose/endorse labels for wiki entities (edits, pages, etc.)
• Labels can be submitted from key points in the interface: Special:Diff, action=undo, action=rollback, etc.
• Public API for to tool developers and extension developers (Huggle, RC Filters, RTRC, etc.)
Consensus building patterns
• Multiple labels can be proposed and endorsed. One label is marked as the "consensus" or "preferred" label
• Jade pages have talk pages which can be used for deeper discussion
Collaborative analysis
• Jade's labels open licensed and publicly accessible
• Machine readable dumps/api for generating fitness and bias trend reports
Curation and suppression
• Recent activity in Jade appears in Special:RecentChanges
• Jade pages can be reverted like any other page.
• Basic suppression actions are supported (hide comment, user, etc.)
Open discussions[edit]
See JADE/Implementations for alternative potential technical implementations.
See also[edit]
Subpages[edit]
|
__label__pos
| 0.763982 |
hema begur hema begur - 7 months ago 39
AngularJS Question
ng-change with ng-repeat on Select drop down menu triggers only once
Here is my controller:
App.controller('LicenseController', ['$scope', 'licenseService', function($scope, licenseService) {
var self = this;
$scope.productTypes = {name:'', productID:''};
self.productTypes = {name:'', productID:''};
$scope.selectedProduct = {name:'', productID:''};
$scope.productVersions = {productVersion:'', versionID:''};
self.productVersions = {productVersion:'', versionID:''};
$scope.fetchProductType = function(){
licenseService.fetchProductType()
.then(
function(d) {
self.productTypes = d;
$scope.productTypes = d;
console.log($scope.productTypes[1].name);
console.log($scope.productTypes[1].productID);
},
function(errResponse){
console.error('Error while fetching Currencies');
}
);
};
$scope.fetchProductType();
$scope.getProductVersions = function(){
console.log($scope.selectedProduct.productID);
licenseService.getProductVersions($scope.selectedProduct.productID)
.then(
function(d) {
$scope.productVersions = d;
self.productVersions = d;
console.log($scope.productVersions[1].productVersion);
console.log($scope.productVersions[1].versionID);
},
function(errResponse){
console.error('Error while creating User.');
}
);
};
}]);
And HTML :
<tr>
<td>
<label for="sel1">Product Type</label>
<select class="form-control" id="sel1" ng-model=productTypes ng-change="getProductVersions()">
<option ng-repeat="type in ctrl.productTypes" value="" >
{{type.name}}
</option>
</select>
</td>
</tr>
<tr>
<td>
<label for="sel1">Product Version</label>
<select class="form-control" id="ver" ng-model="productVersions" >
<option ng-repeat="version in ctrl.productVersions" value="" >
{{version.productVersion}}
</option>
</select>
</td>
</tr>
ng-change triggers only once, on the first change of product type. I also want to pass the selected product type on change. Can someone help how I can do this?
Answer
I ran into a similar problem. The way I was able to fix it was using the ng-options directive instead of looking through the options.
Here is an example in Angular's 1.x documentation:
<select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
https://docs.angularjs.org/api/ng/directive/ngOptions
|
__label__pos
| 0.857696 |
Would you mind participating in a short survey? We don't need your details - it's anonymous.
We'd like to find out more about your opinion of purchasing software online.
_capture.dll
Process name: Cyberlink Capture Wrapper DLL
Application using this process: Cyberlink PowerCinema
_capture.dll
Process name: Cyberlink Capture Wrapper DLL
Application using this process: Cyberlink PowerCinema
_capture.dll
Click here to run a scan if you are experiencing issues with this process.
Process name: Cyberlink Capture Wrapper DLL
Application using this process: Cyberlink PowerCinema
Recommended: Scan your system for invalid registry entries.
What is _capture.dll doing on my computer?
_capture.dll is a Cyberlink Capture Wrapper DLL belonging to Cyberlink PowerCinema from CyberLink Corp. Non-system processes like _capture.dll originate from software you installed on your system. Since most applications store data in your system's registry, it is likely that your registry has suffered fragmentation and accumulated invalid entries which can affect your PC's performance. It is recommended that you check your registry to identify slowdown issues.
_capture.dll
Is _capture.dll harmful?
_capture.dll has not been assigned a security rating yet. Check your computer for viruses or other malware infected files.
_capture.dll is unrated
Can I stop or remove _capture.dll?
Most non-system processes that are running can be stopped because they are not involved in running your operating system. Scan your system now to identify unused processes that are using up valuable resources. _capture.dll is used by 'Cyberlink PowerCinema'.This is an application created by 'CyberLink Corp.'. To stop _capture.dll permanently uninstall 'Cyberlink PowerCinema' from your system. Uninstalling applications can leave invalid registry entries, accumulating over time. Run a free scan to find out how to optimize software and system performance.
Is _capture.dll CPU intensive?
This process is not considered CPU intensive. However, running too many processes on your system may affect your PC’s performance. To reduce system overload, you can use the Microsoft System Configuration Utility to manually find and disable processes that launch upon start-up. Alternatively, download SpeedUpMyPC to automatically scan and identify any unused processes.
Why is _capture.dll giving me errors?
Process related issues are usually related to problems encountered by the application that runs it. The safest way to stop these errors is to uninstall the application and run a system scan to automatically identify any unused processes and services that are using up valuable resources.
The safest way to stop these errors is to uninstall the application and run a scan to identify any system issues including invalid registry entries that have accumulated over time.
Process Library is the unique and indispensable process listing database since 2004 Now counting 140,000 processes and 55,000 DLLs. Join and subscribe now!
System Tools
SpeedUpMyPC
Toolbox
ProcessQuicklink
|
__label__pos
| 0.970153 |
Re: How Long Before You Start to “Think in Max”?
Forums > MaxMSP > How Long Before You Start to "Think in Max"?
March 26, 2013 | 7:22 pm
Chris, mzed,
Thanks for the detailed responses & great advice. I've been able(for the most part) to find analogous structures to the things I'm missing from the traditional syntax's, I've been reading, trolling, reverse-engineering, plagiarizing, etc, like crazy. As you correctly state, the resources are abundant. The problem is me, I feel as though I'm moving at a snail's pace. I am amassing my toolkit, making elaborate notes on my favorite objects & what problems they solve best, as well as checking out the "related" objects in the help, etc.
Since you asked, here's a small example. My goal at the outset, which I think is modest, is to use Max for Live to enable me to design a proper arduino-based foot controller for live clip-based (as opposed to the looper device) looping. By proper, I mean Live API event-driven feedback to LED's on the pedal board, including the blinking status of fired/cued clips . The looper is 4 Tracks x 4 Scenes (for now) w/ 4 track footswitches & four scene footswitches. Basic. I'd considered trying to learn some python & do this using the framework classes, etc., but I'm thinking (hopefully correctly) that the time invested in learning Max will pay off down the road as my ambitions (& skill level) increase, and allow me to do things beyond the scope of python/framework/remote MIDI scripts, etc.
Until now, I've been duct taping everything together with a combination of Bidule, Autohotkey, Clyph-X (all brilliant tools, btw…), but I'm seeking a more integrated (and hopefully bulletproof) approach.
Consider the following subpatcher, which is one small module of (of many) in my device. Although this is a Max for Live device, I'm posting about it in this subforum, since it's more about Max "zen" than Live, since I'm not asking for help w/ the device(it does actually work…), as much as a sanity check on my approach. To me it seems heavy-handed & clunky, and lacks the minimalistic elegance that always impresses me in well written code.
Functional description:
This subpatcher accepts two inputs: A two element list consisting of TriggeredStatus (generated in the parent patcher by a live.observer, and TrackIndex, corresponding to the track selected by one of the four track footswitches.
The second input is a metro-based "clock", essentially an 0 & 127 alternating on 1/8 notes.
Any data entering the subpatcher does two things: Fires all the if-then groups, resulting in an output of four consecutive cc's, for LED control. Because only one Track has been selected ($1), the other three cc commands will be 0, turning off the previously selected LED. A signal from the "LED Clock" is then injected (or not, if the switch is activated on an exact quantize boundary & the clipslot never flashes…) into the MIDI datasteam of the active track's LED, which is then disconnected when the router is cleared by the expected change of TriggeredStatus from 1 to 0 when the clip starts actually playing/recording.
Yeah, it's pretty basic, and there are potential unhandled exceptions (accidentally stepping on two switches, etc.)and I know the proper way to do this is with the arduino handling the flashing logic, and Max simply providing a third cc value for flashing, w/o the clock hack. But at the moment, my "footswitch" is a TouchOSC iPad mockup, and besides, I guess I wanted to see if I could pull it off.
The thing is that I could do this without using "IF" objects (which seems almost to be frowned upon among the Max elite…), but it would require more objects. From the standpoint of efficiency, I have no idea how these objects run under the hood, so I'm not able to say whether one IF object beats a Change, Select, two Messages & a Trigger ( I just made that up, not saying that's the alternative, but you get the idea)
So bigger picture ( parent patch, design objectives, etc,) aside, is this approach reasonable? Heavy-handed & clumsy?
I do appreciate any feedback. Thanks again, sorry for the length.
— Pasted Max Patch, click to expand. —
[attachment=219065,5296]
Attachments:
1. TrackLEDControl.jpg
TrackLEDControl.jpg
|
__label__pos
| 0.502225 |
0
I'm running a webpage dashboard on a TV on the production floor of our factory so workers can see their live uptime, scrap etc.
I need the page to refresh when new data is available.
I want to load a page in a hidden iframe every x seconds, if the iframe is blank then do nothing but if there is a URL in the iframe then load that URL in the main page.
Example:
The Main page dashboard_Machine3.html calls a page in a hidden iframe newdata_Machine3.html every 10 seconds. If it sees that the newdata_Machine3.html page is blank, then nothing is done. If newdata_Machine3.html contains text eg "dashboard_Machine3.html" or "fire_alarm.html" then load that page in the main window.
This way I can jump to another screen if there is a critical problem somewhere or refresh that same page if there is new data to display.
-- Sorry if I wasn't clear, its a tricky one to explain :confused:
Is this possible?
2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by muppet
0
hmm, no takers...
How about this then:
Page A is displayed on a TV showing some charts and info.
Page B is not displayed anywhere but contains the text "0"
As soon as page B contains the text "1", then refresh page A
Is there any way to so this?
By watching page B using a hidden iframe, then triggering a refresh event depending on its contents was my thought. But I'm no web developer.
Thanks anyway
0
iframe code for no problem
<html></html>
iframe code for problem condition
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><script type='text/javascript'>
<!--
top.location = 'location of selected problem page'
//--></script></head><body></bopdy></html>
Edited by almostbob: n/a
0
That works great! Now I can remote control my web browser without constant refreshes.
Thanks almostbob
Here is the code I used on the main page1. Main page2 looked the same but with different content.
<html>
<head>
<script type="text/javascript">
function refreshiframe()
{
parent.frame1.location.href="/sub.html"
setTimeout("refreshiframe()",1000);
}
</script>
</head>
<body bgcolor="#ffffff" onLoad='refreshiframe()'>
Main Page1 content
<IFRAME id="frame1" src="/sub.html" style="width:0px; height:0px; border:0px">
</body>
</html>
Edited by muppet: n/a
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.
|
__label__pos
| 0.508316 |
dcsimg
Activation Timer -- a Simple Task Scheduler
WEBINAR:
On-Demand
Building the Right Environment to Support AI, Machine Learning and Deep Learning
Environment: VC++ 6/VC++.NET, Pure Win32 API
Overview
One of the most common problems in Win32 programming is dealing with a number of functions that must be executed each time the specified period expires. For example, you have three routines that must run:
function_1....every 14 seconds
function_2....every 11 seconds
function_3....every 90 seconds
A common solution involves several objects known as timers, which may seem fairly easy but cumbersome to use. This article introduces a simple yet powerful set of classes that greatly reduce the effort (and headache) required to handle multiple periodic jobs.
Algorithm
Another straightforward solution can be the following:
• For each appended task, create a new thread.
• Create a separate timer within every thread.
• Use these timers in a common way.
This may seem great, but only if your system has enough resources to handle as many threads and tasks you wish to run. It is better to use a single timer and open a new thread only when your background task is really about to start. The modified algorithm is:
• Create a timer.
• After any task is appended:
• Kill the timer.
• Calculate a minimal timeout value = Greatest Common Measure of all timeout values.
• Restart the timer.
• Each time the timer activates, check whether any tasks are up to run.
• If so, create a new thread(s) and run the task(s) in this thread(s).
This is nearly perfect, but one problem remains. If the task's execution period is less than the task's working time, a single task can start multiple threads; therefore, we must keep an eye on all of the threads to avoid resource leaks. In other words, we must implement some kind of garbage collection algorithm, which will track all thread objects and will close all unused handles.
The final algorithm is:
• Create a timer.
• After any task is appended:
• Kill the timer.
• Calculate a minimal timeout value = Greatest Common Measure of all timeout values.
• Restart the timer.
• Each time the timer activates, check whether any tasks are up to run.
• For each ready-to-run task:
• If a task is run for the first time, create a list of active threads, create and add a single thread object to this list.
• If the thread list is not empty, append a new thread object to the end of the list.
• Check all thread objects on the list, except of one recently appended, for completition of execution.
• If any thread is not active, release its thread handle.
Advantages of this approach:
• Minimal resource overhead.
• Elimination of all memory and resource leaks.
• Relatively high computational efficiency.
• Ease of use (and debug)—only one timer to track.
Class Hierarchy
The given set consists of five classes; the higher class is always a manager-class (and an aggregate) for a subordinate class.
The actual hierarchy is:
ActivationTimer --- manages ---> TaskList --- contains --->
Tasks --- (each task) controls (its own) --->
ThreadList --- handles ---> Threads
struct Thread // Structure that incapsulates the
// thread handle.
{
// Only Thread list is allowed to create/close threads:
friend class ThreadList;
protected:
// Active thread handle:
HANDLE ThreadHandle;
Thread* Next; // Next thread in a list.
Thread* Prev; // Previous thread in a list.
// Construction / destruction:
Thread(HANDLE hNewThreadHandle);
virtual ~Thread();
};
class ThreadList // Double-linked list of thread objects.
{
// Only task is allowed to handle ThreadList:
friend class Task;
protected:
Thread* Begin; // Head of list
Thread* End; // Tail of list
int NumOfThreads; // Number of threads in a list.
// Construction / destruction:
ThreadList(HANDLE hNewThreadHandle = NULL);
virtual ~ThreadList();
// Add a new thread to the list:
int AppendThread(HANDLE hNewThreadHandle);
// Get the pointer to a 'num'th thread object:
Thread* operator[] (const int num) const;
// Determine whether 'num'th thread is active or not:
bool IsThreadActive(const int num) const;
// Close the 'num'th thread object:
int CloseThreadObject(const int num);
// Get the number of threads in a list:
int GetNumOfThreads() const;
};
class Task // Class that incapsulates task data.
{
// No one is allowed to create and handle Task except for
// TaskList:
friend class TaskList;
protected:
// Time (in milliseconds), at which task is periodically
// performed:
unsigned long timeout;
void* pFunc; // Pointer to the task
// (i.e.: function).
void* pParameter; // Pointer to a *structure*
// parameter of task.
ThreadList* listOfThreads; // List of active threads
// opened by a task.
Task* Next; // Pointer to the next task
Task* Prev; // Pointer to the previous task
// Construction / destruction:
Task(const unsigned long msTimeout,
void* pNewFunc, void* pParam);
virtual ~Task();
void Execute(); // Call a task AND clean the
// threadlist.
};
class TaskList // Double-linked list of
// task data
{
// No one is allowed to create and handle TaskList except
// for ActivationTimer:
friend class ActivationTimer;
protected:
Task* Begin; // The very first Task.
Task* End; // The last Task.
int NumOfTasks; // Number of Tasks in the list.
// Construction / destruction:
TaskList(const unsigned long msTimeout = 0,
void* pNewFunc = NULL,
void* pParam = NULL);
virtual ~TaskList();
// Retrieve a pointer to the 'num'th task:
Task* operator[] (const int num) const;
// Get the number of tasks:
int GetNumOfTasks () const;
// Get the timeout value for the 'num'-th task:
unsigned long GetTaskTimeout(const int num) const;
// Add a task:
int AppendTask(const unsigned long msTimeout,
void* pNewFunc, void* pParam);
// Remove a task from the list:
int DeleteTask(const int num);
// Call a task and create an individual thread for it:
void CallTask (const int num);
};
class ActivationTimer // A simple task scheduler -
// designed as a singleton.
{
protected:
static TaskList* listOfTasks; // Pointer to the list
// of tasks.
// Minimal timeout - timer checks tasks for execution every
// 'minTimeout' milliseconds:
static unsigned long minTimeout;
static unsigned long maxTimeout; // Maximum timeout in
// the list.
static unsigned long curTimeout; // Current time.
static unsigned int TimerId; // ID of the internal
// timer.
// Check if it is a time to call a task:
static void ExecAppropriateFunc();
// Calculate 'minTimeout' value.
void RecalcTimerInterval();
static void CALLBACK TimerProc(HWND, UINT, UINT, DWORD);
public:
// Construction / destruction:
ActivationTimer(const unsigned long msTimeout = 0,
void* pNewFunc = NULL,
void* pParam = NULL);
virtual ~ActivationTimer();
// Add a single task:
int AddTask(const unsigned long msTimeout, void* pNewFunc,
void* pParam = NULL);
// Remove a task:
int RemoveTask(const int cpPos);
// Get the number of active tasks:
int GetNumOfTasks() const;
// Stop the timer:
void Halt();
// Restart the timer:
void Restart();
// Deallocate a singleton object and
// reallocate it once again.
void Reset();
};
Note 1: As you can see, two double-linked lists (the list of tasks and the list of threads for every task) form the foundation of this set of classes. The question may arise: Why not use STL's <list> container template class? The answer is: STL's <list> brings not only the <list>, but also a HUGE amount of unnecessary code, which slows and enlarges the application. So I've decided to use the most simple (and the most efficient, in our case!) "hand-made" implementation of a double-linked list.
Note 2: Another point of interest—the core class, ActivationTimer, which is implemented as a Singleton. A singleton is a class that assures existence of a maximum of one object of its type at a given time, and provides a global access point to this object. This article gives a comprehensive overview of a singleton design pattern.
Note 3: The real cause of ActivationTimer being a singleton is a stupid limitation of Win32 API: the timer callback procedure, TimerProc, is the only callback function in Win32 that does not take any user-defined argument. This behavior can be overridden in two ways:
• By using not an ordinary timer (SetTimer / KillTimer), but a special synchronization object—waitable timer
(CreateWaitableTimer / SetWaitableTimer / CancelWaitableTimer).
Unfortunately, this approach produces significant performance overhead.
• By using a special synchronization object, which is new to VC++ 7 - timer-queue timer
(CreateTimerQueue / CreateTimerQueueTimer / DeleteTimerQueueEx / DeleteTimerQueueTimer).
Timer-queue timers are lightweight objects that enable you to specify a callback function to be called at a specified time or a period of time. These objects are new to VC++ 7, and I still don't have the ability to implement them, so ... their time is yet to come.
Implementation
Note 4: For better understanding, only member-functions that have a direct influence on the algorithm will be explained here. The source code contains detailed comments on every function.
Step by step:
• Create a timer:
• // Create a timer with one task in the task list:
ActivationTimer::ActivationTimer(const unsigned long msTimeout,
void* pNewFunc, void* pParam)
{
if((msTimeout <= 0UL) || !pNewFunc)
{
listOfTasks = new TaskList();
TimerId = 0;
minTimeout = 0;
maxTimeout = 0;
curTimeout = 0;
return;
}
listOfTasks = new TaskList(msTimeout, pNewFunc, pParam);
minTimeout = msTimeout;
maxTimeout = msTimeout;
curTimeout = msTimeout;
Restart();
}
// Restart the timer:
void ActivationTimer::Restart()
{
TimerId = SetTimer(NULL, NULL, minTimeout, TimerProc);
}
• Append a task:
• // Add a new task to the task list.
// Return value: zero-based position of task in a task list.
int ActivationTimer::AddTask(const unsigned long msTimeout,
void* pNewFunc, void* pParam)
{
// A little bit of parameter validation:
if((msTimeout <= 0UL) || !pNewFunc)
return -1;
// Kill the timer:
Halt();
// Append a new task:
int pos = listOfTasks->AppendTask(msTimeout,
pNewFunc, pParam);
// Recalculate 'maxTimeout' value:
maxTimeout = maxTimeout < msTimeout ?
msTimeout : maxTimeout;
// Recalculate 'minTimeout' value:
RecalcTimerInterval();
// Recreate the timer:
Restart();
return pos;
}
• After any task is appended—calculate minTimeout value:
• // Calculate the value of minTimeout.
// This is a time when 'ExecAppropriateFunc()' routine is
// periodically called.
void ActivationTimer::RecalcTimerInterval()
{
minTimeout = listOfTasks->GetTaskTimeout(0);
for(int i = 0; i < listOfTasks->NumOfTasks; i++)
{
unsigned long tempTimeout = GCM(minTimeout,
listOfTasks->
GetTaskTimeout(i));
minTimeout = minTimeout >
tempTimeout ?
tempTimeout : minTimeout;
}
curTimeout = minTimeout;
}
• Each time timer activates, check if any tasks are up to run:
• // Check whether it is a time to call one of the tasks from
// the task list.
void ActivationTimer::ExecAppropriateFunc()
{
bool reset = true;
for(int i = 0; i < listOfTasks->NumOfTasks; i++)
{
// If time has come, call the 'i'th task:
if((curTimeout % listOfTasks->GetTaskTimeout(i)) == 0)
{
listOfTasks->CallTask(i);
reset &= true;
}
else
{
reset &= false;
}
}
// If all tasks are called simultaneously,
// reset curTimeout value:
if(reset)
curTimeout = minTimeout;
else
curTimeout += minTimeout;
}
• If so, execute these task(s):
• // Call a task and create an individual thread for it:
void TaskList::CallTask(const int num)
{
Task* task = operator[](num);
task->Execute();
}
// Create an individual thread for a task:
void Task::Execute()
{
listOfThreads->AppendThread(CreateThread(NULL, 0,
(LPTHREAD_START_ROUTINE)pFunc,
pParameter, 0, 0));
// ...and wipe out all unused thread handles:
int numThreads = listOfThreads->GetNumOfThreads();
for(int i = 0; i < numThreads - 1; i++)
{
if(!(listOfThreads->IsThreadActive(i)))
listOfThreads->CloseThreadObject(i);
}
}
• On exit, free all the resources, close all thread handles:
• Task::~Task()
{
delete listOfThreads;
}
ThreadList::~ThreadList()
{
Thread* target = Begin;
Thread* temp;
if(target) // If ThreadList is not empty...
while(target)
{
temp = target->Next;
delete target;
target = temp;
}
}
Thread::~Thread()
{
// Check if thread has exited.
// If it did not - terminate it.
DWORD exitCode;
GetExitCodeThread(ThreadHandle, &exitCode);
// !!! UNSAFE CODE !!!
// Try not to use lengthy operations OR
// use some kind of internal completition
// flag to explicitly instruct thread to exit.
// Refer MSDN on hazards of TerminateThread.
if(exitCode == STILL_ACTIVE)
TerminateThread(ThreadHandle, 0);
CloseHandle(ThreadHandle);
}
Note 5: The Thread::~Thread destructor needs some explanation. Calling TerminateThread can be quite dangerous if the target thread is still running, because:
• If the target thread is allocating memory from the heap, the heap lock will not be released.
• If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
• If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.
A possible solution may be one of the following:
• Do not use lengthy operations as a thread function.
• Use a special bool variable (something like: m_bStopExecution), and periodically check the state of this variable.
If this variable is true, the thread can gracefully quit.
• Use a synchronization object—for example, semaphore or waitable timer—to instruct a thread to stop execution (just the same as above).
Please refer to MSDN for more information on TerminateThread and synchronization objects.
Usage
To use ActivationTimer, do the following:
• Include "ActivationTimer.cpp" and "ActivationTimer.h" in your project.
• Write the following line at the beginning of the "StdAfx.h" file:
• #include "ActivationTimer.h"
• Write the following line at the beginning of the "ActivationTimer.cpp" file:
• #include "StdAfx.h"
• Within the main file of your application, declare:
• ActivationTimer actTimer;
• To add a task with no parameters, write:
• void MyFunction()
{
....
}
....
actTimer.AddTask(10000, MyFunction);
This will periodically execute MyFunction every 10 seconds.
• To add a task with a single parameter, declare:
• void MyFunction2(void* pParam)
{
int* value = (int*)pParam;
....
}
....
int someValue = ... ;
actTimer.AddTask(15000, MyFunction2, &someValue);
• If you wish to pass several parameters to your task-function, declare a structure:
• typedef struct
{
int valueA;
float valueB;
bool valueC;
...
} MyStruct;
and write:
void MyFunction3(void* pParam)
{
MyStruct* structVal = (MyStruct*)pParam;
....
}
....
MyStruct* somestruct = new MyStruct;
... // initialize struct here
actTimer.AddTask(5100, MyFunction3, somestruct);
The demo project (see link below) is an ordinary "Hello, World!" application, built with AppWizard, with these examples included. Enjoy!
Acknowledgements
Thank you all the CodeGuru visitors who posted comments, and double-Thank-you to everyone who wrote me, reporting bugs, ideas, and suggestions!
P.S.
Why not a Task Scheduler instead of the Activation Timer? That's because Windows already has its Task Scheduler application, so I've decided not to mess up. At least, Activation Timer application is not included in a standard Windows package, yet........
Downloads
Download demo project - 12 Kb
Download source - 5 Kb
Comments
• ...and the problem with Win32 timers?
Posted by Legacy on 09/09/2003 12:00am
Originally posted by: Naldo
What about the poor precision of Win32 timers and its low priority message in the queue? this would be don't throw the timer event, right?
Thx in advance,
Naldo
Reply
• Why not use built-in Windows schedule ?
Posted by Legacy on 07/07/2003 12:00am
Originally posted by: Florian DREVET
All is in the title :-)
Reply
• Ideas
Posted by Legacy on 06/30/2003 12:00am
Originally posted by: Jedi
I have had a similar situation where I needed to retrieve data from multiple entities at the same time. So I have put a timer in a service and each time it wakes up, it retrieves data in multiple threads. But sometimes data retrieval of these threads goes beyond the timer limit and then everything collapses.
Any design suggestions? Any patterns that you know of?
Any idea how to configure multiple instances of the service to distribute load?
Reply
• BUGFIX
Posted by Legacy on 06/27/2003 12:00am
Originally posted by: Dmitry Khudorozhkov
Instead of:
void ActivationTimer::ExecAppropriateFunc()
{
for(int i = 0; i < listOfTasks->NumOfTasks; i++)
{
if((listOfTasks->GetTaskTimeout(i) == curTimeout)
|| // or
((curTimeout % listOfTasks->GetTaskTimeout(i)) == 0))
listOfTasks->CallTask(i);
}
curTimeout += minTimeout;
if(curTimeout > maxTimeout)
curTimeout = minTimeout;
}
there must be:
void ActivationTimer::ExecAppropriateFunc()
{
bool reset = false;
for(int i = 0; i < listOfTasks->NumOfTasks; i++)
{
if((curTimeout % listOfTasks->GetTaskTimeout(i)) == 0)
{
listOfTasks->CallTask(i);
reset = true;
}
else
{
reset = false;
}
}
if(reset)
curTimeout = minTimeout;
else
curTimeout += minTimeout;
}
Reply
• C/C++ & OOP design
Posted by Legacy on 06/25/2003 12:00am
Originally posted by: no mather
wow, what example of poor C/C++ & OOP design understandings ...
any questions:
what exactly means paramerer specification of 'void f(const unsigned int msTimeout)" ( especialy what means 'const' )?
and with this funct declaration, what exactly checks next statement: if(msTimeout <= 0) ( especialy '<' )?
why 'void CALLBACK TimerProc(...)' is not a static member of ActivationTimer?
what about functors as task objects?
and what about any params for specific task?
why 'friend' anywhere?
what about Double-linked list ws std::vector?
may be ActivationTimer MUST be a singleton?
let stop with questions.
at another side, goot work. don't stop here. here always well have nonadvanced developers, that will search for something like this.
enjoy
Reply
• You must have javascript enabled in order to post comments.
Leave a Comment
• Your email address will not be published. All fields are required.
Most Popular Programming Stories
More for Developers
RSS Feeds
Thanks for your registration, follow us on our social networks to keep up-to-date
|
__label__pos
| 0.854667 |
How to check if two arrays are equal with JavaScript?
var a = [1, 2, 3];
var b = [3, 2, 1];
var c = new Array(1, 2, 3);
alert(a == b + "|" + b == c);
demo
How can I check these array for equality and get a method which returns true if they are equal?
Does jQuery offer any method for this?
25 thoughts on “How to check if two arrays are equal with JavaScript?”
Leave a Comment
|
__label__pos
| 1 |
How do you Recognize a Phishing Attempt?
PHISHING Blog
What is phishing?
Phishing refers to attempts by hackers – or criminals – to impersonate a trusted communication partner in a digital communication via well-crafted but fake websites, emails or short messages. The goal of these scams is, for example, to obtain an Internet user’s personal information in order to use it to carry out further criminal activities, such as clearing out your account.
Think your business is safe from phishing scams? Please reconsider. Given the increasing sophistication and scope of phishing attacks, your company can’t afford to take cybersecurity for granted. Knowing how to prevent phishing scams is one of the most effective steps you can take in the fight against data breaches.
A 2020 study found that 85 percent of all businesses are affected by phishing attacks. This is due to the widespread shift to remote work without proper preparation and additional cybersecurity measures. Phishing scams have become one of the most common ways to obtain sensitive information and spread ransomware, resulting in the loss of millions of dollars on a global scale.
How to recognize a phishing attempt?
A phishing scam occurs when someone impersonates a trusted entity, such as your boss, a bank, or a credit card company, to obtain sensitive information. Commonly sought information includes:
• Username and password
• Social security numbers
• Financial information
• Account numbers
Phishing attempts usually create a sense of fear or urgency to get targets to act quickly rather than think carefully about giving out private information.
Although phishing scammers regularly update their techniques, there are some indicators that can help you spot a phishing attempt, so pay extra attention there!
Suspicious activity or login attempts
Many online services send emails to notify you when someone has tried to log into your account from a new device or location. If you don’t recognize this activity, it could be an indication of a phishing attempt.
False invoices
Scammers sometimes pose as contractors or vendors to trick employees into paying fake invoices with company money. One scammer posed as a legitimate company to get Google and Facebook to pay him a combined $122 million.
Phishing scammers may try to trick users into clicking on links that lead to phishing pages disguised as authentic websites. After the user enters their username and password, the scammer uses the credentials to access their online account and lock them out.
Coupons or free offers
Some phishing attempts use free offers to trick people into opening suspicious emails, clicking on links or revealing personal information that can be used to access other online accounts.
Confirmation of personal information
Some phishing attempts manipulate people into revealing personal information. Fraudsters may use birthdays or social security numbers to answer security questions and “prove” their identity as an account holder.
Refunds they don’t deserve
Phishing scammers have even posed as the IRS and contacted people about an outstanding tax refund. The scam requires targets to provide personal information such as address, date of birth, driver’s license number or PIN for electronic tax returns.
“Problems” with your payment information or account
Phishing attacks can also trick users into revealing financial information by posing as an e-commerce website or online service and asking users to confirm their payment information.
Common Phishing Baits
About 22 percent of data breaches are due to phishing. A key step to avoiding phishing scams is recognizing different phishing attacks. Here are the seven most common types of phishing attacks:
Deceptive phishing
Deceptive phishing is the most common type of phishing scam. A scammer poses as a legitimate source to trick people into giving up their personal information or login credentials. Deceptive phishing emails often use threats to scare users into revealing confidential information.
Pro tip: Deceptive phishing attempts typically contain generic greetings, grammatical or spelling errors, and redirected or shortened links that lead to phishing pages. You should always make sure that a sender is legitimate before clicking on a link or downloading attachments.
Spear phishing
Spear phishing uses personalized information, usually collected through social media, to target specific users and achieve a higher success rate. In these phishing attempts, emails are tagged with the target’s name, location, and even phone number to make the target believe that the sender knows them. However, the goal remains the same: to trick the target into revealing personal information, clicking on a link to a phishing website, or downloading malware.
Whaling
Whaling is a specific type of spear phishing attack that targets executives to access high-level corporate data and accounts. If a whaling attack is successful, a fraudster can perform CEO fraud. CEO fraud involves using a CEO or other executive’s account to authorize fraudulent wire transfers or request employee information that can then be sold on the dark web.
Whaling attacks are very successful because executives typically do not receive the same security awareness training as their employees. To combat the risk of CEO fraud, companies should require that executives participate in ongoing cybersecurity training.
Clone phishing
Clone phishing attacks duplicate legitimate emails to appear trustworthy and replace legitimate attachments or links with malicious versions. Clone phishing emails often come from spoofed email addresses and reference a previous message or claim to contain updated information or files.
Tip: Users should always check links, even if they come from a seemingly trustworthy source. If in doubt, contact the supposed sender directly in a new email instead of replying to a possible clone phishing email.
Smishing
Smishing, a combination of “SMS” and “phishing,” uses text messages to trick users into downloading malware or sharing personal information. In smishing attempts, scammers impersonate well-known companies (such as a vendor or your financial institution) to trick targets into downloading a malicious app or entering their personal information on a phishing website.
Smishing campaigns have posed as very trustworthy entities such as the Amazon, FedEx, and Apple. Users should be wary of messages sent from unknown phone numbers and call the organization directly to verify the authenticity of a message if they are unsure.
Pharming
Unlike traditional phishing scams, pharming does not always target victims directly. Instead, pharming changes the domain of a legitimate website to redirect users to a phishing website. Some pharming attacks send emails that change the host files on the target’s computer and redirect all URLs to a phishing website where malware is installed or personal information is stolen.
Tip: Employees should only enter their credentials on HTTPS-protected websites and regularly update their antivirus software on all devices.
Angler phishing
Angler phishing occurs when scammers impersonate a brand’s customer service account on social media. The scammer then contacts users who post complaints and shares a link that pretends to redirect the target to a customer service chat. However, the link usually leads to a phishing page that steals the target’s data or downloads malware to their device.
Tip: Users should verify an account before dealing with it or directly visit the brand’s customer service center to address complaints.
humbuglabs.org
Add a comment
|
__label__pos
| 0.85947 |
2
$\begingroup$
Does the infinite product diverge to zero or some other value?
$$\prod_{n \mathop = 1}^\infty {\frac{2^n}{3^n}}$$
$\endgroup$
• 2
$\begingroup$ It's an infinite product, not a series. $\endgroup$ – Robert Israel Jul 19 '13 at 4:49
• 4
$\begingroup$ The correct terminology is : "it diverges to 0", consider taking the logarithm of this product and looking at the sum. $\endgroup$ – Arjang Jul 19 '13 at 5:26
• $\begingroup$ Thank you for correcting my amateurish mistakes. $\endgroup$ – KeithSmith Jul 19 '13 at 12:10
14
$\begingroup$
Consider $$P_m=\prod_{n=1}^m\frac{2^n}{3^n}=\left(\frac{2}{3}\right)^{m(m+1)/2}$$
Then, $$P_{\infty}=\prod_{n=1}^{\infty}\frac{2^n}{3^n}=\lim_{m\to\infty}P_m=\lim_{m\to\infty}\left(\frac{2}{3}\right)^{m(m+1)/2}=0$$
| cite | improve this answer | |
$\endgroup$
• 5
$\begingroup$ Why is it so big? $\endgroup$ – Potato Jul 19 '13 at 5:21
• $\begingroup$ @Potato: with \frac it's too small and with \dfrac it's too big. $\endgroup$ – Aang Jul 19 '13 at 5:24
• $\begingroup$ I personally don't think it's too small with \frac. But to each their own, I suppose. $\endgroup$ – Potato Jul 19 '13 at 5:26
• 1
$\begingroup$ You can scale rendered math for yourself if you find it too small. There's no need to use commands like \large, really. $\endgroup$ – Antonio Vargas Jul 19 '13 at 7:00
• 1
$\begingroup$ I guess, @martycohen, that’s Littlewood. $\endgroup$ – Lubin Jul 24 '13 at 4:41
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.904296 |
Atomic Layout
Atomic Layout is a spatial distribution library for React. It uses CSS Grid to define layout areas and render them as React components. This pattern encourages separation of elements and spacing, preventing contextual implementations and boosting maintenance of layouts.
import React from 'react'
import { Composition } from 'atomic-layout'
// Define layout areas: visual representation
// of what composes a layout, detached from
// what components are actually rendered.
const areasMobile = `
thumbnail
header
footer
`
// Declare responsive changes of your areas.
// Operate in two dimensions, remove areas
// or introduce new ones.
const areasTablet = `
thumbnail header
thumbnail footer
`
const Card = ({ title, imageUrl, actions }) => (
<Composition areas={areasMobile} areasMd={areasTablet} gap={20}>
{/* Get React components based on provided areas */}
{({ Thumbnail, Header, Footer }) => (
<React.Fragment>
<Thumbnail>
{/* Render anything, including another Composition */}
<img src={imageUrl} alt={title} />
</Thumbnail>
{/* Preserve semantics with polymorphic prop */}
<Header as="h3">{title}</Header>
{/* Responsive props: just suffix with a breakpoint name */}
<Footer padding={10} paddingMd={20}>
{actions}
</Footer>
</React.Fragment>
)}
</Composition>
)
export default Card
Atomic Layout is responsive-first. It uses Bootstrap 4 breakpoints by default, which you can always customize for your needs.
Motivation
Modern layout development is about modularity and composition. Following the best practices of Atomic design, we strive toward independent UI units that gradually compose into more meaningful pieces. While the attention paid to units implementation is thorough, we often overlook how to achieve layout composition that scales. It's as if we forget that spacing defines composition.
When it comes to distributing the spacing things get more difficult. First of all, true contextless spacing is hard. To make things worse, all present solutions couple spacing with UI elements, inevitably making small reusable pieces contextful and, thus, hard to maintain.
Atomic Layout helps you to compose your elements by introducing a dedicated spacing layer called Composition. It encourages you to separate concerns between UI elements' visual appearance and spacing between them. With the first-class responsive support at your disposal you can build gorgeous responsive permutations of your elements without leaving the dedicated spacing layer, keeping UI elements contextless and predictable. Embrace the era of a true layout composition!
Implementations
Atomic Layout has multiple implementations depending on the styling solution:
Package name Latest version Styling library
atomic-layout Package version styled-components
@atomic-layout/emotion Package version @emotion/styled
Documentation
See the Official documentation.
Here are some shortcuts for quick access:
Examples
Although the examples below use atomic-layout package, they are fully compatible with other styling implementations of the library (i.e. @atomic-layout/emotion).
Basics
Basic composition: square and circle
Basic composition
Combine two UI elements into a single one using Composition.
Component with responsive props
Responsive props
Change a prop's value depending on a breakpoint.
Composition of other compositions
Nested composition
Any element can be a composition and a composite at the same time.
Intermediate
Conditional rendering
Conditional rendering
Render or display elements conditionally based on breakpoints.
Custom configuration
Custom configuration
Configure a default measurement unit, custom breakpoints, and responsive behaviors.
Shorthand media query
Shorthand media query
Use a shorthand query function to declare inline media queries in CSS.
Materials
Artem speaking at React Finland
Creating layouts that last (React Finland, 2019)
Find out the main aspects of a layout's maintainability and why spacing plays a crucial role in it. Learn how to wield layout composition as an actual React component–a missing glue for your elements and design systems.
SurviveJS logo
Layout composition as a React component (SurviveJS)
Read through the extensive interview about how Atomic layout came to be, how it's different from other solutions, and which practices it encourages.
The Future of Layouts — Artem Zakharchenko
The future of layouts (React Vienna, 2018)
Watch Artem discussing the biggest obstacle to achieve maintainable layouts, and showcases a way to combine existing technologies to build clean UI implementations using Atomic layout.
Community
Reach out to us to share an awesome project you're building, or ask a question:
Browser support
Atomic Layout's browser support is made by the browser support of underlying technologies the library uses. Pay attention if your project can support CSS Grid to be sure you can use Atomic Layout.
GitHub
https://github.com/kettanaito/atomic-layout
|
__label__pos
| 0.594012 |
Message Boards Message Boards
GROUPS:
Can a type be set globally using inner/outer and also be replaceable?
Posted 10 months ago
1845 Views
|
11 Replies
|
4 Total Likes
|
Problem Description & Motivation: Using Non-SI-Units for time
This post culminates earlier questions I voiced on Community (Unit checking and making use of unit attributes and Why can't a parameter be used to set the unit attribute?). I am writing a library for System Dynamics modeling for business, economics, and social sciences. From what I have learned in the discussions cited above, treating time in models one should preferably do what engineers do: Use SI-units whenever possible and then use displayUnit to convert them to whatever you want.
There are a few inconveniences though: The displayUnit for the Modelica var time cannot be modified and unfortunately in diagrams there is no nice drop-down selection for a different displayUnit. Also, everything internally is stored in seconds making parameter values rather bizarre when we think in months or years.
So, writing a library I would like the user to make a choice of a global type called ModelTime which ideally would be declared as inner and replaceable at some top-level class. Then any component within a model written using the libary could use the global type to consistently treat any time-related vars.
Minimal Example
The following example shows how I would like to implement this.
• package Units declares two Non-SI Unit types ( Time_year, Time_month)
• package Interfaces contains a partial model class GenericSimulationModel which will be the top-level scope for any model written using the library. It is supposed to provide the type ModelTime as an inner and replaceable class
• package Components defines a simple block class that uses ModelTime via an outer construct to define its output y that simply shows time in the globally chosen units of time
• model Example ties all of this together to provide an example how any model using the library should work out
Here is the code:
model MinimalExample
package Units
type Time_year = Real(final quantity = "Time", final unit = "yr");
type Time_month = Real(final quantity = "Time", final unit = "mo");
end Units;
package Interfaces
partial model GenericSimulationModel "Top-level model scope providing global vars"
inner replaceable type ModelTime = Years "Set to : Months, Years";
protected
type Years = Units.Time_year;
type Months = Units.Time_month;
end GenericSimulationModel;
end Interfaces;
package Components
block ComponentUsingTime
outer type ModelTime = MinimalExample.Units.Time_year;
output ModelTime y;
equation
y = time;
end ComponentUsingTime;
end Components;
model Example
extends Interfaces.GenericSimulationModel(
redeclare replaceable type ModelTime = Months
);
Components.ComponentUsingTime c;
end Example;
equation
end MinimalExample;
While this model compiles without error it does not work out as I intended it: The redelcared type is not used within the component so that it remains set to "years" and not "months".
What can I do to achieve what I want to do?
Note: I crossposted the question on StackOverflow.
11 Replies
... continued from above
Inner/Outer with a simple constant
I am even more perplexed by the following. Let's simplify the above example, instead of using complicated type constructs, we might simply define a constant String UnitOfTime that will be set to provide the string-expression needed to define unit = "some unit" for a var in a sub-component. Again, that constant expression will be given the prefix inner (note, that we should not be needing replaceable here, as we may use simple modification instead).
Minimal Library
The "library" now only consists of a partial model GenericSimulationModel where the unit-string is defined and a very simple component SimpleClock that is to return the simulation time in the Non-SI-Unit chosen. Within that component we use the unit-string given as a global constant directly to configure the output y:
output Real y( final quantity = "Time", unit = UnitOfTime );
Here is the complete MinimalLibrary - code for this:
package MinimalLibrary "Example for setting a global unitString constant"
package Interfaces "Partial models and connectors"
partial model GenericSimulationModel "Top-level class defining global parameters for simulation model"
inner constant String UnitOfTime = "yr";
end GenericSimulationModel;
end Interfaces;
package Components
block SimpleClock "Return the simulation time in Non-SI-Unit of time"
outer constant String UnitOfTime;
output Real y(final quantity = "Time", unit = UnitOfTime);
equation
y = time;
end SimpleClock;
end Components;
model Example "Show a simple clock functionality"
extends Interfaces.GenericSimulationModel( UnitOfTime = "mo");
Components.SimpleClock clock;
end Example;
end MinimalLibrary;
Errors and Warnings
Warning issued for missing start value for outer declaration
While the whole library code above validates sucessfully, there is a warning given when validating the SimpleClock in the Components package which honestly I do not understand:
Warning
System Modeler seems to issue a warning, because within the outer declaration there is no start value given? But that in my opinion is how you are supposed to write outer declarations. I will cite Peter Fritzon:
Outer class declarations should be defined using the short class definition. Modifiers to such outer class declarations are only allowed if the inner keyword is also present, i.e., a simultaneous inner outer class declaration.
The last point is illustrated by the following erroneous model:
class A
outer parameter Real p = 2; // Error, since declaration equation needs inner
end A;
Fritzson, Peter. Principles of Object-Oriented Modeling and Simulation with Modelica 3.3: A Cyber-Physical Approach (Kindle-Positionen8875-8881). Wiley. Kindle-Version.
Error given when running the Example model in Simulation Center
Trying to run the model Example will not finish since the model compiles with an error:
Error
Note: The error will arise also, when the modification (UnitOfTime = "mo") is removed.
After having learned, that we must use constants to set the unit attribute (here), I am rather perplexed to now find, that this will not work out when we use inner/outer declarations.
Is there something wrong with the way inner and outer are implemented?
Posted 10 months ago
The behavior you see for MinimalExample.example and MinimalLibrary.Example are bugs, and from what I can see they should work, I have forwarded them to a developer working on these things.
As for the validation of MinimalLibrary.Components.SimpleClock, what happens is that you have an outer component (outer constant String unitOfTime). The rules for inner/outer in Modelica (this was updated recently) is that an outer element requires that an inner element exists or can be created in a unique way. In this case, there exists no inner element, but a unique inner element can be created, by simply taking the outer declaration as it is (this is basically what the first warning says). The second warning appears because the constant has no binding (although I am not sure why it is referred to as a parameter).
We have recently implemented some support for setting the displayUnit for the x-axis in SimulationCenter, currently it only goes up to days, maybe we should see if we could add years as well. I guess you would like a way to specify this in the model so you don't have to change the plots all the time.
As for the parameters in the diagram view, I assume you are referring to things like this:
Inertia with parameter
which seems to always use the unit. So, it would be better for you if it was displayed in the displayUnit, maybe with the displayUnit as well? So, in the picture above, it would read "J = 1.7 kgm^2", or if the displayUnit was changed to lb ft^2, it would say "J = 40.34 lb ft^2".
Carl,
Thank you for confirming the impression I had about the examples given. Making these things work out in WSM would be very helpful. The warning (besides falsly referring to a parameter) given for the outer declarationg does make sense as we talk about it. It may be better to work with inner outer instead if one cannot be sure about when and where eventually an inner construct is placed?
With regard to displayUnit it would be nice, if this could be influenced globally (maybe then to be overriden by user choice?) in a model for:
• display of time in plots
• display of parameters in icon- and diagram-view
• actually, any output of model entities and possibly also for inputs (cf. Time Scale parameter for MCTT)...
Regarding the conversion of times and (!) rates I would suggest to have: years (yr), quarter years (qtr), months (mo), and weeks (wk) available (next to d, h, min, s) , as these are all reasonable units of time depending upon the setting and they also reflect the choices a user has in most dedicated SD modeling software.
Note: The abbreviation "y" , which is by default already included in the unit conversion table, to me looks a lot less common - I would suggest to go for "yr" instead.
The convenient treatment of rates is (unfortunately) a matter I have not really solved yet: To my understanding, one would have to define a conversion for each and every rate possible, e.g. there needs to be different conversion for apples/second and oranges/second. Thus, working with seconds as the principal unit of time necessitates, in my opinion, that one drops all units for counting stocks in System Dynamics (e.g. money, people, equipment, factories, shops, etc.) so that we only need to convert dimensionless rates (e.g. 1/s)? -- I would be very happy to hear, that this understanding of mine were wrong, and I would greatly appreciate, if you could offer a better way to deal with rates.
Guido
I cannot see that SystemModeler comes with a conversion to/from years. I assume that the reason for that is that there are many years to choose from:
• Calendar year
• Calendar leap year
• Calendar year average
• Tropical year
Otto
But WSM as of Version 12.0 already ships with a predefined conversion:
Screenshot
The first entry is the predefined value and the second one is my custom entry. As you can see, assuming 365 days/year most often suffices.
Your doubts about a single, unchallenged definition for one year in seconds is of course very to the point (scientifically and technically) and they concisely illustrate the difficulties in adapting Modelica/WSM to the more abstract and diffuse requirements of business and social sciences modeling.
Very often, e.g. in strategic business modeling, we will have much more important uncertainties to worry about than imprecise definitions for a "year". If accuracy really matters, then we should indeed go back to days. Most data we get are concerned with some kind of period average and even then other factors matter (e.g. revenue as a function of business days not days in a calendar year; a leap year might have actually less business days than a regular year...).
Ultimately, you are imo making a case for leaving it all up to the modeler and the model's user to judge for themselves what they need in a given context:
Indeed agood case in point for allowing to have a custom conversion table that can easily be applied to modify the display of the system time.
Guido
I was focused looking for the time unit so I scrolled immediately down to s and there isn't a s to y conversion.
Indeed agood case in point for allowing to have a custom conversion table that can easily be applied to modify the display of the system time.
I totally agree with you, in a dream scenario you should also be able to get a date/time display of system time given a specified epoch.
Otto
Otto,
what about rates? Is there a remedy for the apples/second and oranges/second problem I mentioned above?
Thanks.
Guido
Posted 10 months ago
Hello Guido,
We have had some discussions and we think we possibly could implement some automatic support for handling conversion of rates. We have considered a scenario where you have a variable with unit "apples/s" and a displayUnit "apples/year". Given that you have a conversion "1/s" to "1/year" the conversion for "apples/s" to "apples/year" would automatically be inferred. Would that be what you want?
Carl,
that would indeed be a great help. At the moment I am simply reducing everything (using an enumeration called "UnitChoices") to:
• Dmnl ("1")
• Rate ("1/s")
• Time ("s")
Thinking about this from a model user's perspective: You would want to place a stock or a converter (Block) element somewhere and then assign a unit to its output (more tricky for complex sub-system elements with lots of different outputs, which rather call for bus-like output connectors - which would not be expandable per se ?).
That user-dialog has to be made "easy to use" (which is why I simply go for drop-down enumeration) and "reliable". If the user has to enter a string, say "apples/s", then there is some danger of a typo and everything breaks down.
Maybe with what you are saying one could come up with a mix: use a drop-down field to distinguish the choices like the ones listed above and additionally allow the user to overwrite the dimensionless part of the drop-down choice: "1". In that case, the user can choose a Rate and then the string "apple" or "apples".
Hope I have written this clearly?
Guido
PS: My understanding is, that what I have described for the user is the reverse procedure of what you will probably be doing, e.g. parse a string for "something/s" and then replace something -> 1?
Posted 10 months ago
It might be that I don't know enough about what you are modeling, but it seems to me that an output of a specific block would be either dimensionless, a rate or time, and for a specific block you don't really want to change it?
In the package below I have demonstrated some ways to set units in the GUI, and the model Test shows all four of them.
The block Item has an output that is something, e.g. "orange". What this is is set by the constant itemUnit, which shows up in the GUI in the "General" tab in the group "Units" (this is set by the annotation following the declaration of itemUnit).
The block Rate has an output that is a rate of something, e.g. "apple/s". You can set what "X" in "X/s" through the"rateUnit constant, which also shows up in the GUI. Here I have also set a displayUnit to be "X/h", but since we don't have the feature described in my last post, SimulationCenter won't be able to display in "X/h" unless X is 1.
In the block Generic I have done something like what you described. The block output has a unit that is either "1", "s" or "1/s", and this can be chosen with a drop-down list. The drop-down list is created from the choices part of the annotation after the declaration of the output, each which has a part that is the modification to be applied (e.g. "= 1/s") and a description of what it is (e.g. "rate"). The description is what is shown in the drop-down menu.
Finally, in the block GenericWithX you can specify both a base unit (e.g. "banana" or "second") and specify it is a rate or not.
Concerning your PS, yes, that would in principle be what it would do; read "X/s", then use for example,the rule for "1/s" -> "1/year" to convert to "X/year".
package UnitsAndRates
model Test
Item item1(itemUnit = "apple") annotation(Placement(visible = true, transformation(origin = {-30, 57.954}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
Rate rate1(rateUnit = "orange") annotation(Placement(visible = true, transformation(origin = {-10, 10}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
Generic generic1(genericUnit = "1/s") annotation(Placement(visible = true, transformation(origin = {-65, -40}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
GenericWithX genericWithX1(base = "banana") annotation(Placement(visible = true, transformation(origin = {50, -2.046}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
GenericWithX genericWithX2(base = "kiwi", rate = "/s") annotation(Placement(visible = true, transformation(origin = {30, -62.465}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
annotation(Diagram(coordinateSystem(extent = {{-150, -90}, {150, 90}}, preserveAspectRatio = true, initialScale = 0.1, grid = {5, 5})), Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(visible = true, lineColor = {0, 114, 195}, fillColor = {255, 255, 255}, extent = {{-100, -100}, {100, 100}}, radius = 25), Text(visible = true, textColor = {64, 64, 64}, extent = {{-150, 110}, {150, 150}}, textString = "%name")}));
end Test;
block Rate
constant String rateUnit = "1" annotation(Dialog(group = "Units"));
Modelica.Blocks.Interfaces.RealOutput y(unit = rateUnit + "/s", displayUnit = rateUnit + "/h") annotation(Placement(visible = true, transformation(origin = {155, 0}, extent = {{-10, -10}, {10, 10}}, rotation = 0), iconTransformation(origin = {101.511, 0}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
equation
y = 1 + cos(sin(time));
annotation(Diagram(coordinateSystem(extent = {{-150, -90}, {150, 90}}, preserveAspectRatio = true, initialScale = 0.1, grid = {5, 5})), Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(visible = true, lineColor = {0, 114, 195}, fillColor = {255, 255, 255}, fillPattern = FillPattern.Solid, extent = {{-100, -100}, {100, 100}}), Text(visible = true, textColor = {64, 64, 64}, extent = {{-150, 110}, {150, 150}}, textString = "%name"), Text(visible = true, origin = {-0, 3.332}, extent = {{-100, -46.668}, {100, 46.668}}, textString = "Rate")}));
end Rate;
block Item
constant String itemUnit = "1" annotation(Dialog(group = "Units"));
Modelica.Blocks.Interfaces.RealOutput y(unit = itemUnit, displayUnit = itemUnit) annotation(Placement(visible = true, transformation(origin = {153.595, 0}, extent = {{-10, -10}, {10, 10}}, rotation = 0), iconTransformation(origin = {102.397, 0}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
equation
y = 1 + cos(sin(time));
annotation(Diagram(coordinateSystem(extent = {{-150, -90}, {150, 90}}, preserveAspectRatio = true, initialScale = 0.1, grid = {5, 5})), Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(visible = true, lineColor = {0, 114, 195}, fillColor = {255, 255, 255}, extent = {{-100, -100}, {100, 100}}, radius = 25), Text(visible = true, textColor = {64, 64, 64}, extent = {{-150, 110}, {150, 150}}, textString = "%name"), Text(visible = true, extent = {{-100, -40}, {100, 40}}, textString = "Item")}));
end Item;
block Generic
constant String genericUnit = "1" annotation(Dialog(group = "units"), choices(choice = "1" "dimensionless", choice = "s" "time", choice = "1/s" "rate"));
Modelica.Blocks.Interfaces.RealOutput y(unit = genericUnit) annotation(Placement(visible = true, transformation(origin = {155, 0}, extent = {{-10, -10}, {10, 10}}, rotation = 0), iconTransformation(origin = {103.333, 0}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
equation
y = 1 + sin(cos(sin(time)));
annotation(Diagram(coordinateSystem(extent = {{-150, -90}, {150, 90}}, preserveAspectRatio = true, initialScale = 0.1, grid = {5, 5})), Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(visible = true, lineColor = {0, 114, 195}, fillColor = {255, 255, 255}, fillPattern = FillPattern.Solid, extent = {{-100, -100}, {100, 100}}), Text(visible = true, textColor = {64, 64, 64}, extent = {{-150, 110}, {150, 150}}, textString = "%name")}));
end Generic;
block GenericWithX
constant String base = "1" annotation(Dialog(group = units));
constant String rate = "" annotation(Dialog(group = units), choices(choice = "" "not rate", choice = "/s" "rate"));
Modelica.Blocks.Interfaces.RealOutput y(unit = base + rate) annotation(Placement(visible = true, transformation(origin = {156.679, 0}, extent = {{-10, -10}, {10, 10}}, rotation = 0), iconTransformation(origin = {101.922, -2.301}, extent = {{-10, -10}, {10, 10}}, rotation = 0)));
equation
y = 1 + sin(sin(time));
annotation(Diagram(coordinateSystem(extent = {{-150, -90}, {150, 90}}, preserveAspectRatio = true, initialScale = 0.1, grid = {5, 5})), Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Rectangle(visible = true, lineColor = {0, 114, 195}, fillColor = {255, 255, 255}, fillPattern = FillPattern.Solid, extent = {{-100, -100}, {100, 100}}), Text(visible = true, textColor = {64, 64, 64}, extent = {{-150, 110}, {150, 150}}, textString = "%name"), Text(visible = true, origin = {1.009, 0.32}, extent = {{-101.009, -99.68}, {101.009, 99.68}}, textString = "X")}));
end GenericWithX;
annotation(Diagram(coordinateSystem(extent = {{-150, -90}, {150, 90}}, preserveAspectRatio = true, initialScale = 0.1, grid = {5, 5})), Icon(coordinateSystem(extent = {{-100, -100}, {100, 100}}, preserveAspectRatio = true, initialScale = 0.1, grid = {10, 10}), graphics = {Polygon(visible = true, origin = {0.248, 0.044}, lineColor = {56, 56, 56}, fillColor = {128, 202, 255}, fillPattern = FillPattern.Solid, points = {{99.752, 100}, {99.752, 59.956}, {99.752, -50}, {100, -100}, {49.752, -100}, {-19.752, -100.044}, {-100.248, -100}, {-100.248, -50}, {-90.248, 29.956}, {-90.248, 79.956}, {-40.248, 79.956}, {-20.138, 79.813}, {-0.248, 79.956}, {19.752, 99.956}, {39.752, 99.956}, {59.752, 99.956}}, smooth = Smooth.Bezier), Polygon(visible = true, origin = {0, -13.079}, lineColor = {192, 192, 192}, fillColor = {255, 255, 255}, pattern = LinePattern.None, fillPattern = FillPattern.HorizontalCylinder, points = {{100, -86.921}, {50, -86.921}, {-50, -86.921}, {-100, -86.921}, {-100, -36.921}, {-100, 53.079}, {-100, 103.079}, {-50, 103.079}, {0, 103.079}, {20, 83.079}, {50, 83.079}, {100, 83.079}, {100, 33.079}, {100, -36.921}}, smooth = Smooth.Bezier), Rectangle(visible = true, origin = {0, -5}, lineColor = {198, 198, 198}, fillColor = {238, 238, 238}, pattern = LinePattern.None, fillPattern = FillPattern.Solid, extent = {{-100, -25}, {100, 25}}), Polygon(visible = true, origin = {-0, -10.704}, lineColor = {113, 113, 113}, fillColor = {255, 255, 255}, points = {{100, -89.296}, {50, -89.296}, {-50, -89.296}, {-100, -89.296}, {-100, -39.296}, {-100, 50.704}, {-100, 100.704}, {-50, 100.704}, {0, 100.704}, {20, 80.704}, {50, 80.704}, {100, 80.704}, {100, 30.704}, {100, -39.296}}, smooth = Smooth.Bezier)}));
end UnitsAndRates;
Carl,
Actually, the choice in the GenericWithX case would be nested like this:
1. Time or not Time? (If Time then unit = "s" /* choice ends here */ else NestedChoice 2)
2. Rate or Not Rate? (In both cases determine base unit (e.g. replacement for "1"); If Rate then add "/s" to the base unit)
Something like this would be helpful.
I am hoping for some of the functionality mentioned by you and Otto being added soon and thus I will go for "seconds" in time and rates. ;-)
Note: That setting up an experiment (e.g. start time and stop time) for a simulation that goes from start time = 2010 [yr] to 2030 [yr] in seconds is PITA. One also has to be very disciplined in setting up TimeTables (e.g. start values with 0 or an actual date).
Guido
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard
Group Abstract Group Abstract
|
__label__pos
| 0.99864 |
REST即表述性状态传递(英文:Representational State Transfer,简称REST)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格。
表述性状态转移是一组架构约束条件和原则。满足这些约束条件和原则的应用程序或设计就是RESTful。需要注意的是,REST是设计风格而不是标准。REST通常基于使用HTTP,URI,和XML(标准通用标记语言下的一个子集)以及HTML(标准通用标记语言下的一个应用)这些现有的广泛流行的协议和标准。REST 通常使用 JSON 数据格式。
HTTP 方法
以下为 REST 基本架构的四个方法:
GET - 用于获取数据。
PUT - 用于更新或添加数据。
DELETE - 用于删除数据。
POST - 用于添加数据。
RESTful Web Services
Web service是一个平台独立的,低耦合的,自包含的、基于可编程的web的应用程序,可使用开放的XML(标准通用标记语言下的一个子集)标准来描述、发布、发现、协调和配置这些应用程序,用于开发分布式的互操作的应用程序。
基于 REST 架构的 Web Services 即是 RESTful。
由于轻量级以及通过 HTTP 直接传输数据的特性,Web 服务的 RESTful 方法已经成为最常见的替代方法。可以使用各种语言(比如 Java 程序、Perl、Ruby、Python、PHP 和 Javascript[包括 Ajax])实现客户端。
RESTful Web 服务通常可以通过自动客户端或代表用户的应用程序访问。但是,这种服务的简便性让用户能够与之直接交互,使用它们的 Web 浏览器构建一个 GET URL 并读取返回的内容。
更多介绍,可以查看:RESTful 架构详解
创建 RESTful
首先,创建一个 json 数据资源文件 users.json,内容如下:
{
"user1" : {
"name" : "mahesh",
"password" : "password1",
"profession" : "teacher",
"id": 1
},
"user2" : {
"name" : "suresh",
"password" : "password2",
"profession" : "librarian",
"id": 2
},
"user3" : {
"name" : "ramesh",
"password" : "password3",
"profession" : "clerk",
"id": 3
}
}
基于以上数据,我们创建以下 RESTful API:
序号 URI HTTP 方法 发送内容 结果
1 listUsers GET 空 显示所有用户列表
2 addUser POST JSON 字符串 添加新用户
3 deleteUser DELETE JSON 字符串 删除用户
4 :id GET 空 显示用户详细信息
获取用户列表:
以下代码,我们创建了 RESTful API listUsers,用于读取用户的信息列表, server.js 文件代码如下所示:
var express = require('express');
var app = express();
var fs = require("fs");
app.get('/listUsers', function (req, res) {
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
console.log( data );
res.end( data );
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("应用实例,访问地址为 http://%s:%s", host, port)
})
接下来执行以下命令:
$ node server.js
应用实例,访问地址为 http://0.0.0.0:8081
在浏览器中访问 http://127.0.0.1:8081/listUsers,结果如下所示:
{
"user1" : {
"name" : "mahesh",
"password" : "password1",
"profession" : "teacher",
"id": 1
},
"user2" : {
"name" : "suresh",
"password" : "password2",
"profession" : "librarian",
"id": 2
},
"user3" : {
"name" : "ramesh",
"password" : "password3",
"profession" : "clerk",
"id": 3
}
}
|
__label__pos
| 0.946385 |
Unity实现全屏截图以及QQ截图
本文实例为大家分享了Unity实现全屏截图、Unity实现QQ截图,供大家参考,具体内容如下
全屏截图:要实现的是点击鼠标左键,就实现截图,并且将所截图片保存到本地Assets目录下的StreamingAssets文件夹下面。
代码如下:
using UnityEngine;
using System.Collections;
public class TakeScreenShot : MonoBehaviour {
void Update () {
//点击鼠标左键
if (Input.GetMouseButtonDown (0)) {
//开启协程方法
StartCoroutine (MyCaptureScreen ());
}
}
//我的截屏方法
IEnumerator MyCaptureScreen(){
//等待所有的摄像机和GUI被渲染完成。
yield return new WaitForEndOfFrame ();
//创建一个空纹理(图片大小为屏幕的宽高)
Texture2D tex = new Texture2D (Screen.width,Screen.height);
//只能在帧渲染完毕之后调用(从屏幕左下角开始绘制,绘制大小为屏幕的宽高,宽高的偏移量都为0)
tex.ReadPixels (new Rect (0,0,Screen.width,Screen.height),0,0);
//图片应用(此时图片已经绘制完成)
tex.Apply ();
//将图片装换成jpg的二进制格式,保存在byte数组中(计算机是以二进制的方式存储数据)
byte[] result = tex.EncodeToJPG ();
//文件保存,创建一个新文件,在其中写入指定的字节数组(要写入的文件的路径,要写入文件的字节。)
System.IO.File.WriteAllBytes (Application.streamingAssetsPath+"/1.JPG",result);
}
}
之后思考一下,如何像qq截图那样,绘制一个截屏的矩形框只截取自己想要的部分呢?
using UnityEngine;
using System.Collections;
using System.IO;//引入IO流
public class NewBehaviourScript : MonoBehaviour {
//定义一个存储截屏图片的路径
string filePath;
void Start () {
//图片存储在StreamingAssets文件夹内。
filePath = Application.streamingAssetsPath + "/1.png";
}
Rect rect;
//截屏开始的位置
Vector3 s_pos;
//截屏结束的位置
Vector3 e_pos;
//是否绘制
bool isDraw;
void Update()
{
//按下鼠标左键时,记录当前鼠标的位置为开始截屏时的位置
if(Input.GetMouseButtonDown(0))
{
s_pos = Input.mousePosition;
}
//鼠标处于按下状态时
if(Input.GetMouseButton(0))
{
e_pos = Input.mousePosition;
//可以开始绘制
isDraw = true;
}
//抬起鼠标左键时,记录当前鼠标的位置为结束截屏时的位置
if(Input.GetMouseButtonUp(0))
{
//结束绘制
isDraw = false;
e_pos = Input.mousePosition;
//获取到截屏框起始点的位置,和宽高。
rect = new Rect(Mathf.Min(s_pos.x,e_pos.x),Mathf.Min(s_pos.y,e_pos.y),Mathf.Abs(s_pos.x-e_pos.x),Mathf.Abs(s_pos.y - e_pos.y));
//开启绘制的协程方法
StartCoroutine(Capsture(filePath, rect));
}
}
IEnumerator Capsture(string filePath, Rect rect)
{
yield return new WaitForEndOfFrame();
//创建纹理(纹理贴图的大小和截屏的大小相同)
Texture2D tex = new Texture2D((int)rect.width, (int)rect.height);
//读取像素点
tex.ReadPixels(rect, 0, 0) ;
//将像素点应用到纹理上,绘制图片
tex.Apply();
//将图片装换成jpg的二进制格式,保存在byte数组中(计算机是以二进制的方式存储数据)
byte[] result =tex.EncodeToPNG();
//文件夹(如果StreamAssets文件夹不存在,在Assets文件下创建该文件夹)
if(!Directory.Exists(Application.streamingAssetsPath))
Directory.CreateDirectory(Application.streamingAssetsPath);
//将截屏图片存储到本地
File.WriteAllBytes(filePath, result);
}
//在这里要用GL实现绘制截屏的矩形框
//1.GL的回调函数
//2.定义一个材质Material
public Material lineMaterial;
void OnPostRender() {
if(!isDraw) return;
print (s_pos);
Vector3 sPos = Camera.main.ScreenToWorldPoint(s_pos + new Vector3(0, 0, 10));
Vector3 ePos = Camera.main.ScreenToWorldPoint(e_pos + new Vector3(0, 0, 10));
print(string.Format("GL.....{0}, {1}", sPos, ePos));
// Set your materials Done
GL.PushMatrix();
// yourMaterial.SetPass( );
lineMaterial.SetPass(0);//告诉GL使用该材质绘制
// Draw your stuff
//始终在最前面绘制
GL.invertCulling = true;
GL.Begin(GL.LINES);//开始绘制
//GL.Vertex(sPos);
//GL.Vertex(ePos);
//如果想要绘制,矩形,将下面代码启动
GL.Vertex(sPos);
GL.Vertex(new Vector3(ePos.x, sPos.y, 0));
GL.Vertex(new Vector3(ePos.x, sPos.y, 0));
GL.Vertex(ePos);
GL.Vertex(ePos);
GL.Vertex(new Vector3(sPos.x, ePos.y, 0));
GL.Vertex(new Vector3(sPos.x, ePos.y, 0));
GL.Vertex(sPos);
GL.End();//结束绘制
GL.PopMatrix();
}
}
在脚本组件中拖入材质球
此图片黑色的矩形框就是通过GL绘制出来的(通过记录点的位置来依次绘制出线)
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
时间: 2020-04-14
unity实现QQ截图功能
本文实例为大家分享了unity实现QQ截图功能的具体代码,供大家参考,具体内容如下 效果: 代码如下: using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using UnityEngine; using NPinyin; using System.IO; public class NewBehaviourScript : MonoBehaviour {
Unity实现截图功能
本文实例为大家分享了Unity实现截图功能的具体代码,供大家参考,具体内容如下 一.使用Unity自带API using UnityEngine; using UnityEngine.UI; public class ScreenShotTest : MonoBehaviour { public RawImage img; private void Update() { //使用ScreenCapture.CaptureScreenshot if (Input.GetKeyDown(KeyCod
Unity实现截屏以及根据相机画面截图
在游戏开发和软件开发中,经常需要截图的功能,分带UI的截图和不带UI的截图功能.代码如下: using System.Collections; using System.Collections.Generic; using UnityEngine; public static class ScreenShotForCamera{ public static void CaptureScreen(string _path = null) { if (_path == null) _path = "
unity实现按住鼠标选取区域截图
本文实例为大家分享了unity按住鼠标选取区域截图的具体代码,供大家参考,具体内容如下 private int capBeginX; private int capBeginY; private int capFinishX; private int capFinishY; public Image showImg; // Use this for initialization void Start () { } // Update is called once per frame void U
Unity实现相机截图功能
最近做项目的时候需要在游戏里截一张高清截图,研究了一下写成脚本,方便以后使用. 脚本可以自定义分辨率,用相机截高清截图.可以用代码动态截图,也可以在编辑模式下截图. 注意截图宽高比要正确,宽高比不正确时可能会出问题. 截图效果: 脚本: CameraCapture.cs using UnityEngine; using System.IO; /// <summary> /// 相机截图 /// <para>ZhangYu 2018-07-06</para> /// &l
JavaScript实现网页截图功能
使用JavaScript截图,这里我要推荐两款开源组件:一个是Canvas2Image,它可以将Canvas绘图编程PNG/JPEG/BMP的图像:但是光有它还不够,我们需要给任意DOM(至少是绝大部分)截图,这就需要html2canvas,它可以将DOM对象转换成一个canvas对象.两者的功能结合起来,就可以把页面上的DOM截图成PNG或者JPEG图像了,很酷. Canvas2Image 它的原理是利用了HTML5的canvas对象提供了toDataURL()的API: 复制代码 代码如下:
Java模拟QQ桌面截图功能实现方法
本文实例讲述了Java模拟QQ桌面截图功能实现方法.分享给大家供大家参考.具体如下: QQ的桌面截图功能非常方便,去年曾用Java模拟过一个,现整理出来. 本方法首先需要抓到屏幕的整个图象,将图象显示在一个JFrame中,再将JFrame全屏显示,这样就模拟出了一个桌面,Java也就可以获得鼠标的作用区域从而实现桌面中的小范围截屏. import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import
使用微信PC端的截图dll库实现微信截图功能
本文实例为大家分享了截图dll库实现微信截图功能 ,供大家参考,具体内容如下 ScreenForm.cs代码: using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows.Forms; namespace screenT { public partial class ScreenForm : Form { public ScreenForm()
C#实现的滚动网页截图功能示例
本文实例讲述了C#实现的滚动网页截图功能.分享给大家供大家参考,具体如下: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplic
javascript实现粘贴qq截图功能(clipboardData)
这篇文章主要介绍了在网页中实现读取剪贴板粘贴截图功能,即可以把剪贴板的截图Ctrl+V粘贴到网页的一个输入框中,例如QQ截图.旺旺截图或者其它截图软件.具体代码如下. <!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>利用 clipboardData 在网页中实现截屏粘贴的功能</title> <
Android实现拍照截图功能
本文将向大家展示如何拍照截图. 先看看效果图: 拍照截图有点儿特殊,要知道,现在的Android智能手机的摄像头都是几百万的像素,拍出来的图片都是非常大的.因此,我们不能像对待相册截图一样使用Bitmap小图,无论大图小图都统一使用Uri进行操作. 一.首先准备好需要使用到的Uri: private static final String IMAGE_FILE_LOCATION = "file:///sdcard/temp.jpg";//temp file Uri imageUri =
Selenium Webdriver实现截图功能的示例
前几天在研究中自动化的时候突发奇想,想着能不能来截个图,以便之后查看,实现的方法其实也不难,毕竟selenium webdriver已经提供了截图额功能,TakesScreenshot接口函数(英文意思就是获取屏幕截图takes-screenshot). 废话不多说了,直接上代码 package com.wch; import java.io.File; import java.io.IOException; import org.junit.After; import org.junit.Be
|
__label__pos
| 0.861277 |
x
Search in
Sort by:
Question Status:
Search help
• Simple searches use one or more words. Separate the words with spaces (cat dog) to search cat,dog or both. Separate the words with plus signs (cat +dog) to search for items that may contain cat but must contain dog.
• You can further refine your search on the search results page, where you can search by keywords, author, topic. These can be combined with each other. Examples
• cat dog --matches anything with cat,dog or both
• cat +dog --searches for cat +dog where dog is a mandatory term
• cat -dog -- searches for cat excluding any result containing dog
• [cats] —will restrict your search to results with topic named "cats"
• [cats] [dogs] —will restrict your search to results with both topics, "cats", and "dogs"
Steam Internet Session vs. Lobby Session
I was hoping someone could enlighten me on the different session types for Steam subsystem (expanding into how other online subsystems use these would also be bonus)
1. When changing the bIsPresence flag the Steam subsystem will either create an internet session or a lobby session. What is the difference and when should I use one or the other?
2. When setting the session name to either GameSession or PartySession, what is this doing? It seems like the same thing bIsPresence is doing.
3. When using different session names (GameSession and PartySession) it appears I can create both a party session and a game session at the same time with Steam, but I do not think this is the case. Example: If I create a GameSession, and then try to create another GameSession it fails because it already exists, but if I game a GameSession, then a PartySession, then ANOTHER GameSession it succeeds. Does this mean the original GameSession is destroyed automatically?
Product Version: UE 4.15
Tags:
more ▼
asked Mar 27 '17 at 05:19 PM in C++ Programming
avatar image
S0rn0
71 7 13 12
avatar image kcmonkey Jul 17 '17 at 04:38 PM
I'm also interested in this question. Hopefully there will be a answer sooner.
(comments are locked)
10|2000 characters needed characters left
0 answers: sort voted first
Be the first one to answer this question
toggle preview:
Up to 5 attachments (including images) can be used with a maximum of 5.2 MB each and 5.2 MB total.
Follow this question
Once you sign in you will be able to subscribe for any updates here
Answers to this question
|
__label__pos
| 0.909018 |
Determining if Equations are Functions
Sick of ads? Sign up for MathVids Premium
Taught by mrbrianmclogan
• Currently 5.0/5 Stars.
6768 views | 1 rating
Part of video series
Meets NCTM Standards:
Lesson Summary:
This lesson teaches how to determine if an equation represents a function relationship. The criteria to be met includes everything in 'x' being mapped to a 'y', and the 'x' values should have a unique corresponding 'y' value. The first step is to isolate 'y' by solving for it, then taking the square root. The square root can result in 2 possible values for 'y,' which means that the input now has multiple possible values, making it not a function relationship between 'y' and 'x.'
Lesson Description:
Determine if the equation represents a function
I show how to solve math problems online during live instruction in class. This is my way of providing free tutoring for the students in my class and for students anywhere in the world. Every video is a short clip that shows exactly how to solve math problems step by step. The problems are done in real time and in front of a regular classroom. These videos are intended to help you learn how to solve math problems, review how to solve a math problems, study for a test, or finish your homework. I post all of my videos on YouTube, but if you are looking for other ways to interact with me and my videos you can follow me on the following pages through My Blog, Twitter, or Facebook.
Questions answered by this video:
• How can I tell if an equation is a function or not?
• Staff Review
• Currently 5.0/5 Stars.
This video shows an example of one equation. The instructor demonstrates why the equation does not represent a function.
|
__label__pos
| 0.895146 |
How do I read a jpeg image from a folder on a server
Discussion in 'ASP .Net Web Services' started by Lucas Cowald, Oct 11, 2003.
1. Lucas Cowald
Lucas Cowald Guest
Hi,
How do I read a jpeg image from a folder on a server, and give it to a user
as a file that his browser would download it (stream it) directly without
sending any HTML tags.
Here is exactly why I need it:
1) User goes to a page image.asp
2) image.asp would connect to a database and check, if this user has already
downloaded the image before.
3) If the user has never downloaded the image, he will be able to
downloaded, If user has already downloaded the image before, a text will
show on his browser that he can't get it the second time.
What is the best way to acomplish this. Can you show a sample code in
VBscript/ASP?
Thank you in advance for your help.
Lucas Cowald, Oct 11, 2003
#1
1. Advertising
Want to reply to this thread or ask your own question?
It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
1. Speed
Replies:
12
Views:
1,155
2. Speed
Replies:
10
Views:
1,253
Kelsey Bjarnason
Jul 30, 2007
3. lovaspillando
Replies:
0
Views:
1,084
lovaspillando
Aug 26, 2007
4. Ivan Alameda Carballo
Replies:
0
Views:
522
Ivan Alameda Carballo
Aug 26, 2007
5. Lucas Cowald
How do I read a jpeg image from a folder on a server
Lucas Cowald, Oct 11, 2003, in forum: ASP .Net Web Controls
Replies:
2
Views:
195
Lucas Cowald
Oct 15, 2003
Loading...
Share This Page
|
__label__pos
| 0.958826 |
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.
Sign up
Here's how it works:
1. Anybody can ask a question
2. Anybody can answer
3. The best answers are voted up and rise to the top
In my few years of using Linux from using Windows for so long, there have been many new concepts for me to grasp. One of the more obvious seeming mysteries to me is how the mouse is configured in Linux. As a life-long Windows gamer, I've always seen mouse acceleration as my nemesis, as I would expect many gamers.
I can remember being baffled when I first started (using Fedora 9) and finding that I had no mouse acceleration when the acceleration level was in the middle, not when it was turned right down. From then until Fedora 14 it was all dandy set like that, but when I recently moved to Fedora 17, these settings don't feel right.
The only time I don't have acceleration is when the acceleration is turned right down, except then the mouse is very insensitive and the sensitivity level makes no difference at all.
I read recently about a command called xset which lets you have control over the actual values of the variables 'acceleration' and 'threshold' (the number of 'dots' travelled at which point the cursor should accelerate), and someone suggested that perhaps the way to have no acceleration is to set threshold to 1 and use the acceleration value as the sensitivity. However, this doesn't work, even with the threshold set to 1. I can still clearly detect acceleration.
I know I'm using vague words, but you'll have to take my word for it when I say it "feels" like it has acceleration, no matter what I set it to. Even now, as I'm clicking in this text box to correct typos, I'm not hitting the right spot as I would do on Windows with my normal mouse motion because of it.
I should mention that I don't use a fancy mouse or anything; it's just a Microsoft IntelliMouse Optical that you might find in an office (yes, not the favourite mouse for gamers). Have I missed something obvious, or is it really a complicated thing to change?
EDIT: this post:
(Some settings to remove mouse acceleration.) ... So now we have no acceleration, but is that what we want? The mouse is a bit slow now. Sadly that's how it is. With acceleration disabled you get a 1:1 relationship between the mouse and the display. You move the mouse left one dot and the mouse pointer moves one pixel left. If there were a way to multiply the input movement (say by 2) then every other pixel on each axis would be inacessible to the mouse. That would make accurate positioning of the mouse pretty difficult. The 'sensitivity' setting in some GUI mouse control panels actually does the opposite of what you would expect - the most sensitive is a 1:1 ratio - it's the acceleration which makes it seem so much faster.
I find this a bit hard to believe, or at least that sensitivity does move a number of dots on screen per dot moved by the mouse.
share|improve this question
Fedora 22 continues this tradition by taking a perfectly good system and changing mouse settings yet again, now I need four mousepads taped side by side to move my cursor to the right side of the screen. When I discuss those bugs and missing required features, people act like I'm crazy. My guess that the directive is that if the user can't write their own device driver and program the physical hardware and drivers, then those users are actively discouraged from using Linux. At this rate, Fedora 28 mouse won't be configurable. xkcd.com/528 – Eric Leschinski Sep 20 '15 at 14:07
It is a complicated thing, taking into account the time domain, the infinite possibilities for an acceleration (or velocity) curve, framerate- or delay-independent behavior, etc.
Matching behavior with closed-source OS'es or drivers is nigh-impossible, but X.org provides you with ample choices for your taste, provided you take the time to read the documentation or the source.
Non-accelerated behavior (flat acceleration curve, linear velocity curve, linear mouse response or N pixels per 1mm of movement) is the only truly universal, easy-to-adapt and easy-to-adopt behavior. Ironically, it's also what most systems lack or make very hard to get. (See this open question, for example.)
Assuming you want linear response, I'll direct you back at the question you've linked.
share|improve this answer
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.525251 |
Name proof from Next Obligation
Is it possible to name the proofs written under a Next Obligation?
E.g something like
Next Obligation as foo_proof
(* ... *)
Qed.
Print foo_proof.
As far as I know, this is not possible. The proofs are automatically named though: in Equations, the scheme is “foo_obligations_obligation_i” (where foo is the name of the function, and i is the number of the obligation, and in Program it is simply “foo_obligation_i”.
But maybe if you tell us what you want to do with this named proof, we can find another way to achieve it?
|
__label__pos
| 0.921384 |
To create a new app password for an app or device, take the following steps. You can repeat these steps to create an app password for as many apps or devices as you need.
1. Go to the Security basics page and sign in to your Microsoft account.
2. Select more security options.
3. Under App passwords, select Create a new app password. A new app password is generated and appears on your screen. Enter this app password where you would enter your normal password in Outlook. Be sure to copy the password as once you close the window you will not be able to see it again unless you generate a new code.
|
__label__pos
| 0.98762 |
Giải phương trình lượng giác bậc hai theo một hàm số lượng giác 5cosx – 2sinx/2 +7=0 cos5xcosx= cos4x.cos2x+3cos^2x +1
Giải phương trình lượng giác bậc hai theo một hàm số lượng giác
5cosx – 2sinx/2 +7=0
cos5xcosx= cos4x.cos2x+3cos^2x +1
Share
1 Answer
1. Đáp án:
Giải thích các bước giải:
a)
$\begin{array}{l}
5\cos x – 2\sin \frac{x}{2} + 7 = 0\\
\Leftrightarrow 5(1 – 2{\sin ^2}\frac{x}{2}) – 2\sin \frac{x}{2} + 7 = 0\\
\Leftrightarrow – 10{\sin ^2}\frac{x}{2} – 2\sin \frac{x}{2} + 12 = 0\\
\Leftrightarrow \left[ \begin{array}{l}
\sin \frac{x}{2} = 1\\
\sin \frac{x}{2} = – \frac{6}{5}\left( {loai} \right)
\end{array} \right. \Rightarrow x = \pi + k4\pi
\end{array}$
b)
$\begin{array}{l}
\cos 5x\cos x = \cos 4x\cos 2x + 3co{s^2}2x + 1\\
\Leftrightarrow \frac{1}{2}\left( {\cos 6x + \cos 4x} \right) = \frac{1}{2}\left( {\cos 6x + \cos 2x} \right) + 3{\cos ^2}2x + 1\\
\Leftrightarrow \cos 4x – \cos 2x = 6{\cos ^2}2x + 2\\
\Leftrightarrow 2{\cos ^2}2x + 1 – \cos 2x = 6{\cos ^2}2x + 2\\
\Leftrightarrow 4{\cos ^2}2x + \cos 2x + 1 = 0\\
pt\,vo\,\,nghiem
\end{array}$
• 0
Leave an answer
Leave an answer
Browse
|
__label__pos
| 1 |
72,474 questions
70,130 answers
932 comments
47,599 users
MathHomeworkAnswers.org is a free math help site for student, teachers and math enthusiasts. Ask and answer math questions in algebra I, algebra II, geometry, trigonometry, calculus, statistics, word problems and more. Register for free and earn points for questions, answers and posts. Math help is always 100% free.
Note: This site is intended to help students and non-students understand and practice math. we do not condone cheating. Users attempting to abuse the system will be permanently blocked from further use.
Most popular tags
algebra problems solving equations word problems calculating percentages geometry problems calculus problems fraction problems trigonometry problems simplifying expressions rounding numbers math problem solve for x order of operations pre algebra problems evaluate the expression algebra slope intercept form probability factoring please answer this queastion as soon as possible. thank you :) please help me to answer this step by step. polynomials plz. give this answer as soon as possible statistics problems solving inequalities how to find y intercept algebra 2 problems equation of a line logarithmic equations solving systems of equations by substitution help sequences and series word problem dividing fractions greatest common factor graphing linear equations geometric shapes square roots substitution method 6th grade math long division least common multiple factoring polynomials solving systems of equations http: mathhomeworkanswers.org ask# solving equations with fractions standard form of an equation function of x least to greatest ratio and proportion dividing decimals proving trigonometric identities algebra problem trig identity solving equations with variables on both sides help me!! precalculus problems ( slope of a line through 2 points help me solving systems of equations by elimination domain of a function algebraic expressions college algebra trinomial factoring distributive property i need help with this factors of a number solving quadratic equations perimeter of a rectangle slope of a line division greater than or less than 8th grade math fraction word problems exponents limit of a function differentiation equivalent fractions differential equation how to find x intercept algebra 1 hw help asap elimination method geometry 10th grade simplifying fractions area of a triangle inverse function . 7th grade math geometry area of a circle simplify integral place value parallel lines standard deviation solving triangles fractions circumference of a circle percentages solving linear equations width of a rectangle systems of equations containing three variables mixed numbers to improper fractions scientific notation problems number of sides of a polygon zeros of a function algebra word problems lowest common denominator prime factorization solving systems of equations by graphing area of a rectangle diameter of a circle 5th grade math story problems quadratic functions dividing polynomials length of a rectangle mathematical proofs derivative of a function homework vertex of a parabola calculus algebra 1 converting fractions to decimals evaluating functions integers equation finding the nth term perpendicular lines range of a function ordered pairs combining like terms least common denominator calculators greatest to least algebra 2 unit conversion solve for y radius of a circle complex numbers what is the answers? ) solving radical equations slope area word problems functions calculus problem because i don't understand multiplying fractions 4th grade math calculate distance between two points statistics common denominator ratios geometry word problems set builder notation binomial expansion absolute value math homework simplifying radicals help me please and show how to work it out percents #math round to the nearest tenth midpoint of a line significant figures product of two consecutive numbers equation of a tangent line radicals math show work () median solve show every step to solve this problem adding fractions graphing please answer this question as soon as possible. thank you :) divisibility rules graphing functions pre-algebra problems roots of polynomials factor by grouping 1 - improper fractions to mixed numbers percentage number patterns place values (explain this to me) subtracting fractions ? volume of a cylinder decimals expanded forms rational irrational numbers how to complete the square simultaneous equations numbers derivatives solving equations with variables = maths http: mathhomeworkanswers.org ask?cat=# need help please help comparing decimals multiplying polynomials sets http: mathhomeworkanswers.org ask# solving quadratic equations by completing the square implicit differentiation integration divide mixed numbers surface area of a prism average rate of change algebra1 pemdas angles age problem rounding decimals solving trigonometric equations surface area of a cube logarithms trigonometry #help perimeter of a triangle 9th grade math matrices dividing compound interest geometry problem rounding to the nearest cent reducing frations to lowest terms arithmetic sequences direct variation factor how do you solve this problem in distributive property probability of an event simplifying trigonometric equation using identities chemistry none mean lcm measurement answer solve algebra equation
when a number is decreased by 30% of itself, the result is 28
when a number is decreased by 30% of itself, the result is 28
asked Mar 27, 2013 in Algebra 1 Answers by andrell ford (120 points)
Your answer
Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
2 Answers
let the no is x . so by cond, x - (30% off x)= 28 => x - (30*x / 100 )= 28 => x - (30x /100)= 28 => x - 3x /10=28 => (110x - 3x)=28 => 7x = 28 => x = 28/7=4
answered Jul 15, 2013 by tapan kumar adak (220 points)
let nub be x
then decrease value 100-30=70
hence.. 70x/100 =28
x = 28 *100/70
x = 40
answered Feb 2 by farha
Related questions
1 answer 164 views
...
|
__label__pos
| 0.984752 |
跳到主要內容
Dictionary And Proxy
今天來介紹二個 AS3 新增的二個類別(AS2沒有這東西喔)
Dictionary
簡單來說跟 Object 和 Array 是做一樣的事。
是用來索引物件用的類別。
Array是用數字來當做 Key 值。
_array[0] = "字串1";
_array[1] = "字串2";
_array[0] = "字串3";
時, 本來的值就會被取代掉
trace(_array[0]) //得到 字串3
Object是使用String來當作 Key 值
_obj['key'] = "String1";
_obj['key2'] = "String2";
(或寫成_obj.key2 = "String2";)
_obj['key2'] = "String3";
本來的值也會被取
trace(_obj['key2']) //得到 String3
Dictionary
是把'物件', 當作索引值,
每個物件都是獨立單一的, 這樣就可以確保索引值是唯一的。
var _dic :Dictionary = new Dictionary();
var _mc:MovieClip = new MovieClip();
var _mc2:MovieClip = new MovieClip();
//建立二個MovieClip
_dic[_mc] = "Dictionary Value1";
_dic[_mc2] = "Dictionary Value2";
用for in 掃一下內容。
for (var d:* in _dic) {
trace(d, _dic[d])
}
// [object MovieClip] Dictionary Value1
// [object MovieClip] Dictionary Value2
就可以得到當初寫入的值了
, 記得, 不要時一定要delete掉, 否則物件的指派還在
就不會被記憶體回被器回收喔。
完整程式碼:
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.utils.Dictionary;
public class DictionaryDemo extends Sprite {
private var _obj :Object = { };
private var _dic :Dictionary = new Dictionary();
public function DictionaryDemo() {
//_obj[Key] = Value
//但 Object 的 Key 必需是字串
//所以有可能會發生 Key 值已經用掉的問題
var _mc:MovieClip = new MovieClip();
_obj[_mc] = "數值1";
//這樣寫就等於 _obj[_mc.toString()] = 值。
var _mc2:MovieClip = new MovieClip();
_obj[_mc2] = "數值2";
//使用 for in 來掃obj裡的變數
for (var a:String in _obj) {
trace(a, _obj[a]);
// [object MovieClip] 數值2
}
_dic[_mc] = "Dictionary Value1";
_dic[_mc2] = "Dictionary Value2";
for (var d:* in _dic) {
trace(d, _dic[d])
// [object MovieClip] Dictionary Value1
// [object MovieClip] Dictionary Value2
}
}
}
}
Proxy , 代理人
好比我們要載入一個xml
要先透過URLLoader載入
然後再用一個XML物件把載入後的結果存起來
有沒有辦法整合成一個呢, 這時 Proxy 就很好用了
理想
var _xxx:類別 = new 類別
_xxx.載入外部("xml");
_xxx.偵聽事件。
載入成功後。
直接用_xxx.xml裡的tag名稱, 直接就當成xml使用。
先準備一份要載入用的XML文件
撰寫XMLProxy.as類別,
因為 Flash 不充許多重繼成, 但可以透過 Interface 來做到類似的效果,
所以XMLProxy要先extneds Proxy類別, 同時實作IEventDispatcher
package {
import flash.utils.Proxy;
import flash.events.Event;
import flash.events.EventDispatcher;
import flash.events.IEventDispatcher;
import flash.net.URLLoader;
import flash.net.URLRequest;
import flash.utils.Proxy;
import flash.utils.flash_proxy;
[Event(name = "complete", type = "flash.events.Event")]
//加入這組 tag , 是要給 FlashDevelop 或是 Flex 在編程式碼時能有事件提示。
dynamic public class XMLProxy extends Proxy implements IEventDispatcher {
//extends Proxy 時, 一定要設定成 dunamic 類別
private var _eventDispatcher:EventDispatcher;
private var _urlLoader :URLLoader;
private var _xml :XML;
private var _isLoaded :Boolean;
public function XMLProxy(){
_eventDispatcher = new EventDispatcher();
_urlLoader = new URLLoader();
_urlLoader.addEventListener(Event.COMPLETE, xmlLoadedHandler);
}
private function xmlLoadedHandler(e:Event):void {
_xml = XML(_urlLoader.data);
_isLoaded = true;
dispatchEvent(new Event(Event.COMPLETE, true, true));
}
public function loadURL(url:String):void {
var urlRequest:URLRequest = new URLRequest(url);
_urlLoader.load(urlRequest);
}
flash_proxy override function getProperty(name:*):*{
var _name:String = String(name);
return _xml[_name];
}
//以下是因為 interface IEventDispatcher, 所以要實作一樣的 function 名稱。
public function addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, weakRef:Boolean = false):void {
_eventDispatcher.addEventListener(type, listener, useCapture, priority, weakRef);
}
public function dispatchEvent(event:Event):Boolean {
return _eventDispatcher.dispatchEvent(event);
}
public function hasEventListener(type:String):Boolean {
return _eventDispatcher.hasEventListener(type);
}
public function removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void {
_eventDispatcher.removeEventListener(type, listener, useCapture);
}
public function willTrigger(type:String):Boolean {
return _eventDispatcher.willTrigger(type)
}
public function get isLoaded():Boolean { return _isLoaded; }
}
}
完後成, 測試吧。
package {
import flash.display.Sprite;
import flash.events.Event;
public class XMLProxyDemo extends Sprite{
private var _xmlProxy:XMLProxy = new XMLProxy();
//建構 XMLProxy 類別
public function XMLProxyDemo() {
_xmlProxy.addEventListener(Event.COMPLETE , _xmlCompleteHandler);
//偵聽事件, 因為實作了 IEventDispatcher , 所以也可以發送和偵聽。
_xmlProxy.loadURL("xml_data.xml");
//載入 xml。
}
private function _xmlCompleteHandler(e:Event):void {
//載入完成後, 當去使用_xmlProxy物件的屬性時,
//如果是 _xmlProxy 本身有定義的屬性, 就會去讀該屬性。
/* 而在 XMLProxy 裡定義的這行, 就是當屬性沒有定義時, 就去找指定的物件裡的屬性
* 方法也是可以這樣做。
* flash_proxy override function getProperty(name:*):*{
var _name:String = String(name);
return _xml[_name];
}*/
trace(_xmlProxy.isLoaded);
//.isLoaded 是定義好的屬性。
trace(_xmlProxy.item[0].img.@src);
//.item不是 _xmlProxy 裡一開始就定義好的屬性, 透過 Proxy 代理, 去找指定物件的屬性
//就好像真的是_xmlProxy物件的屬性一樣。
trace(_xmlProxy.item[1].label);
}
}
}
留言
耶書寫道…
>Dictionary
>是把'物件', 當作索引值,
>每個物件都是獨立單一的, 這樣就可以確保索引值是唯一的。
不太了解這句話,哈哈。
milkmidi寫道…
var _mc:MovieClip = new MovieClip();
使用Object
_obj[_mc] = "值"。
//這樣是把_mc.toString()當成Key
//所以有可能會被蓋掉
_dic[_mc] = "值"。
是把物件本身當作Key值,
列夫 LINLI寫道…
老師請問一下,dispaychEvent(new Event(客製事件,ture,ture),這個客製事件業可以始用Event的公用常數?
你在XMLProxy這個範例的xmlLoadedHandler()函式,發出的事件EVENT.COMPLETE
請問用公用常數,作客製事件有什麼要小心的
milkmidi寫道…
dispaychEvent(new Event(客製事件,ture,ture)
此時的客製事件,只是一個字串
但就有可能會發生打錯字的問題
比較好的做方法自己寫一個類別來extends Event
同時定義const 的 static 字串
這個網誌中的熱門文章
超好用的無限免費網頁空間,無廣告,無流量限制
大家好,我是奶綠茶
今天來教大家如何申請一個無限免費速度又快的網頁空間
1 首先到 https://github.com/ 申請帳號(一直下一步,下一步,下一步)
2 到你的個人頁,切換上方的 tab 到 Repositories, 按下右鍵的 new
3 Repository name
一定要是這樣的格式 username.github.io
我的 github 網址是 github.com/milkmidi
那就要輸入 milkmidi.github.io
選擇 public, 這樣別人才看的到
private 有其他用途, 而且要付費才能使用
完成後按下 Create repository
5 安裝 SourceTree
github 並不支援 FTP 或是網頁上傳,一定要透過指令碼
在這我們選用有圖型介面的軟體,方便大家學習
https://www.sourcetreeapp.com/
下載並安裝
啟動後登入你的 github 帳號
6 clone 你的 github io 專案
右上角有個 Clone or download 點選後
複製 https 連結(不要選到 ssh )
7 將 https 的連結貼到 SourceTree
8 上傳 html
到本機 github.io 資料夾,放一個 index.html
切換到 SourceTree, 這時會看到 Unstaged files 的欄位
選擇 Stage All
9 git 要求每次的 Commit, 都一定要打說明文字(好習慣)
輸入完成後,按下右邊的 Commit
10 發佈(Push),這樣就完成啦
可以到你的 http://milkmidi.github.io/ 去查看檔案有沒有出來
其他
Commit 可以想像是做一個記錄,你可以很多的 Commit
最後再一次 Push 上去
github 原本是給程式設計師用的版本控管服務
免費版提供無限空間讓你放檔案,但一定要是 public
想要有私有的 Project ,就只能付費
github.io 只能放靜態檔案,php, aspx 服務並不支援。
祝大家學習愉快
轉載請註明出處
奶綠的 github.io Source Code
webpack2 入門實戰 1
大家好,我是奶綠茶
前端戰場不再只是寫寫 js / css , 各種框架、前處理工具百花齊放
身為前端工程師,不只要把程式寫完,還要寫好
老師說:選對好工具,事情就完成一半
如果你還在一隻 JS 打完全部程式,一隻 css 寫所有的 style
每次存檔還在手動 reload 網頁, 圖片壓 K 壓到不要不要的
透過奶綠伯的系列教學,讓你了解 webpack2 帶來的優勢
學會 webpack 可能不會加薪,但至少可以準時下班(誤)
1. 安裝 nodejs
請參考 gulp 安裝編
2. 安裝 global webpack , 筆者使用的是 2.2.1 版本
npm i [email protected] -g
3. 在專案的根目錄放一隻 webpack.config.js
entry:你的主 js 進入點
output.filename:webpack 打包後的檔名
output.path:webpack 打包後的路徑
var path = require('path'); module.exports = { entry: './src/app.js', output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist') } };
4. require , module.exports
現在前端都 module 化
可以每個獨立的功能都寫成單一的 js module
除了好管理,也方便讓團隊使用
寫一隻 module_exports_util.js
每隻經過 webpack 打包的 js , 都會是獨立的檔案
所以變數都是私有的, 外部成員都無法得到
在這個 module 裡,我們想開放二個函式
add , getName
所以在最後的 module.exports 指定
筆記加入 jsdoc , 為了方便在開發時,能夠有型別的提示
var name = "milkmidi"; /** * @param {number} num1 * @param {number} num2 * @return {number} */ function ad…
gulp 前端自動化 - spritesheet
大家好,我是奶綠茶
今天來介紹如何使用 gulp 來自動化將圖片拼成 spritesheet
奶綠我使用的套件是 gulp.spritesmith
https://www.npmjs.com/package/gulp.spritesmith
可以使用 handlebars 格式,拼出自己想要的 css 格式
{{#sprites}} .{{name}} { background-position: {{px.offset_x}} {{px.offset_y}}; width: {{px.width}}; height: {{px.height}}; background-image: url({{{escaped_image}}}); } {{/sprites}} gulp 的設定
gulp.task('sprite',()=>{ console.log('sprite'); const spriteData = gulp.src('src/sprite_src/*') .pipe(spritesmith({ imgName: '../img/sprite.png', cssName: '_sprite.css', padding: 4, imgOpts: { quality: 100 }, cssTemplate: 'src/css/handlebars/basic.handlebars', })); const imgStream = spriteData.img .pipe(buffer()) .pipe(gulp.dest('dist/img/')); const cssStream = spriteData.css .pipe(gulp.dest('src/css')); return merge(imgStream, cssStream); });…
|
__label__pos
| 0.878432 |
Class: Hyrax::Transactions::ApplyChangeSet
Inherits:
Transaction
• Object
show all
Defined in:
lib/hyrax/transactions/apply_change_set.rb
Overview
Applies and saves a `ChangeSet`.
This transaction is intended to ensure appropriate results for a Hyrax model when saving changes from a `ChangeSet`. For example: it will set the system-managed metadata like modified date.
If your application has custom system managed metadata, this is an appropriate place to inject that behavior.
This will also validate the `ChangeSet`. Which validations to use is delegated on the `ChangeSet` itself.
Examples:
Applying a ChangeSet to a Work
work = Hyrax::Work.new
change_set = Hyrax::ChangeSet.for(work)
change_set.title = ['Comet in Moominland']
transaction = Hyrax::Transactions::ApplyChangeSet.new
result = transaction.call(change_set) # => Success(#<Hyrax::Work ...>)
result.bind(&:persisted?) => true
persisted = result.value_or { raise 'oh no!' } # safe unwrap
persisted.title # => ['Comet in Moominland']
Since:
• 3.0.0
Constant Summary collapse
DEFAULT_STEPS =
Since:
• 3.0.0
['change_set.set_modified_date',
'change_set.set_uploaded_date_unless_present',
'change_set.validate',
'change_set.save'].freeze
Instance Attribute Summary
Attributes inherited from Transaction
#container, #steps
Instance Method Summary collapse
Methods inherited from Transaction
#call, #with_step_args
Constructor Details
#initialize(container: Container, steps: DEFAULT_STEPS) ⇒ ApplyChangeSet
Returns a new instance of ApplyChangeSet.
See Also:
Since:
• 3.0.0
42
43
44
# File 'lib/hyrax/transactions/apply_change_set.rb', line 42
def initialize(container: Container, steps: DEFAULT_STEPS)
super
end
|
__label__pos
| 0.935814 |
Libre EDA Project. LibrEDA aims to create a libre software framework for the physical design of silicon chips. This repository is a project management repository. It is used to keep track of general milestones etc. https://libreda.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Thomas Kramer 157be13ed4 Add logos of placer & router. 8 months ago
artwork Add logos of placer & router. 8 months ago
img README: Add NGI0 logo. 8 months ago
README.md Formatting. 8 months ago
README.md
LibrEDA - Physical Chip Design Framework
Abstract
The main goal of this project is to create a new libre software framework for the physical design of digital integrated circuits. The framework is meant to simplify the development of ASIC layout tools, i.e. the tools used to convert a gate-level netlist into a fabrication-ready layout. A special focus will be on modularity, reusability, documentation and maintainability. A user who is not familiar with the framework should be quickly able to learn how to use it and how to write extensions. For this the framework will provide fundamental data structures and algorithms, interface definitions of the design algorithms (e.g. placement, routing or timing analysis), input/output libraries for commonly used file formats (e.g. GDS2, OASIS, DEF) as well as documentation and example implementations for each abstract part. Two implementations will be pursued in parallel: One with a clear focus on simplicity and education and another with a focus on performance and scalability. The first will be written in Python, the second in a more performance-oriented language (for example Rust). At the same time the ‘LibreCell’ standard-cell generator and characterization tool will be developed further.
The framework
The ‘Physical Chip Design Framework’ can be roughly split into the following parts:
• Data structures that represent chip layouts, netlists and the combination of the two.
• Interface definitions of commonly used parts in a chip layout flow:
• Input/output for layouts & netlists
• Placement algorithms
• Routing algorithms
• Timing analysis with an eventual feedback loop to the routing algorithm
There are also parts that are not yet considered such as a pad-ring generator. This project persues two different approaches. One is a framework written in Python that can use existing data structures of Klayout (klayout.de). The Python framework is intended to be as simple as possible and not necessarily efficient or scalable. It should be suitable for teaching and tutorials. The second version should be written in a performance-oriented way (for example in Rust). This version also intents to be scalable for real-world designs. Obviously there are overlaps in the tasks. Where hard work of another task can be reused this is respected in the requested amount. Dependency or priority of tasks does has nothing to do with the order of appearance.
Acknowledgements
Supported by:
NLNet.nl
NGI0
|
__label__pos
| 0.88177 |
Thread: help with generating numbers
1. #1
Registered User
Join Date
Jan 2003
Posts
115
help with generating numbers
Hi guys,
Im trying to implement a function/program that generates numbers from 1 to the input number given by the user. I've come close to generating all the numbers however there are some duplicates of the numbers still remain.
I just want to generate the number with no duplicates but my algorithm must be wrong, can anyone see anything wrong with what ive done?
Cheers.
Code:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define MAXSIZE 1000
int main()
{
int k;
int i;
int j;
int num;
int n=0;
int tmp[MAXSIZE];
printf( "Enter integer (max 1000): " );
scanf( "%d", &k );
srand(1234567);
for( i=1; ; i++ ) {
num = 1+rand()%k;
for( j=0; j<=MAXSIZE; j++ ) {
if ( num == tmp[j] )
break;
else if ( (num != tmp[j]) ) {
tmp[n++] = num;
break;
}
}
if ( n==k )
break;
}
for( i=0; i<=n-1; i++ )
printf( "%d ", tmp[i] );
printf( "\n" );
return 0;
}
there are only 10 people in the world, those who know binary and those who dont
2. #2
C++ Developer XSquared's Avatar
Join Date
Jun 2002
Location
Ontario, Canada
Posts
2,718
Code:
for( j=0; j<=MAXSIZE; j++ ) {
if ( num == tmp[j] )
break;
else if ( (num != tmp[j]) ) {
tmp[n++] = num;
break;
}
}
Look at that code again... it exits as soon as a match is found, and it exits as soon as a match is not found... hmm...
Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah
You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie
3. #3
Just Lurking Dave_Sinkula's Avatar
Join Date
Oct 2002
Posts
5,005
>I just want to generate the number with no duplicates
Here's a way I'd done something similar, if you can stomach a goto.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
4. #4
Registered User
Join Date
Jan 2003
Posts
115
hmm ive tried placing the tmp array outside of that for loop so that i allow it to scan the whole array for a match.
however if it breaks out of that loop then it will add the value to the tmp array thereafter.
there are only 10 people in the world, those who know binary and those who dont
5. #5
Registered User
Join Date
Jan 2003
Posts
115
the goto is hard to digest.
but the if statements and what to do next are just as annoying.
im stuck with the conditions.
there are only 10 people in the world, those who know binary and those who dont
6. #6
Just Lurking Dave_Sinkula's Avatar
Join Date
Oct 2002
Posts
5,005
>the goto is hard to digest.
Then function-ize the inner loop to return true/false.
Code:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int foo(const int *a, size_t i)
{
size_t j;
for ( j = 0; j < i; ++j )
{
if ( a[i] == a[j] )
{
return 1;
}
}
return 0;
}
int main(void)
{
size_t i;
int n[25];
srand(time(NULL));
for ( i = 0; i < sizeof(n)/sizeof(*n); ++i )
{
do
{
n[i] = rand() % sizeof(n)/sizeof(*n) + 1;
} while ( foo(n, i) );
printf("%2d ", n[i]);
}
putchar('\n');
return 0;
}
[edit]
Problems with this approach are mentioned here (if any kind of harmless registration is required, but you still fear entering, this is a teaser...)
Imagine trying to fill each cell of a dart board with its own dart. If you're a bad player like me, everything will cruise along just fine *until* the last few squares, at which point I'll need tens if not hundreds (if not thousands!) of goes to try and fill the remaining squares.
The above method suffers the same problem. You'll find that on slower machines of old, and when used against large arrays, this method can take a long time to complete! With a particularly bad rand() function, it may even lock up in an infinite loop.
I recommend joining if only to read Peter's (or Paul's) posts.
[/edit]
Last edited by Dave_Sinkula; 08-01-2003 at 11:56 PM.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
7. #7
Registered User
Join Date
Jan 2003
Posts
115
cheers dave
there are only 10 people in the world, those who know binary and those who dont
8. #8
Registered User
Join Date
Jan 2003
Posts
115
if you perform the shuffle below, when u exchange the random numbers how will it know that it is not already in the array or not already generated?
i.e. a duplicate occuring
how can the shuffle not include a duplicate?
ive seen in the card programs that deal say 52 cards with this shuffle algorithm, but im not sure how it deals/shuffles without no duplicates..
there are only 10 people in the world, those who know binary and those who dont
9. #9
Registered User
Join Date
Jan 2003
Posts
115
sorry
when you say unique, the same generated random number cannot appear again?
there are only 10 people in the world, those who know binary and those who dont
Popular pages Recent additions subscribe to a feed
Similar Threads
1. Generating a sequence of numbers in a random order
By mirbogat in forum C Programming
Replies: 15
Last Post: 08-12-2008, 03:01 PM
2. Logical errors with seach function
By Taka in forum C Programming
Replies: 4
Last Post: 09-18-2006, 06:20 AM
3. Generating Random Numbers
By FromHolland in forum C++ Programming
Replies: 6
Last Post: 06-16-2003, 10:05 AM
4. Help generating random numbers in MFC
By drb2k2 in forum C++ Programming
Replies: 3
Last Post: 04-08-2003, 09:52 AM
5. the definition of a mathematical "average" or "mean"
By DavidP in forum A Brief History of Cprogramming.com
Replies: 7
Last Post: 12-03-2002, 11:15 AM
Website Security Test
|
__label__pos
| 0.752486 |
technicolor device on network
Photo of author
Written By UltraUnicorn
Lorem ipsum dolor sit amet consectetur pulvinar ligula augue quis venenatis.
technicolor device on network
A technicolor device on a network refers to a type of networking equipment that is manufactured by the French company, Technicolor. These devices are commonly used in homes and businesses to connect computers, printers, and other electronic devices to the internet and to each other. With the increasing demand for high-speed and reliable internet connectivity, technicolor devices have become a popular choice among consumers and businesses alike. In this article, we will delve deeper into the world of technicolor devices on a network and explore their features, benefits, and how they work.
What is a Technicolor Device?
A technicolor device, also known as a Technicolor Gateway, is a type of networking equipment that is designed to connect multiple devices to a network. These devices are manufactured by Technicolor, a company that specializes in the production of networking solutions, home media devices, and digital set-top boxes. Technicolor devices are widely used by internet service providers (ISPs) to provide their customers with high-speed internet connectivity.
One of the main advantages of technicolor devices is their versatility. They can be used to connect a wide range of devices to a network, including computers, smartphones, tablets, gaming consoles, and smart home devices. This makes them an ideal choice for both residential and commercial settings. Technicolor devices are also known for their user-friendly interface and easy setup process, making them a popular choice among non-technical users.
Features of a Technicolor Device
Technicolor devices come with a variety of features that make them stand out from other networking equipment. One of the key features of these devices is their dual-band technology, which allows them to operate on both 2.4GHz and 5GHz frequencies. This feature not only provides faster internet speeds but also reduces interference from other devices in the vicinity. This is particularly useful in crowded areas where there are multiple wireless networks operating simultaneously.
Another important feature of technicolor devices is their compatibility with various internet protocols, including ADSL, VDSL, and fiber. This means that they can be used with a wide range of internet connections, making them a versatile option for different types of networks. Additionally, technicolor devices come with advanced security features such as firewalls, encryption, and parental controls to ensure a safe and secure internet experience for users.
Benefits of Using a Technicolor Device
There are several benefits of using a technicolor device on a network. The first and most obvious benefit is the ability to connect multiple devices to the internet simultaneously. This is particularly useful in homes and businesses where there are several devices that require internet connectivity. With a technicolor device, users can connect all their devices to a single network, eliminating the need for multiple routers and switches.
Another major benefit of using a technicolor device is its high-speed internet connectivity. These devices are designed to provide fast and reliable internet speeds, which is essential for activities such as streaming, online gaming, and video conferencing. Furthermore, technicolor devices come with Quality of Service (QoS) features that prioritize certain types of internet traffic, ensuring a smooth and uninterrupted internet experience for users.
In addition to these benefits, technicolor devices also come with advanced management features that allow users to monitor and control their network. This includes features such as guest networks, device prioritization, and bandwidth allocation. These features give users more control over their network, allowing them to optimize it according to their needs.
How Does a Technicolor Device Work?
The exact working of a technicolor device may vary depending on the model and the type of network it is connected to. However, the basic principle remains the same. A technicolor device acts as a bridge between the devices connected to it and the internet. It does this by converting digital signals from the devices into analog signals that can be transmitted over a physical medium such as a telephone line or a cable.
When a device sends a request for internet access, the technicolor device receives the signal and converts it into digital form. It then checks the request against its security protocols and forwards it to the internet service provider. Once the request is approved, the technicolor device establishes a connection between the device and the internet, allowing data to flow back and forth.
Conclusion
In conclusion, a technicolor device on a network is a versatile and reliable networking equipment that is used to connect multiple devices to the internet. These devices are manufactured by Technicolor and come with a variety of features that make them an ideal choice for both residential and commercial settings. They provide high-speed internet connectivity, advanced security features, and give users more control over their network. With the increasing demand for fast and reliable internet, technicolor devices are expected to remain a popular choice for years to come.
whats with the p emoji
The p emoji, also known as the “person with folded hands” emoji, has become a popular symbol in digital communication. This simple, yet versatile emoji has captured the attention of many users and has sparked discussions about its meaning and usage. In this article, we will delve deeper into the world of the p emoji and explore its origins, variations, and significance.
Origins of the p emoji
The p emoji first made its appearance in 2010 as part of the Unicode 6.0 update. It was introduced as a way to express the gesture of “namaste” or “anjali mudra,” a traditional Hindu greeting which involves pressing the palms together and bowing the head. The Unicode Consortium, the organization responsible for standardizing characters and symbols across different platforms, approved the p emoji as part of their efforts to diversify the available emojis.
Since its introduction, the p emoji has gained immense popularity, especially in the Western world. It has become a symbol of peace, prayer, and gratitude, and has been widely used in various contexts. The p emoji has also been adapted and modified to suit different cultural references and expressions, making it a universal symbol of unity and respect.
Variations of the p emoji
The p emoji has undergone several transformations, both in appearance and meaning. One of the most common variations is the addition of skin tone options, which were introduced in 2015. This allowed users to choose from six different skin tones, making the p emoji more inclusive and representative of different races and ethnicities.
Another significant variation is the use of gender-specific versions of the p emoji. In 2016, Apple introduced a female version of the p emoji, followed by a male version in 2017. This was a response to the growing demand for emojis that reflect gender diversity and equality. The p emoji is also available in different hairstyles, clothing, and accessories, further enhancing its versatility and appeal.
Meaning and usage of the p emoji
The p emoji has a multitude of meanings and uses, depending on the context and the user’s intention. Its primary significance is that of prayer and respect. Many users use the p emoji to express a sense of gratefulness, appreciation, and hope. It is often used when someone wants to convey a message of peace, harmony, and unity.
The p emoji is also commonly used in the context of yoga and meditation. As mentioned earlier, it represents the gesture of “namaste,” which is often associated with these practices. Many yoga enthusiasts and practitioners use the p emoji to share their love for yoga and its philosophies.
Additionally, the p emoji has been adapted to convey different emotions and expressions. It is often used to express a sense of calmness, serenity, and inner peace. Some users also use it to convey a sense of humility, gratitude, and surrender. The p emoji is also commonly used in spiritual or religious contexts, where it represents devotion, reverence, and faith.
Controversies surrounding the p emoji
Like any other popular emoji, the p emoji has also been the subject of controversies. One of the main concerns raised by some users is the appropriation of Hindu culture and religion. As mentioned earlier, the p emoji is derived from the traditional Hindu greeting, and some users argue that its usage in digital communication is disrespectful and offensive. This has sparked discussions about cultural sensitivity and the need to understand the origins and meanings of symbols before using them.
Another controversy surrounding the p emoji is its potential misuse. Some users have pointed out that the p emoji is often used in inappropriate contexts, such as in humorous or sarcastic posts. This has led to debates about the appropriate usage of emojis and the need to use them responsibly.
Conclusion
The p emoji, with its simple yet powerful gesture, has captured the hearts of many users around the world. Its origins in Hindu culture and its widespread usage in digital communication have sparked discussions about cultural representation and sensitivity. However, its adaptability and versatility have also made it a prominent symbol of unity, peace, and gratitude. With its various variations and meanings, the p emoji continues to be a significant part of our digital communication and serves as a reminder of the importance of respect, diversity, and inclusivity.
what is the meaning of pos
POS, or Point of Sale, is a term that is commonly used in the world of business and retail. It refers to the location or spot where a transaction takes place, usually involving the exchange of goods and services for money. However, the meaning of POS goes beyond just a physical location. In this article, we will delve deeper into the concept of POS and explore its significance in the modern business landscape.
The origins of POS can be traced back to the ancient civilizations, where barter systems were the primary mode of trade. People would gather in designated areas to exchange goods and services, which can be considered as the early form of a POS. As time progressed, the concept of POS evolved and became more sophisticated with the introduction of currency and other forms of payment.
In today’s world, POS is more commonly associated with the use of electronic devices, such as cash registers, credit card machines, and barcode scanners. These devices have become an essential part of the retail industry, enabling businesses to process transactions quickly and efficiently. However, the meaning of POS has also expanded beyond just the physical devices to include software and systems that facilitate the entire sales process, from inventory management to customer relationship management.
One of the key benefits of a POS system is the ability to track and manage sales data in real-time. This data is crucial for businesses to make informed decisions about their products, pricing, and overall performance. By analyzing sales data, businesses can identify their best-selling products, understand customer buying patterns, and even forecast future sales. This information is vital for businesses to stay competitive and adapt to changing market trends.
In addition to sales data, a POS system can also generate reports on inventory and stock levels. This feature allows businesses to keep track of their products and ensure that they have enough stock to meet customer demand. It also helps in preventing stock shortages or overstocking, which can lead to financial losses. By having a clear view of their inventory, businesses can make better purchasing and stocking decisions, ultimately improving their bottom line.
Another significant advantage of POS is the integration with other business systems. Most modern POS systems can be connected to accounting software, customer relationship management (CRM) tools, and even e-commerce platforms. This integration streamlines business processes and reduces the need for manual data entry, saving time and reducing the chances of error. For example, a POS system connected to an accounting software can automatically update sales data, eliminating the need for manual entry and reducing the risk of human error.
The role of POS has also evolved with the rise of e-commerce. As more businesses move towards online selling, the need for a reliable POS system has become even more critical. E-commerce platforms have their own set of challenges, such as managing online orders, tracking inventory, and processing payments. A POS system that seamlessly integrates with an e-commerce platform can help businesses manage these tasks efficiently and provide a better customer experience.
Moreover, POS systems have also become more advanced with the introduction of cloud-based technology. This means that businesses can access their sales data and reports from anywhere, at any time, as long as they have an internet connection. Cloud-based POS systems also offer more flexibility and scalability, allowing businesses to add or remove features as their needs change. This has made POS systems more accessible to small and medium-sized businesses, who may not have the resources to invest in expensive hardware and software.
Aside from its practical uses, POS also has a significant impact on the customer experience. A smooth and efficient transaction process can enhance the overall shopping experience for customers. With a POS system, customers can expect a faster checkout process, accurate pricing, and a variety of payment options. This improves customer satisfaction and can lead to repeat business and positive word-of-mouth.
Furthermore, POS systems have also paved the way for the introduction of loyalty programs and other customer retention strategies. By capturing customer data at the point of sale, businesses can personalize their marketing efforts and offer exclusive deals and promotions to their loyal customers. This not only helps in retaining customers but also increases the chances of upselling and cross-selling.
One of the challenges that businesses face with POS systems is the need for proper training and maintenance. As POS systems become more sophisticated, employees need to be trained on how to use them effectively. This can be time-consuming and costly, especially for small businesses. However, with the right training and support, businesses can maximize the benefits of their POS systems and improve their overall performance.
In conclusion, the meaning of POS goes beyond just a physical location or a device. It encompasses the entire sales process and its impact on business operations and customer experience. From its humble beginnings in ancient civilizations to its modern-day form, POS has played a vital role in the evolution of trade and commerce. With the continuous advancements in technology, we can expect POS systems to become even more sophisticated and essential for businesses in the future.
Leave a Comment
|
__label__pos
| 0.982801 |
Creating a PostgreSQL Database
After installing PostgreSQL and phpPgAdmin on your server, you can begin to work with postgreSQL databases. In this tutorial we will show you how to Create a PostgreSQL database in cPanel.
How to Create a PostgreSQL Database
1. Login to cPanel.
2. Click the PostgreSQL Databases button in the Databases section.
3. In the Create New Database section, enter your database name.
4. Click the Create Database button. You are finished when you see a message stating “Added the database” along with the database name.
5. Click the Go Back button to return to the previous page. You will then see your new database listed in the Current Databases section.
Congratulations, now you know how to create a PostgreSQL database in cPanel! Continue to our next guide where we will show you how to create a database user, and add them to a postgreSQL database. Learn more about PostgreSQL Hosting options.
Leave a Reply
|
__label__pos
| 0.714566 |
NASM - The Netwide Assembler
NASM Forum => Programming with NASM => Topic started by: ceeman on December 09, 2020, 08:51:31 PM
Title: Problems understanding code
Post by: ceeman on December 09, 2020, 08:51:31 PM
section .text
global _start
_start:
xor edx, edx
xor ebx, ebx
mov ecx, STR1
looptop:
cmp byte[ecx], 0
je loopend
cmp byte[ecx], 65
jge inc_fun
inc edx
jmp loopbot
inc_fun:
inc ebx
loopbot:
inc ecx
jmp looptop
loopend:
mov eax, 1
int 0x80
section .data
STR1 db 'Hello, DAT103',0xa,0x0
I have this code, but can seem to put my head around it.
Most of all i wonder what happens when ecx is set to STR1, and what happens when comparing byte[ecx],0.
I can't see how it prints anything at all either, but the solution says it is 8.
Anyone can figure this out? Thanks.
Title: Re: Problems understanding code
Post by: Frank Kotler on December 09, 2020, 10:31:58 PM
Hi ceeman,
Welcome to the forum.
Why?
I think we can figure out what this code does, but I doubt if we can figure out why !
Code: [Select]
mov ecx. STR1
puts the address ("offset") of the string into the register. Straightforward enough...
Code: [Select]
cmp byte [ecx], 0
will find the end of the string when we get there. In the meantime, we seem to count lowercase letters... into ebx... When we hit the sys_exit, this will be the exit code. If you type "echo ?$" Linux will print this exit code. I don't know where "8" might come from. Perhaps better to ask where you found the code?
Best,
Frank
Title: Re: Problems understanding code
Post by: debs3759 on December 09, 2020, 11:43:18 PM
It looks to me like you are counting the number of ASCII characters that are equal to or greater than "A", which gives you the result 8. That's "Hello" and "DAT".
What are you expecting?
Title: Re: Problems understanding code
Post by: Frank Kotler on December 09, 2020, 11:59:21 PM
Ah, right you are - greater than 'A', not greater than 'a'. Thank you!
Best,
Frank
Title: Re: Problems understanding code
Post by: ceeman on December 10, 2020, 10:53:40 AM
Hello, and thanks for the replies. This code was from an exam where they asked for:
a) What is the result that the exit() syscall passes to a caller, for example, the shell if you run the program from the command line? (Line 12: cmp byte[ecx], 97) Solution: 4
b) What is the result if Line 12 in program is replaced by cmp byte[ecx], 65? (Originally it was cmp byte[ecx], 97). Solution: 8.
Thanks for the explanation, it made way more sense now. Thank you!
|
__label__pos
| 0.556431 |
21 August 2009
SharePoint Timer Job/Scheduler
Hi,
This Article target's on development and deployment of timer job in SharePoint.
Lets begin creating a blank project and calling references of SPJobDefinition for assigned timer that will execute the functionality as needed by the timer job to execute. Along with this we are also creating a feature which will specify the trigger schedule.
Here I’m specifying the code snippet for the same.
Create a Class library project include all the SharePoint related references needed.
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
DEFINE JOB
Inherit the SPJobDefinition class which is a member for Sharepoint Administration
class ClassName:SPJobDefinition
{
internal const string TASK_NAME = "MYTimer" ;
public ClassName() : base(){
}
public ClassName (string jobName, SPService service, SPServer server, SPJobLockType targetType): base(jobName, service, server, targetType){
}
public ClassName (string jobName, SPWebApplication webApplication)
: base((jobName, webApplication, null, SPJobLockType.Job) {
this.Title = "MYTimer" ;
}
//Override the Execute function
public override void Execute(Guid targetInstanceId) {
//Calling our function which needs to be executed
MYfunction();
//base.Execute(targetInstanceId);
}
public void MYfunction() {
try
{
SPSite osite = new SPSite( "SiteURL" );
//SPSite osite = SPContext.Current.Site;
SPWeb oweb = osite.OpenWeb();
oweb.AllowUnsafeUpdates = true;
if (oweb.Lists[ "Tasks" ] != null)
{
SPList olist = oweb.Lists[ "Tasks" ];
SPListItem newTask = olist.Items.Add();
newTask[ "Title" ] = DateTime.Now;
newTask.Update();
}
}
catch (Exception ee) { //Add you Exceptions catch }
}
}
Add a new class item for Feature Creation
//Feature creation
class MyclassInstaller:SPFeatureReceiver {
internal const string TASK_NAME = "MYTimer" ;
public override void FeatureInstalled(SPFeatureReceiverProperties properties) {
}
public override void FeatureUninstalling(SPFeatureReceiverProperties properties) {
}
public override void FeatureActivated(SPFeatureReceiverProperties properties) {
// register the the current web
SPSite site = properties.Feature.Parent as SPSite;
// make sure the job isn't already registered
foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
{
if (job.Name == TASK_NAME)
job.Delete();
}
TaskLoggerJob taskLoggerJob = new TaskLoggerJob(TASK_NAME, site.WebApplication);
// For Minute Trigger
SPMinuteSchedule schedule = new SPMinuteSchedule();
schedule.BeginSecond = 0;
schedule.EndSecond = 59;
//Intervals define the Minute Time Gap between triggers ex-2= min gap for timer trigger
schedule.Interval = 2;
taskLoggerJob.Schedule = schedule;
taskLoggerJob.Update();
}
public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
{
SPSite site = properties.Feature.Parent as SPSite;
// delete the job
foreach (SPJobDefinition job in site.WebApplication.JobDefinitions)
{
if (job.Name == TASK_NAME)
job.Delete();
}
}
}
DEPLOYMENT
The best way to deploy the time project is by creating a WSP either can use WSP builder or NANT for creating a WSP.
But Before we deploy this solution we need to add its FEATURE.XML in 12 hives feature folder with naming Feature conventions as here i have termed "MyTimer". You can manually add this file in this folder structure with following tags in it :
Feature xmlns="http://schemas.microsoft.com/sharepoint/"
Id="DA1B534E-08D9-41ef-B2C4-B656E9389D80"
Title="MYTimer" Description="Installs the task MY timer job feature to the current site collection."
Scope="Site"
Hidden="TRUE"
Version="1.0.0.0"
ReceiverAssembly="MYSite, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3aeda64f0b993534"
ReceiverClass="MYSite.MyclassInstaller"
>
Once a WSP is created you follow the same procedures as recommended i.e
1. Add Solution
2. Deploy Solutions
3. Install Feature
4. Activate Feature.
STSADM Commands for WSP Deployment
pushd %programfiles%\common files\microsoft shared\web server extensions\12\bin
@Echo ------Adding Sol------
stsadm -o addsolution -filename
file://wsppath%20/MyTimer.wsp
stsadm -o execadmsvcjobs
@Echo ------deploy Sol----
stsadm -o deploysolution -name MyTimer.wsp -allowGacDeployment -local -force
stsadm -o execadmsvcjobs
iisreset
@echo -----Feature added-----
stsadm -o installfeature -filename MyTimer\feature.xml -force
stsadm -o activatefeature -filename MyTimer\feature.xml -url siteURL
-force
stsadm -o execadmsvcjobs
iisreset
There goes you can check timer execution in Timer job status & Timer job definitions in central administration which details the execution time and its status for success.
Just a Quick information of all the inbuilt Timer in sharepoint Sorted by Neil Click here
Here are the snipplets for Weekly, Monthly & Annual.
Hourly(Triggers @ Every Hour 01.Min)
SPHourlySchedule JobSchedule = new
SPHourlySchedule();
JobSchedule.BeginMinute = 1;
JobSchedule.EndMinute = 2;
Weekly (Triggers @ Thursday 04:01:00PM)
SPWeeklySchedule JobSchedule = new SPWeeklySchedule();
JobSchedule.BeginDayOfWeek = DayOfWeek.Thursday;
JobSchedule.EndDayOfWeek = DayOfWeek.Thursday;
JobSchedule.BeginHour = 16;
JobSchedule.EndHour = 16;
JobSchedule.BeginMinute = 01;
JobSchedule.EndMinute = 05;
JobSchedule.BeginSecond = 00;
JobSchedule.EndSecond = 00;
taskLoggerJob.Schedule = JobSchedule;
Monthly (Triggers @ First Day(01) of the Month, at 10:15:00AM)
SPMonthlySchedule JobSchedule = new SPMonthlySchedule();
JobSchedule.BeginDay = 1;
JobSchedule.EndDay = 1;
JobSchedule.BeginHour = 10;
JobSchedule.EndHour = 10;
JobSchedule.BeginMinute = 15;
JobSchedule.EndMinute = 25;
JobSchedule.BeginSecond = 00;
JobSchedule.EndSecond = 00;
Annually (Triggers @ April 21, at 10:15 AM)
SPYearlySchedule JobSchedule = new SPYearlySchedule();
JobSchedule.BeginMonth = 4;
JobSchedule.EndMonth = 4;
JobSchedule.BeginDay = 21;
JobSchedule.EndDay = 21;
JobSchedule.BeginHour = 10;
JobSchedule.EndHour = 10;
JobSchedule.BeginMinute = 15;
JobSchedule.EndMinute = 25;
JobSchedule.BeginSecond = 00;
JobSchedule.EndSecond = 00;
Addin your comments for this article.
Special Thanks: Andrew Connell, Ganesh Bankar.
3 comments:
1. Does it work in SP2010?
Do you have a sample of this project? (Something I can download)
Thanks in advanced!
ReplyDelete
Thanks for your valuable comments
Rate Now:
|
__label__pos
| 0.560741 |
PhpRiot
Become Zend Certified
Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...
When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store
usort
(PHP 4, PHP 5)
usortSort an array by values using a user-defined comparison function
Description
bool usort ( array &$array , callable $value_compare_func )
This function will sort an array by its values using a user-supplied comparison function. If the array you wish to sort needs to be sorted by some non-trivial criteria, you should use this function.
Note:
If two members compare as equal, their relative order in the sorted array is undefined.
Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.
Parameters
array
The input array.
value_compare_func
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
int callback ( mixed $a, mixed $b )
Caution
Returning non-integer values from the comparison function, such as float, will result in an internal cast to integer of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.
Return Values
Returns TRUE on success or FALSE on failure.
Changelog
Version Description
4.1.0 A new sort algorithm was introduced. The value_compare_func doesn't keep the original order for elements comparing as equal.
Examples
Example #1 usort() example
<?php
function cmp($a$b)
{
if (
$a == $b) {
return
0;
}
return (
$a $b) ? -1;
}
$a = array(32561);
usort($a"cmp");
foreach (
$a as $key => $value) {
echo
"$key$value\n";
}
?>
The above example will output:
0: 1
1: 2
2: 3
3: 5
4: 6
Note:
Obviously in this trivial case the sort() function would be more appropriate.
Example #2 usort() example using multi-dimensional array
<?php
function cmp($a$b)
{
return
strcmp($a["fruit"], $b["fruit"]);
}
$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";
usort($fruits"cmp");
while (list(
$key$value) = each($fruits)) {
echo
"\$fruits[$key]: " $value["fruit"] . "\n";
}
?>
When sorting a multi-dimensional array, $a and $b contain references to the first index of the array.
The above example will output:
$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons
Example #3 usort() example using a member function of an object
<?php
class TestObj {
var
$name;
function
TestObj($name)
{
$this->name $name;
}
/* This is the static comparing function: */
static function cmp_obj($a$b)
{
$al strtolower($a->name);
$bl strtolower($b->name);
if (
$al == $bl) {
return
0;
}
return (
$al $bl) ? +: -1;
}
}
$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");
usort($a, array("TestObj""cmp_obj"));
foreach (
$a as $item) {
echo
$item->name "\n";
}
?>
The above example will output:
b
c
d
Example #4 usort() example using a closure to sort a multi-dimensional array
<?php
$array
[0] = array('key_a' => 'z''key_b' => 'c');
$array[1] = array('key_a' => 'x''key_b' => 'b');
$array[2] = array('key_a' => 'y''key_b' => 'a');
function
build_sorter($key) {
return function (
$a$b) use ($key) {
return
strnatcmp($a[$key], $b[$key]);
};
}
usort($arraybuild_sorter('key_b'));
foreach (
$array as $item) {
echo
$item['key_a'] . ', ' $item['key_b'] . "\n";
}
?>
The above example will output:
y, a
x, b
z, c
See Also
PHP Manual
|
__label__pos
| 0.963085 |
Excel SUMIF Function
HomeExcel Functions List (Top 100) Examples + Sample FileExcel SUMIF Function (Example + Sample File)
What is EXCEL SUMIF FUNCTION
The Excel SUMIF Function is listed under Microsoft Excel's Maths Functions category. It returns the sum of the numbers which meet the condition you specify. In simple words, it only considers and calculates the sum of values that fulfill the condition.
How to use it
To learn how to use the SUMIF function in Excel, you need to understand its syntax and arguments:
Syntax
SUMIF(range, criteria, [sum_range])
Arguments
• range: A range of cells from which you want to check for criteria.
• criteria: A criteria which can be a number, text, expression, cell reference or a function.
• [sum_range]: A cell range that has the values you want to sum.
Notes
• If the sum_range is omitted, the cells in range will be summed.
• Make sure to use double quotation marks to specify Text criteria or criteria that include math symbols, must be enclosed in double quotation marks.
• The size of the criteria range and sum range should be of the same size.
Example
To master the SUMIF function we need to try it out in an example and below is one which you can try out:
In the below example, we have specified A1:A9 as criteria range and B1:B9 as sum range and after that, we have specified the criteria in A12 which has the value C.
You can also insert criteria directly into the function. In the below example, we have used an asterisk wildcard to specify a criterion which has an alphabet "S".
And, if you skip specifying the sum range it will give you the sum of criteria range.
But, that will be only possible if the criteria range has numeric values.
Related functions
This tutorial is the part of our Excel Functions with Examples (Function Guide) and below are some of the related functions:
About the Author
Puneet Gogia
Puneet is using Excel since his college days. He helped thousands of people to understand the power of the spreadsheets and learn Microsoft Excel. You can find him online, tweeting about Excel, on a running track, or sometimes hiking up a mountain.
|
__label__pos
| 0.823828 |
You may also like
problem icon
Consecutive Numbers
An investigation involving adding and subtracting sets of consecutive numbers. Lots to find out, lots to explore.
problem icon
14 Divisors
What is the smallest number with exactly 14 divisors?
problem icon
Summing Consecutive Numbers
Many numbers can be expressed as the sum of two or more consecutive integers. For example, 15=7+8 and 10=1+2+3+4. Can you say which numbers can be expressed in this way?
Bargain
Stage: 3 Short Challenge Level: Challenge Level:1
The reduction of 15% off sale prices is equal to a reduction of 7.5% off the original prices. Therefore the toal reduction on the original prices is (50 + 7.5)% = 57.5%.
This problem is taken from the UKMT Mathematical Challenges.
View the previous week's solution
View the current weekly problem
|
__label__pos
| 0.999047 |
Mybatis [2] – multiple mapper files and the role of namespace
Time:2021-5-7
The code is placed directly in GitHub warehouse【 https://github.com/Damaer/Myb… 】It can be run directly, so it doesn’t take up space.
Mybatis [2] - multiple mapper files and the role of namespace
Multiple mapper files and the role of namespace
How to deal with multiple mapper files and what is the use of namespace
First, let’s look at the create database statement
#Create database
CREATE DATABASE `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
#Create data table
CREATE TABLE `student` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(20) NOT NULL ,
`age` INT NOT NULL , `score` DOUBLE NOT NULL , PRIMARY KEY (`id`)) ENGINE = MyISAM;
Here we have to talk about the running process of mybatis again: first, we pass theResources.getResourceAsStream("mybatis.xml")Read tomybatis.xmlIn this file, the configuration of the whole project is related to the database, such as the running database environment (which database to connect to, the address of the database server, user name, password), or the configuration of external configuration files,Most importantly, this file registers the mapper fileThen we useSqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);When I was young,sqlSessionFactoryGo back and read itmybatis.xmlIt will read the configuration files, and will get the information read by each configuration file one by oneMapperMapping files when we useopenSession()GetsqlSessionFor example, we usesqlSession.insert("insertStudent",student);, you will find the SQL configuration statements in each mapper, which is similar to the following:
<mapper namespace="mapper1">
<insert id="insertStudent" parameterType="bean.Student">
insert into student(name,age,score) values(#{name},#{age},#{score})
</insert>
</mapper>
findidThe same is OK, so many people will say, since the distinction is usedidWhat’s the use of the namespace attribute in my mapper file?
When we have two or more of the sameidIf there is only one, we must use namespace to distinguishmapper.xmlDocuments, then wenamespaceYou can write anything. When using it, you only need to:sqlSession.insert("insertStudent",student);If our ID is the same, we need to use:sqlSession.insert("mapper1.insertStudent",student);Add in frontnamspace. Otherwise, the following error will appear, prompting us to use the full name includingnamespaceOr redefine oneid
In general, eitheridIt’s not the same. You can use it directly, oridIt’s the same, butnamespaceIt’s not the same. Add it when you use itnamespacedistinguish. Otherwise, the following error will be reported:
Mybatis [2] - multiple mapper files and the role of namespace
There are multiple mapper files. You need to register two files in mybatis.xml file:
<!-- Register mapping file -- >
<mappers>
<mapper resource="mapper/mapper1.xml"/>
<mapper resource="mapper/mapper2.xml"/>
</mappers>
When using, add the namespace:
Mybatis [2] - multiple mapper files and the role of namespace
This article is only on behalf of their own (this rookie) learning accumulation records, or learning notes, if there is infringement, please contact the author to delete. No one is perfect, so is the article. The style of writing is immature. If you don’t have talent, don’t spray. If you have any mistakes, I hope you can point them out. Thank you very much~
The road of technology is not temporary, high mountains and long rivers, even if it is slow, it will not stop.
Official account: Qinhai grocery store
|
__label__pos
| 0.976645 |
src/HOL/Tools/datatype_abs_proofs.ML
author berghofe
Fri, 16 Oct 1998 18:54:55 +0200
changeset 5661 6ecb6ea25f19
parent 5578 7de426cf179c
child 5891 92e0f5e6fd17
permissions -rw-r--r--
- Changed structure of name spaces - Proofs for datatypes with unneeded parameters are working now - added additional parameter flat_names - added quiet_mode flag
(* Title: HOL/Tools/datatype_abs_proofs.ML
ID: $Id$
Author: Stefan Berghofer
Copyright 1998 TU Muenchen
Proofs and defintions independent of concrete representation
of datatypes (i.e. requiring only abstract properties such as
injectivity / distinctness of constructors and induction)
- case distinction (exhaustion) theorems
- characteristic equations for primrec combinators
- characteristic equations for case combinators
- distinctness of constructors (external version)
- equations for splitting "P (case ...)" expressions
- datatype size function
- "nchotomy" and "case_cong" theorems for TFL
*)
signature DATATYPE_ABS_PROOFS =
sig
val prove_casedist_thms : string list -> (int * (string * DatatypeAux.dtyp list *
(string * DatatypeAux.dtyp list) list)) list list -> (string * sort) list ->
thm -> theory -> theory * thm list
val prove_primrec_thms : bool -> string list -> (int * (string * DatatypeAux.dtyp list *
(string * DatatypeAux.dtyp list) list)) list list -> (string * sort) list ->
DatatypeAux.datatype_info Symtab.table -> thm list list -> thm list list ->
thm -> theory -> theory * string list * thm list
val prove_case_thms : bool -> string list -> (int * (string * DatatypeAux.dtyp list *
(string * DatatypeAux.dtyp list) list)) list list -> (string * sort) list ->
string list -> thm list -> theory -> theory * string list * thm list list
val prove_distinctness_thms : bool -> string list -> (int * (string * DatatypeAux.dtyp list *
(string * DatatypeAux.dtyp list) list)) list list -> (string * sort) list ->
thm list list -> thm list list -> theory -> theory * thm list list
val prove_split_thms : string list -> (int * (string * DatatypeAux.dtyp list *
(string * DatatypeAux.dtyp list) list)) list list -> (string * sort) list ->
thm list list -> thm list list -> thm list -> thm list list -> theory ->
theory * (thm * thm) list
val prove_size_thms : bool -> string list -> (int * (string * DatatypeAux.dtyp list *
(string * DatatypeAux.dtyp list) list)) list list -> (string * sort) list ->
string list -> thm list -> theory -> theory * thm list
val prove_nchotomys : string list -> (int * (string * DatatypeAux.dtyp list *
(string * DatatypeAux.dtyp list) list)) list list -> (string * sort) list ->
thm list -> theory -> theory * thm list
val prove_case_congs : string list -> (int * (string * DatatypeAux.dtyp list *
(string * DatatypeAux.dtyp list) list)) list list -> (string * sort) list ->
thm list -> thm list list -> theory -> theory * thm list
end;
structure DatatypeAbsProofs : DATATYPE_ABS_PROOFS =
struct
open DatatypeAux;
val thin = read_instantiate_sg (sign_of Set.thy) [("V", "?X : ?Y")] thin_rl;
val (_ $ (_ $ (_ $ (distinct_f $ _) $ _))) = hd (prems_of distinct_lemma);
(************************ case distinction theorems ***************************)
fun prove_casedist_thms new_type_names descr sorts induct thy =
let
val _ = message "Proving case distinction theorems...";
val descr' = flat descr;
val recTs = get_rec_types descr' sorts;
val newTs = take (length (hd descr), recTs);
val induct_Ps = map head_of (dest_conj (HOLogic.dest_Trueprop (concl_of induct)));
fun prove_casedist_thm ((i, t), T) =
let
val dummyPs = map (fn (Var (_, Type (_, [T', T'']))) =>
Abs ("z", T', Const ("True", T''))) induct_Ps;
val P = Abs ("z", T, HOLogic.imp $ HOLogic.mk_eq (Var (("a", 0), T), Bound 0) $
Var (("P", 0), HOLogic.boolT))
val insts = take (i, dummyPs) @ (P::(drop (i + 1, dummyPs)));
val cert = cterm_of (sign_of thy);
val insts' = (map cert induct_Ps) ~~ (map cert insts);
val induct' = refl RS ((nth_elem (i,
split_conj_thm (cterm_instantiate insts' induct))) RSN (2, rev_mp))
in prove_goalw_cterm [] (cert t) (fn prems =>
[rtac induct' 1,
REPEAT (rtac TrueI 1),
REPEAT ((rtac impI 1) THEN (eresolve_tac prems 1)),
REPEAT (rtac TrueI 1)])
end;
val casedist_thms = map prove_casedist_thm ((0 upto (length newTs - 1)) ~~
(DatatypeProp.make_casedists descr sorts) ~~ newTs)
in
(store_thms "exhaust" new_type_names casedist_thms thy, casedist_thms)
end;
(*************************** primrec combinators ******************************)
fun prove_primrec_thms flat_names new_type_names descr sorts
(dt_info : datatype_info Symtab.table) constr_inject dist_rewrites induct thy =
let
val _ = message "Constructing primrec combinators...";
val big_name = space_implode "_" new_type_names;
val thy0 = add_path flat_names big_name thy;
val descr' = flat descr;
val recTs = get_rec_types descr' sorts;
val used = foldr add_typ_tfree_names (recTs, []);
val newTs = take (length (hd descr), recTs);
val induct_Ps = map head_of (dest_conj (HOLogic.dest_Trueprop (concl_of induct)));
val big_rec_name' = big_name ^ "_rec_set";
val rec_set_names = map (Sign.full_name (sign_of thy0))
(if length descr' = 1 then [big_rec_name'] else
(map ((curry (op ^) (big_rec_name' ^ "_")) o string_of_int)
(1 upto (length descr'))));
val rec_result_Ts = map TFree (variantlist (replicate (length descr') "'t", used) ~~
replicate (length descr') HOLogic.termS);
val reccomb_fn_Ts = flat (map (fn (i, (_, _, constrs)) =>
map (fn (_, cargs) =>
let
val recs = filter is_rec_type cargs;
val argTs = (map (typ_of_dtyp descr' sorts) cargs) @
(map (fn r => nth_elem (dest_DtRec r, rec_result_Ts)) recs)
in argTs ---> nth_elem (i, rec_result_Ts)
end) constrs) descr');
val rec_set_Ts = map (fn (T1, T2) => reccomb_fn_Ts ---> HOLogic.mk_setT
(HOLogic.mk_prodT (T1, T2))) (recTs ~~ rec_result_Ts);
val rec_fns = map (uncurry (mk_Free "f"))
(reccomb_fn_Ts ~~ (1 upto (length reccomb_fn_Ts)));
val rec_sets = map (fn c => list_comb (Const c, rec_fns))
(rec_set_names ~~ rec_set_Ts);
(* introduction rules for graph of primrec function *)
fun make_rec_intr T set_name ((rec_intr_ts, l), (cname, cargs)) =
let
fun mk_prem (dt, (j, k, prems, t1s, t2s)) =
let
val T = typ_of_dtyp descr' sorts dt;
val free1 = mk_Free "x" T j
in (case dt of
DtRec m =>
let val free2 = mk_Free "y" (nth_elem (m, rec_result_Ts)) k
in (j + 1, k + 1, (HOLogic.mk_Trueprop (HOLogic.mk_mem
(HOLogic.mk_prod (free1, free2), nth_elem (m, rec_sets))))::prems,
free1::t1s, free2::t2s)
end
| _ => (j + 1, k, prems, free1::t1s, t2s))
end;
val Ts = map (typ_of_dtyp descr' sorts) cargs;
val (_, _, prems, t1s, t2s) = foldr mk_prem (cargs, (1, 1, [], [], []))
in (rec_intr_ts @ [Logic.list_implies (prems, HOLogic.mk_Trueprop (HOLogic.mk_mem
(HOLogic.mk_prod (list_comb (Const (cname, Ts ---> T), t1s),
list_comb (nth_elem (l, rec_fns), t1s @ t2s)), set_name)))], l + 1)
end;
val (rec_intr_ts, _) = foldl (fn (x, ((d, T), set_name)) =>
foldl (make_rec_intr T set_name) (x, #3 (snd d)))
(([], 0), descr' ~~ recTs ~~ rec_sets);
val (thy1, {intrs = rec_intrs, elims = rec_elims, ...}) =
setmp InductivePackage.quiet_mode (!quiet_mode)
(InductivePackage.add_inductive_i false true big_rec_name' false false true
rec_sets rec_intr_ts [] []) thy0;
(* prove uniqueness and termination of primrec combinators *)
val _ = message "Proving termination and uniqueness of primrec functions...";
fun mk_unique_tac ((tac, intrs), ((((i, (tname, _, constrs)), elim), T), T')) =
let
val distinct_tac = (etac Pair_inject 1) THEN
(if i < length newTs then
full_simp_tac (HOL_ss addsimps (nth_elem (i, dist_rewrites))) 1
else full_simp_tac (HOL_ss addsimps
((#distinct (the (Symtab.lookup (dt_info, tname)))) @
[Suc_Suc_eq, Suc_not_Zero, Zero_not_Suc])) 1);
val inject = map (fn r => r RS iffD1)
(if i < length newTs then nth_elem (i, constr_inject)
else #inject (the (Symtab.lookup (dt_info, tname))));
fun mk_unique_constr_tac n ((tac, intr::intrs, j), (cname, cargs)) =
let
val k = length (filter is_rec_type cargs)
in (EVERY [DETERM tac,
REPEAT (etac ex1E 1), rtac ex1I 1,
DEPTH_SOLVE_1 (ares_tac [intr] 1),
REPEAT_DETERM_N k (etac thin 1),
etac elim 1,
REPEAT_DETERM_N j distinct_tac,
etac Pair_inject 1, TRY (dresolve_tac inject 1),
REPEAT (etac conjE 1), hyp_subst_tac 1,
REPEAT (etac allE 1),
REPEAT (dtac mp 1 THEN atac 1),
TRY (hyp_subst_tac 1),
rtac refl 1,
REPEAT_DETERM_N (n - j - 1) distinct_tac],
intrs, j + 1)
end;
val (tac', intrs', _) = foldl (mk_unique_constr_tac (length constrs))
((tac, intrs, 0), constrs);
in (tac', intrs') end;
val rec_unique_thms =
let
val rec_unique_ts = map (fn (((set_t, T1), T2), i) =>
Const ("Ex1", (T2 --> HOLogic.boolT) --> HOLogic.boolT) $
absfree ("y", T2, HOLogic.mk_mem (HOLogic.mk_prod
(mk_Free "x" T1 i, Free ("y", T2)), set_t)))
(rec_sets ~~ recTs ~~ rec_result_Ts ~~ (1 upto length recTs));
val cert = cterm_of (sign_of thy1)
val insts = map (fn ((i, T), t) => absfree ("x" ^ (string_of_int i), T, t))
((1 upto length recTs) ~~ recTs ~~ rec_unique_ts);
val induct' = cterm_instantiate ((map cert induct_Ps) ~~
(map cert insts)) induct;
val (tac, _) = foldl mk_unique_tac
((rtac induct' 1, rec_intrs), descr' ~~ rec_elims ~~ recTs ~~ rec_result_Ts)
in split_conj_thm (prove_goalw_cterm []
(cert (HOLogic.mk_Trueprop (mk_conj rec_unique_ts))) (K [tac]))
end;
val rec_total_thms = map (fn r =>
r RS ex1_implies_ex RS (select_eq_Ex RS iffD2)) rec_unique_thms;
(* define primrec combinators *)
val big_reccomb_name = (space_implode "_" new_type_names) ^ "_rec";
val reccomb_names = map (Sign.full_name (sign_of thy1))
(if length descr' = 1 then [big_reccomb_name] else
(map ((curry (op ^) (big_reccomb_name ^ "_")) o string_of_int)
(1 upto (length descr'))));
val reccombs = map (fn ((name, T), T') => list_comb
(Const (name, reccomb_fn_Ts @ [T] ---> T'), rec_fns))
(reccomb_names ~~ recTs ~~ rec_result_Ts);
val thy2 = thy1 |>
Theory.add_consts_i (map (fn ((name, T), T') =>
(Sign.base_name name, reccomb_fn_Ts @ [T] ---> T', NoSyn))
(reccomb_names ~~ recTs ~~ rec_result_Ts)) |>
Theory.add_defs_i (map (fn ((((name, comb), set), T), T') =>
((Sign.base_name name) ^ "_def", Logic.mk_equals
(comb $ Free ("x", T),
Const ("Eps", (T' --> HOLogic.boolT) --> T') $ absfree ("y", T',
HOLogic.mk_mem (HOLogic.mk_prod (Free ("x", T), Free ("y", T')), set)))))
(reccomb_names ~~ reccombs ~~ rec_sets ~~ recTs ~~ rec_result_Ts)) |>
parent_path flat_names;
val reccomb_defs = map ((get_def thy2) o Sign.base_name) reccomb_names;
(* prove characteristic equations for primrec combinators *)
val _ = message "Proving characteristic theorems for primrec combinators..."
val rec_thms = map (fn t => prove_goalw_cterm reccomb_defs
(cterm_of (sign_of thy2) t) (fn _ =>
[rtac select1_equality 1,
resolve_tac rec_unique_thms 1,
resolve_tac rec_intrs 1,
REPEAT (resolve_tac rec_total_thms 1)]))
(DatatypeProp.make_primrecs new_type_names descr sorts thy2)
in
(thy2 |> Theory.add_path (space_implode "_" new_type_names) |>
PureThy.add_tthmss [(("recs", map Attribute.tthm_of rec_thms), [])] |>
Theory.parent_path,
reccomb_names, rec_thms)
end;
(***************************** case combinators *******************************)
fun prove_case_thms flat_names new_type_names descr sorts reccomb_names primrec_thms thy =
let
val _ = message "Proving characteristic theorems for case combinators...";
val thy1 = add_path flat_names (space_implode "_" new_type_names) thy;
val descr' = flat descr;
val recTs = get_rec_types descr' sorts;
val used = foldr add_typ_tfree_names (recTs, []);
val newTs = take (length (hd descr), recTs);
val T' = TFree (variant used "'t", HOLogic.termS);
val case_dummy_fns = map (fn (_, (_, _, constrs)) => map (fn (_, cargs) =>
let
val Ts = map (typ_of_dtyp descr' sorts) cargs;
val Ts' = replicate (length (filter is_rec_type cargs)) T'
in Const ("arbitrary", Ts @ Ts' ---> T')
end) constrs) descr';
val case_names = map (fn s =>
Sign.full_name (sign_of thy1) (s ^ "_case")) new_type_names;
(* define case combinators via primrec combinators *)
val (case_defs, thy2) = foldl (fn ((defs, thy),
((((i, (_, _, constrs)), T), name), recname)) =>
let
val (fns1, fns2) = ListPair.unzip (map (fn ((_, cargs), j) =>
let
val Ts = map (typ_of_dtyp descr' sorts) cargs;
val Ts' = Ts @ (replicate (length (filter is_rec_type cargs)) T');
val frees' = map (uncurry (mk_Free "x")) (Ts' ~~ (1 upto length Ts'));
val frees = take (length cargs, frees');
val free = mk_Free "f" (Ts ---> T') j
in
(free, list_abs_free (map dest_Free frees',
list_comb (free, frees)))
end) (constrs ~~ (1 upto length constrs)));
val caseT = (map (snd o dest_Free) fns1) @ [T] ---> T';
val fns = (flat (take (i, case_dummy_fns))) @
fns2 @ (flat (drop (i + 1, case_dummy_fns)));
val reccomb = Const (recname, (map fastype_of fns) @ [T] ---> T');
val decl = (Sign.base_name name, caseT, NoSyn);
val def = ((Sign.base_name name) ^ "_def",
Logic.mk_equals (list_comb (Const (name, caseT), fns1),
list_comb (reccomb, (flat (take (i, case_dummy_fns))) @
fns2 @ (flat (drop (i + 1, case_dummy_fns))) )));
val thy' = thy |>
Theory.add_consts_i [decl] |> Theory.add_defs_i [def];
in (defs @ [get_def thy' (Sign.base_name name)], thy')
end) (([], thy1), (hd descr) ~~ newTs ~~ case_names ~~
(take (length newTs, reccomb_names)));
val case_thms = map (map (fn t => prove_goalw_cterm (case_defs @
(map mk_meta_eq primrec_thms)) (cterm_of (sign_of thy2) t)
(fn _ => [rtac refl 1])))
(DatatypeProp.make_cases new_type_names descr sorts thy2);
val thy3 = thy2 |> Theory.add_trrules_i
(DatatypeProp.make_case_trrules new_type_names descr) |>
parent_path flat_names;
in
(store_thmss "cases" new_type_names case_thms thy3, case_names, case_thms)
end;
(************************ distinctness of constructors ************************)
fun prove_distinctness_thms flat_names new_type_names descr sorts dist_rewrites case_thms thy =
let
val thy1 = add_path flat_names (space_implode "_" new_type_names) thy;
val descr' = flat descr;
val recTs = get_rec_types descr' sorts;
val newTs = take (length (hd descr), recTs);
(*--------------------------------------------------------------------*)
(* define t_ord - functions for proving distinctness of constructors: *)
(* t_ord C_i ... = i *)
(*--------------------------------------------------------------------*)
fun define_ord ((thy, ord_defs), (((_, (_, _, constrs)), T), tname)) =
if length constrs < DatatypeProp.dtK then (thy, ord_defs)
else
let
val Tss = map ((map (typ_of_dtyp descr' sorts)) o snd) constrs;
val ts = map HOLogic.mk_nat (0 upto length constrs - 1);
val mk_abs = foldr (fn (T, t') => Abs ("x", T, t'));
val fs = map mk_abs (Tss ~~ ts);
val fTs = map (fn Ts => Ts ---> HOLogic.natT) Tss;
val ord_name = Sign.full_name (sign_of thy) (tname ^ "_ord");
val case_name = Sign.intern_const (sign_of thy) (tname ^ "_case");
val ordT = T --> HOLogic.natT;
val caseT = fTs ---> ordT;
val defpair = (tname ^ "_ord_def", Logic.mk_equals
(Const (ord_name, ordT), list_comb (Const (case_name, caseT), fs)));
val thy' = thy |>
Theory.add_consts_i [(tname ^ "_ord", ordT, NoSyn)] |>
Theory.add_defs_i [defpair];
val def = get_def thy' (tname ^ "_ord")
in (thy', ord_defs @ [def]) end;
val (thy2, ord_defs) =
foldl define_ord ((thy1, []), (hd descr) ~~ newTs ~~ new_type_names);
(**** number of constructors < dtK ****)
fun prove_distinct_thms _ [] = []
| prove_distinct_thms dist_rewrites' (t::_::ts) =
let
val dist_thm = prove_goalw_cterm [] (cterm_of (sign_of thy2) t) (fn _ =>
[simp_tac (HOL_ss addsimps dist_rewrites') 1])
in dist_thm::(standard (dist_thm RS not_sym))::
(prove_distinct_thms dist_rewrites' ts)
end;
val distinct_thms = map (fn ((((_, (_, _, constrs)), ts),
dist_rewrites'), case_thms) =>
if length constrs < DatatypeProp.dtK then
prove_distinct_thms dist_rewrites' ts
else
let
val t::ts' = rev ts;
val (_ $ (_ $ (_ $ (f $ _) $ _))) = hd (Logic.strip_imp_prems t);
val cert = cterm_of (sign_of thy2);
val distinct_lemma' = cterm_instantiate
[(cert distinct_f, cert f)] distinct_lemma;
val rewrites = ord_defs @ (map mk_meta_eq case_thms)
in
(map (fn t => prove_goalw_cterm rewrites (cert t)
(fn _ => [rtac refl 1])) (rev ts')) @ [standard distinct_lemma']
end) ((hd descr) ~~ (DatatypeProp.make_distincts new_type_names
descr sorts thy2) ~~ dist_rewrites ~~ case_thms)
in
(thy2 |> parent_path flat_names |>
store_thmss "distinct" new_type_names distinct_thms,
distinct_thms)
end;
(******************************* case splitting *******************************)
fun prove_split_thms new_type_names descr sorts constr_inject dist_rewrites
casedist_thms case_thms thy =
let
val _ = message "Proving equations for case splitting...";
val descr' = flat descr;
val recTs = get_rec_types descr' sorts;
val newTs = take (length (hd descr), recTs);
fun prove_split_thms ((((((t1, t2), inject), dist_rewrites'),
exhaustion), case_thms'), T) =
let
val cert = cterm_of (sign_of thy);
val _ $ (_ $ lhs $ _) = hd (Logic.strip_assums_hyp (hd (prems_of exhaustion)));
val exhaustion' = cterm_instantiate
[(cert lhs, cert (Free ("x", T)))] exhaustion;
val tacsf = K [rtac exhaustion' 1, ALLGOALS (asm_simp_tac
(HOL_ss addsimps (dist_rewrites' @ inject @ case_thms')))]
in
(prove_goalw_cterm [] (cert t1) tacsf,
prove_goalw_cterm [] (cert t2) tacsf)
end;
val split_thm_pairs = map prove_split_thms
((DatatypeProp.make_splits new_type_names descr sorts thy) ~~ constr_inject ~~
dist_rewrites ~~ casedist_thms ~~ case_thms ~~ newTs);
val (split_thms, split_asm_thms) = ListPair.unzip split_thm_pairs
in
(thy |> store_thms "split" new_type_names split_thms |>
store_thms "split_asm" new_type_names split_asm_thms,
split_thm_pairs)
end;
(******************************* size functions *******************************)
fun prove_size_thms flat_names new_type_names descr sorts reccomb_names primrec_thms thy =
let
val _ = message "Proving equations for size function...";
val big_name = space_implode "_" new_type_names;
val thy1 = add_path flat_names big_name thy;
val descr' = flat descr;
val recTs = get_rec_types descr' sorts;
val big_size_name = space_implode "_" new_type_names ^ "_size";
val size_name = Sign.intern_const (sign_of (the (get_thy "Arith" thy1))) "size";
val size_names = replicate (length (hd descr)) size_name @
map (Sign.full_name (sign_of thy1))
(if length (flat (tl descr)) = 1 then [big_size_name] else
map (fn i => big_size_name ^ "_" ^ string_of_int i)
(1 upto length (flat (tl descr))));
val def_names = map (fn i => big_size_name ^ "_def_" ^ string_of_int i)
(1 upto length recTs);
val plus_t = Const ("op +", [HOLogic.natT, HOLogic.natT] ---> HOLogic.natT);
fun make_sizefun (_, cargs) =
let
val Ts = map (typ_of_dtyp descr' sorts) cargs;
val k = length (filter is_rec_type cargs);
val t = if k = 0 then HOLogic.zero else
foldl1 (app plus_t) (map Bound (k - 1 downto 0) @ [HOLogic.mk_nat 1])
in
foldr (fn (T, t') => Abs ("x", T, t')) (Ts @ replicate k HOLogic.natT, t)
end;
val fs = flat (map (fn (_, (_, _, constrs)) => map make_sizefun constrs) descr');
val fTs = map fastype_of fs;
val thy' = thy1 |>
Theory.add_consts_i (map (fn (s, T) =>
(Sign.base_name s, T --> HOLogic.natT, NoSyn))
(drop (length (hd descr), size_names ~~ recTs))) |>
Theory.add_defs_i (map (fn (((s, T), def_name), rec_name) =>
(def_name, Logic.mk_equals (Const (s, T --> HOLogic.natT),
list_comb (Const (rec_name, fTs @ [T] ---> HOLogic.natT), fs))))
(size_names ~~ recTs ~~ def_names ~~ reccomb_names)) |>
parent_path flat_names;
val size_def_thms = map (get_axiom thy') def_names;
val rewrites = size_def_thms @ map mk_meta_eq primrec_thms;
val size_thms = map (fn t => prove_goalw_cterm rewrites
(cterm_of (sign_of thy') t) (fn _ => [rtac refl 1]))
(DatatypeProp.make_size new_type_names descr sorts thy')
in
(thy' |> Theory.add_path big_name |>
PureThy.add_tthmss [(("size", map Attribute.tthm_of size_thms), [])] |>
Theory.parent_path,
size_thms)
end;
(************************* additional theorems for TFL ************************)
fun prove_nchotomys new_type_names descr sorts casedist_thms thy =
let
val _ = message "Proving additional theorems for TFL...";
fun prove_nchotomy (t, exhaustion) =
let
(* For goal i, select the correct disjunct to attack, then prove it *)
fun tac i 0 = EVERY [TRY (rtac disjI1 i),
hyp_subst_tac i, REPEAT (rtac exI i), rtac refl i]
| tac i n = rtac disjI2 i THEN tac i (n - 1)
in
prove_goalw_cterm [] (cterm_of (sign_of thy) t) (fn _ =>
[rtac allI 1,
exh_tac (K exhaustion) 1,
ALLGOALS (fn i => tac i (i-1))])
end;
val nchotomys =
map prove_nchotomy (DatatypeProp.make_nchotomys descr sorts ~~ casedist_thms)
in
(store_thms "nchotomy" new_type_names nchotomys thy, nchotomys)
end;
fun prove_case_congs new_type_names descr sorts nchotomys case_thms thy =
let
fun prove_case_cong ((t, nchotomy), case_rewrites) =
let
val (Const ("==>", _) $ tm $ _) = t;
val (Const ("Trueprop", _) $ (Const ("op =", _) $ _ $ Ma)) = tm;
val cert = cterm_of (sign_of thy);
val nchotomy' = nchotomy RS spec;
val nchotomy'' = cterm_instantiate
[(cert (hd (add_term_vars (concl_of nchotomy', []))), cert Ma)] nchotomy'
in
prove_goalw_cterm [] (cert t) (fn prems =>
let val simplify = asm_simp_tac (HOL_ss addsimps (prems @ case_rewrites))
in [simp_tac (HOL_ss addsimps [hd prems]) 1,
cut_facts_tac [nchotomy''] 1,
REPEAT (etac disjE 1 THEN REPEAT (etac exE 1) THEN simplify 1),
REPEAT (etac exE 1) THEN simplify 1 (* Get last disjunct *)]
end)
end;
val case_congs = map prove_case_cong (DatatypeProp.make_case_congs
new_type_names descr sorts thy ~~ nchotomys ~~ case_thms)
in
(store_thms "case_cong" new_type_names case_congs thy, case_congs)
end;
end;
|
__label__pos
| 0.905695 |
Home » Java » Core Java » Functional Programming with Java 8 Lambda Expressions – Monads
About Debasish Ray Chawdhuri
Functional Programming with Java 8 Lambda Expressions – Monads
What is a monad?: A monad is a design pattern concept used in mostly functional programming languages like lisp or in the modern world clojure or scala. (I would in fact copy a few things from scala.) Now why is it becoming important in java? Because java has got its new lambda feature from version 8. Lambda or closure is a functional programming feature. It allowes you to use code blocks as variables and lets you pass it around as such. I have discussed about Java’s ‘Project Lambda’ in my previous article What’s Cooking in Java 8 – Project Lambda. You can now try it out on JDK 8 preview release available in here. Now could we do monads before Java 8? Sure, after all Java’s lambda is semantically just another way of implementing an interface (Its not actually that because the compiler knows where its being used), but it would be a lot messier code which would pretty much kill its utility.
Now, rather than describing an abstract and seemingly meaningless idea to you, let me set up a use-case in Java as it would be without monads.
Pesky null checks: If you have written any non-trivial (like Hello-World) java program, you have probably done some null checks. They are like the necessary evil of programming, you cannot do without them, but they make your program cluttered with noise. Lets take the following example with a set of java data objects. Notice I have not used getters or setter which are anti-patterns anyway.
public static class Userdetails{
public Address address;
public Name name;
}
public static class Name{
public String firstName;
public String lastName;
}
public static class Address{
public String houseNumber;
public Street street;
public City city;
}
public static class Street{
public String name;
}
public static class City{
public String name;
}
Now say you want to access the street name from a UserDetails user with the possibility of any property being null. Without monads, you would probably write a code like the following.
if(user == null )
return null;
else if(user.address == null)
return null;
else if(user.address.street == null)
return null;
else
return user.address.street.name;
It ideally should be a one-liner. We have so much noise around the code we really care about. So lets see how we can fix that. Let create a class Option that represents an optional value. And lets then have a map method that will run a lambda on its wrapped value and return another option. If the wrapped value is null, it will return an Option containing null without processing the lambda, thus avaoiding a null pointer exception. Note that the map method needs to actually take a lambda as a parameter, but we will need to create an interface SingleArgExpression to support that.
SingleArgExpression.java
package com.geekyarticles.lambda;
public interface SingleArgExpression<P, R> {
public R function(P param);
}
Option.java
package com.geekyarticles.javamonads;
import com.geekyarticles.lambda.
public class Option<T> {
T value;
public Option(T value){
this.value = value;
}
public <E> Option<E> map(SingleArgExpression<T,E> mapper){
if(value == null){
return new Option<E>(null);
}else{
return new Option<E>(mapper.function(value));
}
}
@Override
public boolean equals(Object rhs){
if(rhs instanceof Option){
Option o = (Option)rhs;
if(value == null)
return (o.value==null);
else{
return value.equals(o.value);
}
}else{
return false;
}
}
@Override
public int hashCode(){
return value==null? 0 : value.hashCode();
}
public T get(){
return value;
}
}
OptionExample.java
package com.geekyarticles.javamonads.examples;
import com.geekyarticles.javamonads.
public class OptionExample{
public static class Userdetails{
public Option<Address> address = new Option<>(null);
public Option<Name> name = new Option<>(null);
}
public static class Name{
public Option<String> firstName = new Option<String>(null);
public Option<String> lastName = new Option<String>(null);
}
public static class Address{
public Option<String> houseNumber;
public Option<Street> street;
public Option<City> city;
}
public static class Street{
public Option<String> name;
}
public static class City{
public Option<String> name;
}
public static void main(String [] args){
Option<Userdetails> userOpt = new Option<>(new Userdetails());
//And look how simple it is now
String streetName = userOpt.flatMap(user -> user.address).map(address -> address.street).map(street -> street.name).get();
System.out.println(streetName);
}
}
So now, basically the idea is to return an Option whenever a method has the chance of returning null. It will make sure that the consumer of the method understands that the value can be null and also lets the consumer move past null checks implicitly as shown. Now that we are returning Option from all our methods that might have to return null, its likely that the expressions inside the map would also have Option as return type. To avoid calling get() every time, we can have a similar method flatMap that is same as map, except it accepts an Option as a return type for the lambda that is passed to it.
public <E> Option<E> flatMap(SingleArgExpression<T, Option<E>> mapper){
if(value == null){
return new Option<E>(null);
}
return mapper.function(value);
}
The last method I would talk about is filter. It will let us put an if condition in the map chain, so that a value is obtained only when a condition is true. Note that this is also null-safe. The use of filter is not obvious in this particular monad, but we will see its usage later. The following is a sample where all nullable fields have been upgraded to Option and hence flatMap is used instread of map.
Option.java
package com.geekyarticles.javamonads;
import com.geekyarticles.lambda.
public class Option<T> {
T value;
public Option(T value){
this.value = value;
}
public <E> Option<E> map(SingleArgExpression<T,E> mapper){
if(value == null){
return new Option<E>(null);
}else{
return new Option<E>(mapper.function(value));
}
}
public <E> Option<E> flatMap(SingleArgExpression<T, Option<E>> mapper){
if(value == null){
return new Option<E>(null);
}
return mapper.function(value);
}
public Option<T> filter(SingleArgExpression<T, Boolean> filter){
if(value == null){
return new Option<T>(null);
}else if(filter.function(value)){
return this;
}else{
return new Option<T>(null);
}
}
@Override
public boolean equals(Object rhs){
if(rhs instanceof Option){
Option o = (Option)rhs;
if(value == null)
return (o.value==null);
else{
return value.equals(o.value);
}
}else{
return false;
}
}
@Override
public int hashCode(){
return value==null? 0 : value.hashCode();
}
public T get(){
return value;
}
}
OptionExample.java
package com.geekyarticles.javamonads.examples;
import com.geekyarticles.javamonads.
public class OptionExample{
public static class Userdetails{
public Option<Address> address = new Option<>(null);
public Option<Name> name = new Option<>(null);
}
public static class Name{
public Option<String> firstName = new Option<String>(null);
public Option<String> lastName = new Option<String>(null);
}
public static class Address{
public Option<String> houseNumber;
public Option<Street> street;
public Option<City> city;
}
public static class Street{
public Option<String> name;
}
public static class City{
public Option<String> name;
}
public static void main(String [] args){
//This part is just the setup code for the example to work
Option<Userdetails> userOpt = new Option<>(new Userdetails());
userOpt.get().address = new Option<>(new Address());
userOpt.get().address.get().street=new Option<>(new Street());
userOpt.get().address.get().street.get().name = new Option<>("H. Street");
//And look how simple it is now
String streetName = userOpt.flatMap(user -> user.address).flatMap(address -> address.street).flatMap(street -> street.name).get();
System.out.println(streetName);
}
}
Collections and Monads: Monads can be useful for Collection frameworks as well. Although the best way would be for every collection class to be monads themselves for best performance (Which they might become in future), currently we can wrap them up. It also creates a problem of having to break the type cheking system, because we do not know the generic return type of the builder beforehand.
NoArgExpression.java
package com.geekyarticles.lambda;
public interface NoArgExpression<R> {
public R function();
}
SingleArgExpression.java
package com.geekyarticles.lambda;
public interface SingleArgExpression<P, R> {
public R function(P param);
}
CollectionMonad.java
package com.geekyarticles.javamonads;
import com.geekyarticles.lambda.
import java.util.Collection;
import java.util.ArrayList;
import java.util.Arrays;
public class CollectionMonad<T> {
Collection<T> value;
NoArgExpression<Collection> builder;
public CollectionMonad(Collection<T> value, NoArgExpression<Collection> builder){
this.value = value;
this.builder = builder;
}
public CollectionMonad(T[] elements){
this.value = new ArrayList<T>(elements.length);
this.value.addAll(Arrays.asList(elements));
this.builder = () -> new ArrayList();
}
@SuppressWarnings("unchecked")
public <E> CollectionMonad<E> map(SingleArgExpression<T,E> mapper){
Collection<E> result = (Collection<E>)builder.function();
for(T item:value){
result.add(mapper.function(item));
}
return new CollectionMonad<E>(result, builder);
}
//What flatMap does is to flatten out the CollectionMonad returned by the lambda that is provided
//It really shrinks a nested loop.
@SuppressWarnings("unchecked")
public <E> CollectionMonad<E> flatMap(SingleArgExpression<T, CollectionMonad<E>> mapper){
Collection<E> result = (Collection<E>)builder.function();
for(T item:value){
CollectionMonad<E> forItem = mapper.function(item);
for(E e : forItem.get()){
result.add(e);
}
}
return new CollectionMonad<E>(result, builder);
}
@SuppressWarnings("unchecked")
public CollectionMonad<T> filter(SingleArgExpression<T, Boolean> filter){
Collection<T> result = (Collection<T>)builder.function();
for(T item:value){
if(filter.function(item)){
result.add(item);
}
}
return new CollectionMonad<T>(result, builder);
}
public Collection<T> get(){
return value;
}
@Override
public String toString(){
return value.toString();
}
}
ListMonadTest.java
package com.geekyarticles.javamonads.examples;
import com.geekyarticles.javamonads.
import java.util.
public class ListMonadTest {
public static void main(String [] args){
mapExample();
flatMapExample();
filterExample();
}
public static void mapExample(){
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(1);
list.add(210);
list.add(130);
list.add(2);
CollectionMonad<Integer> c = new CollectionMonad<>(list, () -> new ArrayList());
//Use of map
System.out.println(c.map(v -> v.toString()).map(v -> v.charAt(0)));
System.out.println();
}
public static void flatMapExample(){
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(1);
list.add(210);
list.add(130);
list.add(2);
CollectionMonad<Integer> c = new CollectionMonad<>(list, () -> new ArrayList());
//Use of flatMap
System.out.println(c.flatMap(v -> new CollectionMonad<Integer>(Collections.nCopies(v,v), () -> new ArrayList())));
System.out.println();
}
public static void filterExample(){
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(1);
list.add(210);
list.add(130);
list.add(2);
CollectionMonad<Integer> c = new CollectionMonad<>(list, () -> new ArrayList());
//Use of flatMap and filter
System.out.println(c.flatMap(v -> new CollectionMonad<Integer>(Collections.nCopies(v,v), () -> new ArrayList())).filter(v -> v<=100));
System.out.println();
}
}
At the first glance, it might appear that using flatmap is quite a bit of trouble here because we need to create a CollectionMonad from the lambda. But if you think about the equivalent code with a nested for loop, it still is pretty neat.
Streams and Monads: Well at this point you might be thinking of InputStream(s), but we would discuss something more general than this. A stream is basically a sequence which is possibly infinite. It can be created say for example using a formula, or indeed an InputStream. We will have Streams with hasNext() and next() methods just like Iterator. In fact we will use Iterator interface so we can use the enhanced for loop. But we will also make the stream monads. This case is particularly interesting because streams are possibly infinite, hence the map must return a stream that lazily processes the lambda. In our example, we would create a specialized random number generator with specific distribution. Normally all values are equally probable. But we can change that by mapping. Let see the example to better understand.
Let’s create a generic Stream that can wrap an arbitrary Iterator. That way we can use it existing collection framework as well.
Stream.java
package com.geekyarticles.javamonads;
import java.util.Iterator;
import com.geekyarticles.lambda.
import java.util.NoSuchElementException;
public class Stream<T> implements Iterable<Option<T>>, Iterator<Option<T>>{
//Provides a map on the underlying stream
private class MapperStream<T,R> extends Stream<R>{
private Stream<T> input;
private SingleArgExpression<T, R> mapper;
public MapperStream(Stream<T> input, SingleArgExpression<T, R> mapper){
this.input = input;
this.mapper = mapper;
}
@Override
public Option<R> next(){
if(!hasNext()){
//This is to conform to Iterator documentation
throw new NoSuchElementException();
}
return input.next().map(mapper);
}
@Override
public boolean hasNext(){
return input.hasNext();
}
}
//Provides a flatMap on the underlying stream
private class FlatMapperStream<T,R> extends Stream<R>{
private Stream<T> input;
private SingleArgExpression<T, Stream<R>> mapper;
private Option<Stream<R>> currentStream = new Option<>(null);
public FlatMapperStream(Stream<T> input, SingleArgExpression<T, Stream<R>> mapper){
this.input = input;
this.mapper = mapper;
}
@Override
public Option<R> next(){
if(hasNext()){
return currentStream.flatMap(stream -> stream.next());
}else{
//This is to conform to Iterator documentation
throw new NoSuchElementException();
}
}
@Override
public boolean hasNext(){
if(currentStream.map(s -> s.hasNext()) //Now Option(false) and Option(null) should be treated same
.equals(new Option<Boolean>(Boolean.TRUE))){
return true;
}else if(input.hasNext()){
currentStream=input.next().map(mapper);
return hasNext();
}else{
return false;
}
}
}
//Puts a filter on the underlying stream
private class FilterStream<T> extends Stream<T>{
private Stream<T> input;
private SingleArgExpression<T, Boolean> filter;
private Option<T> next = new Option<>(null);
public FilterStream(Stream<T> input, SingleArgExpression<T, Boolean> filter){
this.input = input;
this.filter = filter;
updateNext();
}
public boolean hasNext(){
return next != null;
}
//We always keep one element calculated in advance.
private void updateNext(){
next = input.hasNext()? input.next(): new Option<T>(null);
if(!next.map(filter).equals(new Option<Boolean>(Boolean.TRUE))){
if(input.hasNext()){
updateNext();
}else{
next = null;
}
}
}
public Option<T> next(){
Option<T> res = next;
updateNext();
if(res == null){
throw new NoSuchElementException();
}
return res;
}
}
protected Iterator<T> input;
public Stream(Iterator<T> input){
this.input=input;
}
//Dummy constructor for the use of subclasses
protected Stream(){
}
@Override
public boolean hasNext(){
return input.hasNext();
}
@Override
public Option<T> next(){
return new Option<>(input.next());
}
@Override
public void remove(){
throw new UnsupportedOperationException();
}
public <R> Stream<R> map(SingleArgExpression<T,R> mapper){
return new MapperStream<T, R>(this, mapper);
}
public <R> Stream<R> flatMap(SingleArgExpression<T, Stream<R>> mapper){
return new FlatMapperStream<T, R>(this, mapper);
}
public Stream<T> filter(SingleArgExpression<T, Boolean> filter){
return new FilterStream<T>(this, filter);
}
public Iterator<Option<T>> iterator(){
return this;
}
}
StreamExample.java
package com.geekyarticles.javamonads.examples;
import com.geekyarticles.javamonads.
import java.util.
public class StreamExample{
public static void main(String [] args){
iteratorExample();
infiniteExample();
}
static void iteratorExample(){
System.out.println("iteratorExample");
List<Integer> l = new ArrayList<>();
l.addAll(Arrays.asList(new Integer[]{1,2,5,20,4,51,7,30,4,5,2,2,1,30,9,2,1,3}));
Stream<Integer> stream = new Stream<>(l.iterator());
//Stacking up operations
//Multiply each element by 10 and only select if less than 70
//Then take the remainder after dividing by 13
for(Option<Integer> i : stream.map(i -> i*10).filter(i -> i < 70).map(i -> i%13)){
System.out.println(i.get());
}
System.out.println();
}
static void infiniteExample(){
System.out.println("infiniteExample");
Iterator<Double> randomGenerator = new Iterator<Double>(){
@Override
public Double next(){
return Math.random();
}
@Override
public boolean hasNext(){
//Infinite iterator
return true;
}
public void remove(){
throw new UnsupportedOperationException();
}
};
Stream<Double> randomStream = new Stream<>(randomGenerator);
//Now generate a 2 digit integer every second, for ever.
for(Option<Integer> val:randomStream.map(v -> (int)(v*100))){
System.out.println(val.get());
try{
Thread.sleep(1000);
}catch(InterruptedException ex){
ex.printStackTrace();
}
}
}
}
This example is fairly complex, so spend some time reading this. However, the Stream class needs to be created only once. Once its there, it can used to wrap any Iterator and it will give you all the monadic features for free.
In my next post, I would explain some more monads.
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
3 comments
1. A critique here. I don’t think there’s enough explanation of what exactly a monad is here. Your intro doesn’t go any deeper than to say it’s a functional programming design pattern. In your code examples or surrounding text, I don’t see anything which states “This is a monad.” I only see some classes that happen to be named [Something]Monad.
So despite your good intentions, I don’t see anything to show how nomads (which are not clearly defined) change Java programming. I believe this could help with better code comments around the examples you’re trying to illustrate, highlighting them from the noise of structural Java syntax.
It would also be helpful if you showed some of the output from your examples so that a user can appreciate the result without having to compile and run the test themselves.
2. Dear Debasish Ray Chawdhuri!
There are neither monads nor monad tutorial. This is just flatmapping which is just a method of the monad typeclass.
Leave a Reply
Your email address will not be published. Required fields are marked *
*
six × 1 =
You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Do you want to know how to develop your skillset and become a ...
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.
THANK YOU!
Close
|
__label__pos
| 0.645235 |
Question #ca917
1 Answer
May 4, 2017
detail in explanation
Explanation:
1. #n=1 #
#1=1/4(5^1-1)# correspond
2. let #n=k#
#1+5+5^2+5^3+...+5^(k-1)=1/4(5^k-1)# is true
3. if #n=k+1#
#1+5+5^2+5^3+...+5^(k-1)+5^(k+1-1)=1/4(5^k-1)+5^k#
then observe the right pattern temporarily
#=>1/4*5^k+5^k-1/4#
#=>(5/4)*5^k-1/4#
#=>(1/4)*5*5^k-1/4#
#=>1/4*(5^(k+1)-1)#
so
#1+5+5^2+5^3+...+5^(k-1)+5^(k+1-1)=1/4*(5^(k+1)-1)#
is also true
conclusion:
by mathematical induction , #1+5+5^2+...+5^(n-1)=1/4(5^n-1) #
is true for all positive integer n
|
__label__pos
| 0.99976 |
Stack in Java
Prev Tutorial Next Tutorial
Stack in Java
Stack is one of the sub-class of Vector class so that all the methods of Vector are inherited into Stack.
The concept of Stack of Data Structure is implemented in java and develop a pre-defined class called Stack.
stack
Stack Important Points
• Stack class allow to store Heterogeneous elements.
• Stack work on Last in First out (LIFO) manner.
• Stack allow to store duplicate values.
• Stack class is Synchronized.
• Initial 10 memory location is create whenever object of stack is created and it is re-sizable.
• Stack also organizes the data in the form of cells like Vector.
• Stack is one of the sub-class of Vector.
Creating a Stack is nothing but creating an object of Stsck Class.
Syntax
Stack s=new Stack();
Constructors of Stack
• Stack(): is used for creating an object of Stack.
Syntax
Stack s=new Stack();
Methods of Stack
• public boolean empty(): is used for returns true provided Stack is empty.It returns false in case of Stack is non-empty.
• public void push (Object): is used for inserting the elements into the Stack.
• public Object pop(): is used for removing Top Most elements from the Stack.
• public Object peek(): is used for retrieving Top Most element from the Stack.
• public int search(Object): is used for searching an element in the Stack.If the element is found then it returns Stack relative position of that element otherwise it returns -1, -1 indicates search is unsuccessful and element is not found.
Example of Stack add Elements to Stack
import java.util.*;
class StackDemo
{
public static void main(String args[])
{
Stack s=new Stack();
//add the data to s
s.push(10);
s.push(20);
s.push(30);
s.push(40);
System.out.println("Stack data: "+s);// [10,20,30,40]
}
}
Output
Stack data: [10,20,30,40]
Example of Stack to add and remove Elements from Stack
import java.util.*;
class StackDemo
{
public static void main(String args[])
{
Stack s=new Stack();
// Add the data to s
s.push(10);
s.push(20);
s.push(30);
s.push(40);
System.out.println("Stack elements: "+s); //[10,20,30,40]
// Remove the top most element
System.out.println("Delete element: "+s.pop()); //40
System.out.println("Stack elements after pop: "+s);// [10,20,30]
}
}
Output
Stack elements: [10,20,30,40]
Delete element: 40
Stack elements after pop: [10,20,30]
Complete Example of Stack
import java.util.*;
class StackDemo
{
public static void main(String args[])
{
Stack s=new Stack();
System.out.println("content of s="+s); //[]
System.out.println("size of s="+s.size()); //10
System.out.println("Is empty?="s.empty()); //true
//add the data to s
s.push(10);
s.push(20);
s.push(30);
s.push(40);
System.out.println("content of s="+s); //[10,20,30,40]
System.out.println("size of s="+s.size()); //4
System.out.println("Is s empty ?=s.empty()"); //false
//remove the top most element
System.out.println("delete element="+s.pop()); //40
System.out.println("content of s after pop="+s);// [10,20,30]
//extract the top most element
System.out.println("top most element="+s.peek()); //30
System.out.println("content of s after peek="+s); //[10 20 30]
//Search the element 10 and 100
int srp=s.search(10);
System.out.println("stack relative pos.of 10 is="+srp); //3
int srp1=s.search(100);
System.out.println("stack relative pos.of 100 is="+srp1); //-1
}
}
Output
Prev Tutorial Next Tutorial
Download Projects
Advertisements
|
__label__pos
| 0.719332 |
6
I would like to place some LaTeX math code in the columns of a file to be read by pgfplotstable. Unlike How to use underscores with pgfplotstable?, I would like the columns to be formatted so LaTeX will interpret the subscripts and symbols that it contains. For example, I have a data file that looks like:
{Time} {$\theta$} {Fit to $C_a \tan 3\theta$}
0 0.2 0.195
...
Every time I try to read a file like this with pgfplotstable, I get an error:
! Missing \endcsname inserted.
<to be read again>
\mathop
l.101 }
^^M
Is it possible to have the formatting embedded in the column headings of a data file? If so, how?
• In what context to you want to use the LaTeX code contained in the tables? In a table printed using \pgfplotstabletypeset, or as a legend in a PGFplots plot? – Jake Apr 18 '12 at 15:05
• @Jake: Let's say I'd like to use it in a legend. I figure if I change how the column is generated, I'm more likely to change the column name than the LaTeX code generating the plot. – sappjw Apr 18 '12 at 16:18
7
pgfplotstable assumes that column names do not contain expandable material.
Its way of dealing with "display names" is to provide the display names explicitly using the column name key which is used during \pgfplotstabletypeset.
Protecting expandable material in column names is unsupported. It is unlikely that pgfplotstable will support such protection automatically in the future (because protection cannot be done during \edef which is a common use case of access to columns).
So, the answer is: no, this is generally unsupported. Period.
You can hack the processing such that it does basic escaping - on your own risk. You should skip this section unless you know what you are doing and you know why you are doing it. Do not blame me. This here would work if you wanted to typeset the table:
\let\ESCAPE=\string
\pgfplotstabletypeset[
every head row/.style={before row={\global\let\ESCAPE=\relax}},
]{
{Time} {$\ESCAPE\theta$} {Fit to $C_a \ESCAPE\tan 3\ESCAPE\theta$}
0 0.2 0.195
}
It is based on the fact that \string\macro yields the string sequence "\ m a c r o" . Clearly, you would need to change the header of your input table for such an approach.
• Would \unexpanded help? – egreg Apr 19 '12 at 21:55
• @egreg thanks for the hint. It does not seems so (and neither does \noexpand). – Christian Feuersänger Apr 19 '12 at 22:08
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged or ask your own question.
|
__label__pos
| 0.835888 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.